Assignment of the Perl statement operator inside ternary problems

This piece of Perl code in my program gives the wrong result.

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

Regardless of the value of $condition , the output is always 3, how did it happen?

+41
conditional-operator operator-precedence perl
Aug 12 '08 at 16:03
source share
5 answers

This is explained in the Perl documentation .

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, it means ($ a = 2) = 3, giving $ a = 3

When $ condition is false, it means ($ a) = 3, giving $ a = 3

The right way to write this

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

We were bitten by this at work, so I post here, hoping others will find it useful.

+79
Aug 12 '08 at 16:05
source share

Once you have a suspicion that you may be suffering from priority issues, the trick is to understand what, in Perl’s opinion, you had in mind:

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

In your case, this will show you:

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

... at this moment you should say "oh, that explains!"

+40
Sep 05 '08 at 21:41
source share

Just to extend the previous answer ... If for some reason the assignments should be part of a conditional expression, you should write it like this:

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

This would be useful if you would assign different variables based on the condition.

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

And if you select a variable, but at the same time assign the same thing, regardless of what you could do:

 ($condition ? $a : $b) = 3; 
+21
Aug 22 '08 at 4:58
source share

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); } 
+4
Sep 16 '08 at 15:43
source share

One sentence of Tithonia to answer above:

If you want to assign different values ​​to the same variable, this might be better (path to the copy book):

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

0
Sep 04 '08 at 12:54
source share



All Articles