Question

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
}
Was it helpful?

Solution

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:

  1. test() evaluates to true
  2. $int += 1 is evaluated, incrementing $int to 6
  3. The result of the assignment, $int, is assigned the value 0

This code will work how you want:

test() ? ($int++) : ($int = 0);

Or this:

$int += test() ? 1 : -$int; #If you want to be cute
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top