Keep It Simple, Stupid 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

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 meditating upon the Monastery: (5)
As of 2018-04-25 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (91 votes). Check out past polls.

Notices?