Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
> 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

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

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-01-20 16:26 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (57 votes). Check out past polls.