Assignment inside Perl ternary conditional operator problems

前端 未结 5 1672
一生所求
一生所求 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:22

    Just to extend the previous answer... If, for whatever reason, the assignments need to be part of the conditional, you'd want to write it thusly:

    $condition ? ($a=2) : ($a=3);
    

    This would be useful if you're assigning to different variables based on the condition.

    $condition ? ($a=2) : ($b=3);
    

    And if you're choosing the variable, but assigning the same thing no matter what, you could even do this:

    ($condition ? $a : $b) = 3;
    

提交回复
热议问题