The whole idea of a foreach my $x (@arr){} iterator is so that you don't have to know the number of elements in @arr to process each one. In many languages like C, you have to setup something like:
for (i=0;i<=max;i++){..do something with x[i], etc..}.
In Perl, the foreach loop causes $x to become each thing in the array successively without: a)modifying the size of @arr (the $x value can be use to modify a value in @arr); b) needing a subscript and c)perhaps more importantly, you don't have to worry about the ending condition being: i<=max or i<max! "off-by-one" is a VERY common error.
If you want to keep track of how many x's there have been processed so far, then something like this is a better way to go because the looping construct doesn't depend upon the $count value, meaning that you won't "overflow" the array bounds even if your count should have started at 0 instead of 1 or maybe a --$count vs $count++ boo-boo:
my @arr =(10,11,12);
my $count =1;
foreach my $x (@arr)
{
print $count++," $x\n";
}
#prints
#1 10
#2 11
#3 12
If you are going to actually reduce the size (num of elements) in @arr instead of just iterating over each element, then use a "while" loop. The following processes pairs of things from @tokens and removes them from @tokens as it does so.
while (@tokens)
{
my ($x, $y) = splice(@tokens,0,2);
.....use $x and $y to do something...
..next loop causes another pair of $x, $y to be
used if there are any left in @tokens
}
Update: To simplify the above to one shift (instead of 2 using splice()), this is completely legal although not a normal situation:
#!/usr/bin/perl -w
use strict;
my @arr = ( 11, 12, 13, 14 );
while (@arr)
{
my $x = shift(@arr);
print "this item=$x #left in arr ".@arr."\n";
}
=prints
this item=11 #left in arr 3
this item=12 #left in arr 2
this item=13 #left in arr 1
this item=14 #left in arr 0
=cut
|