http://www.perlmonks.org?node_id=11112564


in reply to Re^6: Iterating over hash while deleting elements (Best Practice)
in thread Iterating over an hash while removing keys

The Rule: reset the iterator if and only if other elements are deleted.
I don't think a new iterator is the best generic approach.
Why? What's wrong with getting a new iterator as long as the function is documented to reset it?

I'm really not a fan of your proposition, because it makes it look like this is a normal iteration over an hash, but you only know otherwise by looking inside the block. It's kind of obscure as well, you might iterate normally for a few keys, and in some conditions start over, (which is kind of confusing when iterating over an hash with it's sometimes random order). Also by having the loop logic split in two places, you can't abstract it away with:

while (my $key = $remaining_keys->next()) { ...; }
where you might decide that you finally do care about the order of traversal, and just make next() call .get_most_important_key() instead of .get_random_key() or .get_first_key().

I guess you're trying to solve the problem of iterating over a hash while changing it's content, but not always removing the current key. This would do the work:

while (my ($key, $value) = delete_first %hash) { do_stuff(\%hash, $key, $value); $subset{$key} = $value if valid($key); }
does the work, and at least there's no back and forth in the way you iterate over the hash.

ot sure how costly resetting is in the end.
Doesn't matter, I'm resetting in the beginning :D

Replies are listed 'Best First'.
Re^8: Iterating over hash while deleting elements (Best Practice)
by LanX (Cardinal) on Feb 07, 2020 at 14:23 UTC
    > What's wrong with getting a new iterator as long as the function is documented to reset it?

    My approach is more generic because you don't need to delete the whole hash.

    You could probably also use a simple for loop and just next if the key doesn't exist anymore.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice