logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

Perl::Critic::Policy::Community::Each - Don't use each to iterate through a hash

Affiliation

       This policy is part of Perl::Critic::Community.

Author

       Dan Book, "dbook@cpan.org"

Configuration

       This policy is not configurable except for the standard options.

Description

       The each() function relies on an iterator internal to a hash (or array), which is the same iterator used
       by keys() and values(). So deleting or adding hash elements during iteration, or just calling keys() or
       values() on the hash, will cause undefined behavior and the code will likely break. This could occur even
       by passing the hash to other functions which operate on the hash. Instead, use a "foreach" loop iterating
       through the keys or values of the hash.

         while (my ($key, $value) = each %hash) { ... }                # not ok
         foreach my $key (keys %hash) { my $value = $hash{$key}; ... } # ok
         foreach my $i (0..$#array) { my $elem = $array[$i]; ... }     # ok

Name

       Perl::Critic::Policy::Community::Each - Don't use each to iterate through a hash

See Also

       Perl::Critic, <http://blogs.perl.org/users/rurban/2014/04/do-not-use-each.html>

perl v5.40.1                                       2025-03-22              Perl::Critic::...Community::Each(3pm)

See Also