I don't think a new iterator is the best generic approach.
Because only the loop's body knows if resetting the iterator is appropriate.
for the general case - iterating a hash and occasionally deleting elements in the body, this should always fit
while (my $key = each %hash) { if ( condition($key) ) { delete @hash{ dependent_keys($key) }; keys %hash; } }
The Rule: reset the iterator if and only if other elements are deleted.
This will never end in an endless loop, because the hash will
my %seen; while (my $key = each %hash) { next if $seen{$key}++; if ( condition($key) ) { delete @hash{ dependent_keys($key) }; keys %hash; } }
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
FootballPerl is like chess, only without the dice
°) not sure how costly resetting is in the end.
²) provided it's a finite structure which isn't refilled simultanously
In reply to Re^6: Iterating over hash while deleting elements (Best Practice)
by LanX
in thread Iterating over an hash while removing keys
by Eily
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |