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.
By rote learning.
Via Genetic memory.
It's provided by my firmware.
I just remember them.
Thirty days hath September
My computer gets it right, usually.
I just ask someone else.
Someone punches me on the first of the month.
Results (220 votes),