Risk-Aware AI Code Review for Business-Critical Systems
LiveReview LiveReview Explore LiveReview

Perl::Critic::Policy::Community::LoopOnHash - Don't loop over hashes

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

       It's possible to loop over a hash as if it was a list, which results in alternating between the keys and
       values of the hash. Often, the intent was instead to loop over either the keys or the values of the hash.

        foreach my $foo (%hash) { ... }      # not ok
        action() for %hash;                  # not ok
        foreach my $foo (keys %hash) { ... } # ok
        action() for values %hash;           # ok

       If you intended to loop over alternating keys and values, you can make this intent clear by first copying
       them to an array:

        foreach my $key_or_value (@{[%hash]}) { ... }
        foreach my $key_or_value (my @dummy = %hash) { ... }

       This policy is a subclass of the policy Perl::Critic::Policy::Variables::ProhibitLoopOnHash, and performs
       the same function but in the "community" theme.

Name

       Perl::Critic::Policy::Community::LoopOnHash - Don't loop over hashes

See Also

       Perl::Critic

perl v5.40.1                                       2025-03-22              Perl::Critic::...ity::LoopOnHash(3pm)

See Also