Is perl's each function worth using?

each, hash, iterator, perl

Solution

I think it is worth using as long as you are aware of this. It's ideal when you need both key and value in iteration:

while (my ($k,$v) = each %h) {
    say "$k = $v";
}

In your example you can reset the iterator by adding `keys %h;` like so:

my %h = map { $_ => 1 } qw/1 2 3/;
while (my $k = each %h) { print "1: $k\n"; last }
keys %h;  # reset %h
while (my $k = each %h) { print "2: $k\n" }

From Perl 5.12 `each` will also allow iteration on an array.

Problem

From perldoc -f each we read: There is a single iterator for each hash, shared by all `each`, `keys`, and `values` function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating `keys HASH` or `values HASH`. The iterator is not reset when you leave the scope containing the `each()`, and this can lead to bugs: ``` my %h = map { $_, 1 } qw(1 2 3); while (my $k = each %h) { print "1: $k\n"; last } while (my $k = each %h) { print "2: $k\n" } ``` Output: ``` 1: 1 2: 3 2: 2 ``` What are the common workarounds for this behavior? And is it worth using `each` in general?

Original source