Recipe 2.4 Operating on a Series of Integers

2.4.1 Problem

You want to perform an operation on all integers between X and Y, such as when you're working on a contiguous section of an array or wherever you want to process all numbers[1] within a range.

[1] Okay, integers. It's hard to find all the reals. Just ask Cantor.

2.4.2 Solution

Use a for loop, or .. in conjunction with a foreach loop:

foreach ($X .. $Y) {
    # $_ is set to every integer from X to Y, inclusive
}

foreach $i ($X .. $Y) {
    # $i is set to every integer from X to Y, inclusive
}

for ($i = $X; $i <= $Y; $i++) {
    # $i is set to every integer from X to Y, inclusive
}

for ($i = $X; $i <= $Y; $i += 7) {
    # $i is set to every integer from X to Y, stepsize = 7
}

2.4.3 Discussion

The first two approaches use a foreach loop in conjunction with the $X .. $Y construct, which creates a list of integers between $X and $Y. Now, if you were just assigning that range to an array, this would use up a lot of memory whenever $X and $Y were far apart. But in a foreach loop, Perl notices this and doesn't waste time or memory allocating a temporary list. When iterating over consecutive integers, the foreach loop will run faster than the equivalent for loop.

Another difference between the two constructs is that the foreach loop implicitly localizes the loop variable to the body of the loop, but the for loop does not. That means that after the for loop finishes, the loop variable will contain the value it held upon the final iteration. But in the case of the foreach loop, that value will be inaccessible, and the variable will hold whatever it heldif anythingprior to entering the loop. You can, however, use a lexically scoped variable as the loop variable:

foreach my $i ($X .. $Y)       { ... }
for (my $i=$X; $i <= $Y; $i++) { ... }

The following code shows each technique. Here we just print the numbers we generate:

print "Infancy is: ";
foreach (0 .. 2) {
    print "$_ ";
}
print "\n";

print "Toddling is: ";
foreach $i (3 .. 4) {
    print "$i ";
}
print "\n";

print "Childhood is: ";
for ($i = 5; $i <= 12; $i++) {
    print "$i ";
}
print "\n";

Infancy is: 0 1 2 
Toddling is: 3 4 
Childhood is: 5 6 7 8 9 10 11 12 

2.4.4 See Also

The for and foreach operators in perlsyn(1) and the "For Loops" and "Foreach Loops" sections of Chapter 4 of Programming Perl