in reply to Re^4: Short form (ternary) if else
in thread Short form (ternary) if else

Both will work (i.e. run without error) but the first form won't do what you're expecting due to operator precedence. The second form is preferable anyway because it is shorter, less complicated and easier to read. Take a look at the perlop manpage - under Conditional Operator for an explanation.

I suggest you write some test code for yourself rather than just asking whether this or that code will or won't work. You can do this sort of thing on the commandline:

ken@ganymede: ~/tmp $ perl -Mstrict -Mwarnings -E 'my $x = 1 ? 1 : 0; say $x;' 1 ken@ganymede: ~/tmp $ perl -Mstrict -Mwarnings -E 'my $x; 1 ? $x=1 : $x=0; say $x;' 0 ken@ganymede: ~/tmp $ perl -Mstrict -Mwarnings -E 'my $x; 1 ? ($x=1) : ($x=0); say $x;' 1 ken@ganymede: ~/tmp $

-- Ken

Replies are listed 'Best First'.
Re^6: Short form (ternary) if else
by Riales (Hermit) on Feb 08, 2012 at 23:20 UTC
    I'm surprised by this result:
    ken@ganymede: ~/tmp $ perl -Mstrict -Mwarnings -E 'my $x; 1 ? $x=1 : $x=0; say $x;' 0
    Do you know why $x becomes 0?
      operator precedence; ? : binds tighter than =. So

      1 ? $x=1 : $x=0

      really means

      (1 ? $x=1 : $x)=0

      which is then the same as

      ($x=1)=0

      which is why $x becomes 0.
      You can use assignments within ? :, you just need to parenthesize them

      1 ? $x=1 : ($x=0)

        Ah, perfect explanation. I knew it had something to do with operator precedence but I just couldn't work out quite where it was happening. Thank you, good sir!

      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;' 0

      The link I gave above (perlop manpage - under Conditional Operator) has a fuller description.

      -- Ken

        Thanks all! I got my question answered and then some. Good discussion.