Perl::Critic::Policy::Community::Each(3pm)

Perl::Critic::Policy::Community::Each3pm

Don't use each to iterate through a hash

Overview

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

Affiliation

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

Configuration

This policy is not configurable except for the standard options.

Releases

2 releases since Debian 12 (Bookworm); the text changed 1 time.

  1. 12
  2. 13

Author

Dan Book, "[email protected]"

From libperl-critic-community-perl 1.0.4-1 in Debian 13 (Trixie). Parsed by carta from the page's man source.