Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment inside Perl ternary conditional operator problems

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?

like image 571
Pat Avatar asked Aug 12 '08 16:08

Pat


People also ask

Can we use assignment operator in ternary operator?

both are fine. invalid lvalue in assignment. which gives error since in C(not in C++) ternary operator cannot return lvalue.

How do you assign a value to a ternary operator?

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.

Can you use a ternary without assignment?

Nope you cannot do that.

How do you write if Elseif and else in ternary operator?

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 ? .


1 Answers

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.

like image 105
Pat Avatar answered Oct 11 '22 06:10

Pat