Don't ask to ask, just ask PerlMonks

### Re^3: Conditional Operator Confusion

by Herkum (Parson)
 on Nov 30, 2006 at 16:44 UTC ( #586999=note: print w/replies, xml ) Need Help??

in reply to Re^2: Conditional Operator Confusion
in thread Conditional Operator Confusion

The trinary is much like any other operator, for example ==. Lets try this example,

```my \$result = \$a == \$b
[download]```

Here, you get the result of the == operator, is \$a equal \$b. If they match it returns true, if they don't match it returns false.

The trinary works in a similar manner except you are setting the value returned instead of the implied value of other operators.

```my \$result = \$a == \$b ? 1 : 0;
[download]```

This does the same thing as the first example, except you are explicitly setting the value returned. Does this help?

Replies are listed 'Best First'.
Re^4: Conditional Operator Confusion
by Melly (Hermit) on Nov 30, 2006 at 17:03 UTC

Not really... I'm sure I'm being really dumb here, but I still don't understand, in the following example, why \$x gets set to "FALSE"... just very, very confused...

```1==1?\$x='TRUE':\$y='FALSE';
print "x=\$x\n";
[download]```
Tom Melly, pm@tomandlu.co.uk

The conditional operator has higher precedence than the assignment operator, so
\$c?\$x='TRUE':\$y='FALSE'
is the same as
(\$c?\$x='TRUE':\$y)='FALSE'

The addition operator has higher precedence than the conditional operator, so
\$c?\$x+2:\$y+3
is the same as
\$c?\$x+2:(\$y+3)

If you want to do assignments, use if or add parens. Think of as the conditional operator as an operator that returns something.

Thanks - I think I've finally got it (with some help from the chatterbox as well).

All of which goes to confirm something a coworker once told me..

```Me: What's the precedence in <lang> for these operators?
CW: Who cares? Use brackets - it's easier to read and
you won't get screwed...
```
Tom Melly, pm@tomandlu.co.uk

Log In?
 Username: Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://586999]
help
Chatterbox?
 [Discipulus]: since 2002 I just usewd www.perlmonks.org and good morning Discipulus .oO(maybe a PM discussion?) [Corion]: Discipulus: Yeah, I left a note to the replies mentioning pairsite.com ;)

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2017-09-26 07:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
During the recent solar eclipse, I:

Results (293 votes). Check out past polls.

Notices?