Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

10. More Control Structures > Autoincrement and Autodecrement

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, like the same operator in C and similar languages:

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

Just 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 thus 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, you increment one element in %count, and possibly create it as well. After that loop finishes, $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.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial