Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Conditional Operator Confusion

by MonkE (Hermit)
on Nov 29, 2006 at 13:59 UTC ( #586701=note: print w/replies, xml ) Need Help??


in reply to Conditional Operator Confusion

To understand how precedence works in this circumstance, consider the following variation of the OP's code. The assignment operator has enough precendence to end evaluation of the trinary conditional operator, so the conditional operator is simply choosing an "lvalue" for the assignment operator. The parenthesis in the second loop help show what's actually happening.
use strict; use warnings; my $x='baz'; my $y='moo'; for (1..10) { $_>5 ? $x='foo' : $y='bar'; print "x=$x, y=$y\n"; } # re-initialize vars print "----------\n"; $x = 'baz'; $y = 'moo'; # the above loop is functionally equivalent to: for (1..10) { ($_>5 ? $x : $y) = 'bar'; print "x=$x, y=$y\n"; }
Output:
x=baz, y=bar x=baz, y=bar x=baz, y=bar x=baz, y=bar x=baz, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar ---------- x=baz, y=bar x=baz, y=bar x=baz, y=bar x=baz, y=bar x=baz, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar x=bar, y=bar

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://586701]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2017-02-24 20:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?






    Results (363 votes). Check out past polls.