Skip Menu |
 

Preferred bug tracker

Please visit the preferred bug tracker to report your issue.

This queue is for tickets about the Perl-Critic CPAN distribution.

Report information
The Basics
Id: 75904
Status: new
Priority: 0/
Queue: Perl-Critic

People
Owner: Nobody in particular
Requestors: EDAVIS [...] cpan.org
Cc:
AdminCc:

Bug Information
Severity: Wishlist
Broken in: 1.117
Fixed in: (no value)



Subject: Suggested policy: iterate over arrays with 'each' instead of $i=0;$i++
Download (untitled) / with headers
text/plain 949b
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


This service is sponsored and maintained by Best Practical Solutions and runs on Perl.org infrastructure.

Please report any issues with rt.cpan.org to rt-cpan-admin@bestpractical.com.