Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^6: Short form (ternary) if else

by Riales (Hermit)
on Feb 08, 2012 at 23:20 UTC ( #952621=note: print w/ replies, xml ) Need Help??

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

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?

Comment on Re^6: Short form (ternary) if else
Select or Download Code
Replies are listed 'Best First'.
Re^7: Short form (ternary) if else
by wrog (Friar) on Feb 08, 2012 at 23:32 UTC
    operator precedence; ? : binds tighter than =. So

    1 ? $x=1 : $x=0

    really means

    (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)

      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!
Re^7: Short form (ternary) if else
by kcott (Canon) on Feb 08, 2012 at 23:59 UTC

    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://952621]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2015-11-30 07:39 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (765 votes), past polls