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.
shiny regexes and rules offered by Perl 6
other CPAN module
by looking at it on my monitor
I print it and I read it in spare time
first I convert it into $FORMAT, then I parse it
I hire someone to do it
using my custom module
I write a brand new language to do the task
on the server where I play as human, XML is forbidden
what is XML?
I speak XML natively
I write a new grammar for Perl 6
some other way
Results (413 votes),