in reply to
Re^5: Short form (ternary) if else
in thread Short form (ternary) if else
I'm surprised by this result:
$ perl -Mstrict -Mwarnings -E 'my $x; 1 ? $x=1 : $x=0; say $x;'
1 ? $x=1 : $x=0
(1 ? $x=1 : $x)=0
which is then the same as
which is why $x becomes 0.
You can use assignments within ? :, you just need to parenthesize them
1 ? $x=1 : ($x=0)
Adding parentheses to the second statement to show precedence, we get:
( 1 ? ( $x=1 ) : $x ) = 0;
As the 2nd and 3rd arguments are lvalues, you can assign to the ternary operator. As the first argument (1) is TRUE, the assignment becomes:
( $x=1 ) = 0;
Which effectively boils down to:
$ perl -Mstrict -Mwarnings -E 'my $x; ($x = 1) = 0; say $x;'
The link I gave above (perlop manpage - under Conditional Operator) has a fuller description.
No recent polls found