Perl-Critic / Perl-Critic

The leading static analyzer for Perl. Configurable, extensible, powerful.
http://perlcritic.com
Other
181 stars 103 forks source link

Suggested policy: iterate over arrays with 'each' instead of $i=0;$i++ #465

Open thaljef opened 11 years ago

thaljef commented 11 years ago

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:

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

See also: http://www.modernperlbooks.com/mt/2012/03/inadvertent-inconsistencies-each-in-perl-512.html

epa commented 9 years ago

Another article on this: http://www.effectiveperlprogramming.com/2010/05/perl-5-12-lets-you-use-each-on-an-array/