The normal way to iterate over an array is with 'foreach'.
However sometimes you need both the array index and its value:
my @a = qw(a b c);
for (my $i = 0; $i < @a; $i++) {
say "$i $a[$i]";
}
Or perhaps you would prefer to write
foreach my $i (0 .. $#a) {
say "$i $a[$i]";
}
But perl 5.12 introduces a more convenient alternative:
while (my ($i, $v) = each @a) {
say "$i $v";
}
Benchmarking indicates this is also significantly faster than the two
older idoms. Perl::Critic could have a policy to suggest using it.
This might not be the most straightforward policy to implement, since it
involves looking at both the range of values looped over and the body of
the loop. (If the body of the loop does not use $a[$i] then it is still
faster and simpler just to iterate over 0 .. $#a.)
RT Ticket: http://rt.cpan.org/Ticket/Display.html?id=75904 Requested On: Tue Mar 20 03:02:37 2012 Requested By: EDAVIS@cpan.org
The normal way to iterate over an array is with 'foreach'. However sometimes you need both the array index and its value:
Or perhaps you would prefer to write
But perl 5.12 introduces a more convenient alternative:
Benchmarking indicates this is also significantly faster than the two older idoms. Perl::Critic could have a policy to suggest using it.
This might not be the most straightforward policy to implement, since it involves looking at both the range of values looped over and the body of the loop. (If the body of the loop does not use $a[$i] then it is still faster and simpler just to iterate over 0 .. $#a.)
See also: http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html