This means that "each" mechanism is not very good to use.
It depends: As described in each, every hash has an iterator that is per-hash. The code you showed in the root node doesn't work because both of the each calls access the same iterator. My solution fetches the list of keys once at the beginning of the for loop, which will use a bit more memory; I could have done this for both loops, but in this example I knew that the inner each would work because there's nothing else interfering with the iterator, so I kept it. keys does have the advantage that if you want to loop through the hash in a predictable order, you can just say sort keys %hash.
Also, note that if you want to create the Cartesian product of two sets of hash keys, there are plenty of modules that will do this, see the links in the section "See Also" in my module Algorithm::Odometer::Tiny.
use warnings;
use strict;
use Algorithm::Odometer::Tiny;
my $h = {a=>1, b=>2, c=>3, d=>4};
my $odo = Algorithm::Odometer::Tiny
->new( [sort keys %$h], [sort keys %$h] );
while ( my @x = $odo->() ) {
print "outer: $x[0], inner: $x[1]\n";
}
|