Advertisement
OK, so I wrote this little script to test an issue I'd been having. Anyone know why the first block prints False, but the second block prints True?
#!/usr/bin/perl -wl
# Ternary Operator
1 == 1 ? $i = "True" : $i = "False";
print $i;
# Traditional if-then
if (1 == 1) {
$i = "True";
} else {
$i = "False";
}
print $i;
#!/usr/bin/perl -wl
# Ternary Operator
1 == 1 ? $i = "True" : $i = "False";
print $i;
# Traditional if-then
if (1 == 1) {
$i = "True";
} else {
$i = "False";
}
print $i;
Advertisement
Advertisement
-
Re: Odd ternary operator results
Mon, September 25, 2006 - 2:27 PMIt's a ternary __operator__, which means it has to have an effect. You aren't using it as an operator. You've used it simply as a test, not as an operator.
The correct syntax would be
$i = (1 == 1) ? "True" : "False";
print $i; -
-
Re: Odd ternary operator results
Mon, September 25, 2006 - 2:40 PMThe following also seem to work :
# Ternary Operator
1 == 1 ? $i = "True" : ($i = "False");
print $i;
==> ??? -
-
Re: Odd ternary operator results
Mon, September 25, 2006 - 3:01 PMHm, so the Ternary operator has higher precedence than the simple = assignment operator
perldoc.perl.org/perlop.ht...ociativity
That may be the root of the issue here.
-
-
Re: Odd ternary operator results
Mon, September 25, 2006 - 4:48 PMOK, that makes sense - thanks!
--Alex
-