Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


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

Title:
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 How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-04-23 11:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found