You do not repeat the hash, you repeat the list of keys returned by keys before you start the loop, because
for my $key (keys %$hash_ref) { ... }
roughly coincides with
my @anon = keys %$hash_ref; for my $key (@anon) { ... }
Removing from the hash does not cause any problems.
each , on the other hand, iterates over the hash. Each time he called, each returns a different element. However, it is still safe to delete current item!
# Also safe while (my ($key) = each(%$hash_ref)) { ... delete $hash_ref->{$key}; ... }
If you add or remove hash elements while iterating over it, entries may be skipped or duplicated, so don't do this. Exception: you can always delete an item that was recently returned by each ()
ikegami
source share