http://www.perlmonks.org?node_id=758668

I am always tripping up over this, and like betterworld says, parentheses are the answer. I believe this also works, and may be slightly easier to get your head around/remember (it is for me anyway).
```(\$condition) ? (\$a=2) : (\$a=3);

btw from previous experience, I found it quite difficult to super search or google for advice on this construct, as most search engines do not recognise most punctuation, and I for one did not know it was called 'ternary ?'.

update: p.s. in response to linuxer, say you wanted to do \$condition ? \$a=2 : \$b=3, would (\$condition) ? (\$a=2) : (\$b=3) then be the correct/advisible way to do it?

cheers
why_bird
........
Those are my principles. If you don't like them I have others.
-- Groucho Marx
.......

Replies are listed 'Best First'.
Re^2: Why does the Perl conditional operator not do what I expect?
by AnomalousMonk (Bishop) on Apr 20, 2009 at 13:01 UTC
say you wanted to do
\$condition ? \$a=2 : \$b=3
would
(\$condition) ? (\$a=2) : (\$b=3)
then be the correct/advisible way to do it?
It would be one way to do it with a ternary operator. Another way is shown below. Both are correct (i.e., compile without error). Which is 'advisable' depends on circumstances; I tend to prefer the ternary form below, but
if (\$cond) { \$a = 2 } else { \$b = 3 }
seems the clearest and most advisable of all.
```>perl -wMstrict -le
"my \$cond = shift;
\$a = \$b = 99;
(\$cond ? \$a : \$b) = (\$cond ? 2 : 3);
print qq{a \$a  b \$b};
"
0
a 99  b 3

>perl -wMstrict -le
"my \$cond = shift;
\$a = \$b = 99;
(\$cond ? \$a : \$b) = (\$cond ? 2 : 3);
print qq{a \$a  b \$b};
"
1
a 2  b 99