From perldoc -f each we read:
There is a single iterator for each hash, shared by all
each,keys, andvaluesfunction calls in the program; it can be reset by reading all the elements from the hash, or by evaluatingkeys HASHorvalues 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?
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:
In your example you can reset the iterator by adding
keys %h;like so:From Perl 5.12
eachwill also allow iteration on an array.