print $foo == 1 ? "hi" : "bye";
-- Randal L. Schwartz, Perl hacker | [reply] [d/l] |
Great answer.
For some reason, I expect that several people will be tempted to transform this into:
print ( $foo == 1 ) ? "hi" : "bye";
and I just wanted to note that doing so will break it, printing either "1" or "" and then returning the value of "hi" to the "void context" unless the print failed. (But if you have warnings enabled, you will get a warning for the above code.)
Two ways to fix this are:
print( ( $foo == 1 ) ? "hi" : "bye" );
print +( $foo == 1 ) ? "hi" : "bye";
-
tye
(but my friends call me "Tye") | [reply] [d/l] [select] |
Hmm. I don't grog why the parens change the precedence. Or
is it that the parens cause a list context, which is gobbled
up by the print?
The parens fix is easy to see. But the '+'? Is it that
the compiler seeks something to add to void? And than
encounters the ternary? Alternatively, if my
list-context-gut-feeling ;-) is correct, it would force
a scalar context to the $foo==1, preventing the print's
greedy behavior. In that cause, the '+' could be replaced
by a '.', isn't it?
Cheers, Jeroen
"We are not alone"(FZ)
| [reply] |