Search code examples
perlpostfix-operatorprefix-operator

Perl: Where am I going wrong with postfix/prefix precedence?


The following fragment shows a simple n-perline output procedure.

Two cases are shown, one using prefix ++, the other postfix ++, in a boolean expression.

Since '++' has higher precedence than '==', I expected the results to be the same, but they are not: one does 5 per line, the other 6.

use English;

my @arr = (1,2,3,4,5,6,7,8,9,8,7,6);
my $perline = 5;
my $ndone = 0;

for(@arr) {
    print "  $ARG";
    if(++$ndone == $perline) {
        $ndone = 0;
        print "\n";
    }
}

print "\n---\n";

my $perline = 5;
my $ndone = 0;

for(@arr) {
    print "  $ARG";
    if($ndone++ == $perline) {
        $ndone = 0;
        print "\n";
    }
}

Output:

  1  2  3  4  5
  6  7  8  9  8
  7  6
---
  1  2  3  4  5  6
  7  8  9  8  7  6

Solution

  • This is not about precedence of operations but about what prefix and postfix ++ return. From perldoc perlop:

    "++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable by one before returning the value, and if placed after, increment or decrement after returning the value.

    Essentially you could define these as functions:

    sub prefix_plusplus {
        $_[0] = $_[0] + 1;   # increment value
        return $_[0];        # returns value after increment
    }
    
    sub postfix_plusplus {
        my $before = $_[0];
        $_[0] = $_[0] + 1;  # increment value
        return $before;     # returns value before increment
    }
    
    
    my $x = my $y = 5;
    printf "%d,%d\n", prefix_plusplus($x), postfix_plusplus($y);   #  6,5
    printf "%d,%d\n", $x, $y;                                      #  6,6
    
    # and same thing with the ++ operand
    $x = $y = 5;
    printf "%d,%d\n", ++$x, $y++;                                  #  6,5
    printf "%d,%d\n", $x, $y;                                      #  6,6