in reply to Evaluating the condition ($x)
Better use if-then-else construct instead, if you don't want to take advantage, but execute complex code.
my $z; if ($x) {$z = "true\n"} else {$z = "false\n"}
But for my taste it's better written as
my $z = $x ? "true\n" : "false\n";
Your trap is even documented in perlop#Conditional-Operator
Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:
$x % 2 ? $x += 10 : $x += 2Really means this:
(($x % 2) ? ($x += 10) : $x) += 2Rather than this:
($x % 2) ? ($x += 10) : ($x += 2)That should probably be written more simply as:
$x += ($x % 2) ? 10 : 2;
Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery
¹) See also WP : "The conditional operator's most common usage is to make a terse simple conditional assignment statement. "
²) tho I don't think I ever took advantage of the lvalue aspect, to create a LHS
DB<22> 1 ? $a : $b = 1 DB<23> x $a,$b 0 1 1 undef DB<24> 0 ? $a : $b = 2 DB<25> x $a,$b 0 1 1 2
(I'd certainly use parentheses in productive code.)
|
|---|