O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Operating on a Series of Integers

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 in any situations where you want to process all numbers[4] within a range.

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
}

Discussion

The first two methods use the $X .. $Y construct, which creates a list of integers between $X and $Y. This uses a lot of memory when $X and $Y are far apart. (This is fixed in the 5.005 release.) When iterating over consecutive integers, the explicit for loop in the third method is more memory efficient.

The following code shows each technique. Here we only 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 

See Also

The for and foreach operators in perlsyn (1) and the “For Loops” and “Foreach Loops” sections of Chapter 2 of Programming Perl

[4] Okay, integers. It’s hard ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required