Due to the priority of the Perl statement, the statement is parsed as:
($condition ? $a = 2 : $a ) = 3 ;
Since the ?: operator produces an assignable result, 3 is assigned the result of the condition.
When $ condition is true, that means $ a = 2 = 3 gives $ a = 3
When $ condition is false, that means $ a = 3 gives $ a = 3
The right way to write this
$a = $condition ? 2 : 3;
In general, you really need to get used to using conventions to do the job, as in the original example - this is what causes Perl to get a write-only reputation.
A good rule of thumb is that conditional expressions refer only to simple meanings and not to expressions with side effects. When you or someone else needs to read this code after eight months, would you prefer it to read like this?
$x < 3 ? foo($x) : bar($y);
Or how is it?
if ($x < 3) { $foo($x); } else { $bar($y); }
raldi Sep 16 '08 at 15:43 2008-09-16 15:43
source share