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?
both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Nope you cannot do that.
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With