Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata