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 $condition is, the output is always 3, how come?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is explained in the Perl documentation.
Because of Perl operator precedence the statement is being parsed as
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
We got bitten by this at work, so I am posting here hoping others will find it useful.