Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (12)
As of 2016-09-26 19:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:







    Results (489 votes). Check out past polls.