What are auto-increment and auto-decrement operators in Perl?

The auto-increment and auto-decrement operators in Perl allow us to increment or decrement the value of an integer by 1.

These are unary operators and take just one operand.

The following are the operator representations:

  • Auto-increment : ++
  • Auto-decrement : --

There are two variations of each of these operators: pre-increment/post-increment and pre-decrement/post-decrement.

Pre-increment and pre-decrement

If we append the auto-increment or auto-decrement operators before the variable, the operation is termed as pre-increment or pre-decrement depending on the operator used.

++$x # pre-increment
--$x # pre-decrement

In these operations, the value is updated instantly. Let’s look at an example:

# taking a variable
$x = 10;
$test = ++$x;
print "The value of test (pre-inc) is: $test\n";
print "The value of x is: $x\n";
$y = 10;
$test2 = --$y;
print "The value of test (pre-dec) is: $test2\n";
print "The value of y is: $y\n";

In the above example, we define the variables x and y. The variables are pre-incremented and pre-decremented, respectively, and then associated with a test variable.

The variables are incremented/decremented at the time of association with the test variable, i.e., instantly.

This is why the test variables, x, and y all contain the same values.

The pre-increment & pre-decrement order of events

Post-increment and post-decrement

If we append the auto-increment or auto-decrement operators after the variable, the operation is termed as post-increment or post-decrement depending on the operator used.

$x++ # post increment
$x-- # post decrement

In these operations, the value is stored in a temporary variable and updated after the execution of the current statement. Let’s look at an example:

# taking a variable
$x = 10;
$test = $x++;
print "The value of test (post-inc) is: $test\n";
print "The value of x is: $x\n";
$y = 10;
$test2 = $y--;
print "The value of test (post-dec) is: $test2\n";
print "The value of y is: $y\n";

In the above example, we use the post-increment and post-decrement operators. As a result, the values of x and y are updated after the execution of the assignment statements.

Therefore, the test variables contain the previous values of x and y, while the variables themselves are updated.

The post-increment & post-decrement order of events

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved