Assignment inside Perl ternary conditional operator problems

This is explained in the Perl documentation.

Because of Perl operator precedence the statement is being parsed as

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

Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.

When $condition is true this means ($a=2)=3 giving $a=3

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

The correct way to write this is

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

We got bitten by this at work, so I am posting here hoping others will find it useful.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)