ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы.



2.5. 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[2] within a range.

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

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


Previous: 2.4. Converting Between Binary and DecimalPerl CookbookNext: 2.6. Working with Roman Numerals
2.4. Converting Between Binary and DecimalBook Index2.6. Working with Roman Numerals