Assignment inside Perl ternary conditional operator problems

前端 未结 5 1658
一生所求
一生所求 2021-02-05 00:57

This snippet of Perl code in my program is giving the wrong result.

$condition ? $a = 2 : $a = 3 ;
print $a;

No matter what the value of

5条回答
  •  情话喂你
    2021-02-05 01:26

    Once you have an inkling that you might be suffering from precedence problems, a trick to figure out what Perl thought you meant:

    perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;'
    

    In your case, that'll show you:

    (($condition ? ($a = 2) : $a) = 3);
    print($a);
    -e syntax OK
    

    ...at which point you should be saying "oh, that explains it"!

提交回复
热议问题