Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^5: Iterating over hash while deleting elements

by Eily (Monsignor)
on Feb 06, 2020 at 17:29 UTC ( [id://11112507]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Iterating over hash while deleting elements
in thread Iterating over an hash while removing keys

I guess then:

sub delete_first(\%) { my $hash = shift; keys %$hash; my ($key, $value) = each %$hash; delete $hash->{$key}; wantarray ? ($key, $value) : $key; } while (my $key = delete_first %hash) { do_stuff(); }
Would be safer. At least delete_first doesn't depend on the current state of the hash's iterator, and the iterator (each) is still valid right after calling it.

Replies are listed 'Best First'.
Re^6: Iterating over hash while deleting elements (Best Practice)
by LanX (Saint) on Feb 07, 2020 at 11:52 UTC
    > while (my $key = delete_first %hash)

    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

    • either be emptied ²
    • or the last "re-iteration" is not interrupted.
    The only difficulty might be efficiency consideration:
    • If the $key itself is deleted
      => this should be done outside the if-block to not reset °
    • If the $key itself is NOT deleted
      => you might want to avoid processing it again by a checking a %seen hash.
    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

      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

        > 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11112507]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-03-19 10:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found