Autoincrement and Autodecrement

You’ll often want a scalar variable to count up or down by one. Since these are frequent constructs, there are shortcuts for them like nearly everything else we do frequently.

The autoincrement operator (++) adds one to a scalar variable as the same operator in C and similar languages:

    my $bedrock = 42;
    $bedrock++;  # add one to $bedrock; it's now 43

Like other ways of adding one to a variable, the scalar will be created if necessary:

    my @people = qw{ fred barney fred wilma dino barney fred pebbles };
    my %count;                     # new empty hash
    $count{$_}++ foreach @people;  # creates new keys and values as needed

The first time through that foreach loop, $count{$_} is incremented. That’s $count{"fred"}, which goes from undef (since it didn’t previously exist in the hash) up to 1. The next time through the loop, $count{"barney"} becomes 1; after that, $count{"fred"} becomes 2. Each time through the loop, one element in %count is incremented and possibly created as well. After that loop is done, $count{"fred"} is 3. This provides a quick and easy way to see which items are in a list and how many times each one appears.

Similarly, the autodecrement operator (--) subtracts one from a scalar variable:

    $bedrock--;  # subtract one from $bedrock; it's 42 again

The Value of Autoincrement

You can fetch the value of a variable and change that value at the same time. Put the ++ operator in front of the variable name to increment the variable first and then fetch its value. This is ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.