Reputation: 55
I am simply trying to increment a value within the ternary operator's 'true' section when the test()
subroutine returns true, but set it back to zero when the it returns false.
I don't understand why the following code doesn't work:
use warnings;
use strict;
my $int = 5;
test() ? $int += 1 : $int = 0;
print "$int\n"; # => prints "0"
sub test {
return 1; #return true
}
Upvotes: 3
Views: 331
Reputation: 674
The answer is fairly simple: perl's ternary operator is assignable
In particular, your code really means this:
(test() ? $int += 1 : $int) = 0;
You may recall that the result of an assignment is the variable being assigned to; this means that the following happens:
This code will work how you want:
test() ? ($int++) : ($int = 0);
Or this:
$int += test() ? 1 : -$int; #If you want to be cute
Upvotes: 2