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 ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.