http://qs1969.pair.com?node_id=475106

Fellow Monks,

I have just spent an hour debugging a very strange problem, only to discover that I have been bitten by the behaviour of each. While all this is properly documented (each), I was not aware of it, so I thought I'd bring it up here as a caveat to remember.

The subroutine in the following snippet works only once (or rather every other time).

use strict; use warnings; our %hash = ( 1=> 2, 3=>4 ); sub find_2{ while (my ($key,$val) = each(%hash)) { return "The key for 2 is $key\n" if $val == 2; } die "could not find 2"; } print find_2; print find_2;
After the first call, it dies:
The key for 2 is 1 could not find 2 at each.pl line 11.
What happens here is that the subroutine does not search through the whole hash (it short-cicuits for performance reasons by returning the solution as soon as it has found it), and as a result, the next call to each on the same hash (even in completely different parts of the code!) will not start at the beginning again, but pick up where the first call left off.

Solution: Either go through the whole hash, or rewind it after using each:

if ($val == 2){; #rewind each my $a = scalar keys %hash; return "The key for 2 is $key\n" }