Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Deleting Hash Entries while Iterating

( #177696=categorized question: print w/ replies, xml ) Need Help??
Contributed by rmalhotra on Jun 27, 2002 at 12:56 UTC
Q&A  > hashes


Description:

Is it safe to delete hash elements while iterating over the same hash. Does it degrade the performance of the program??

Answer: Deleting Hash Entries while Iterating
contributed by ariels

I suggest that the docs for each may say just what you're asking.

If just iterating over the list of keys of the hash (e.g. foreach (keys %hash)) then of course no limitations exist -- the list of keys is generated once at the start of the iteration, so deletion does nothing.

Answer: Deleting Hash Entries while Iterating
contributed by thelenm

You may be interested in Adding or removing keys while iterating over a hash, which has some discussion on this topic.

Answer: Deleting Hash Entries while Iterating
contributed by davido

You may iterate over the hash using each, deleting elements as you go, if you wish. The POD for each says, "You must not add elements to the hash while iterating over it, although you are permitted to use delete."

Update: Please note that different versions of the POD have different comments regarding deleting elements while iterating using each. Camel II says "ok". Earlier versions of the POD say, "don't do it". And the POD for version 5.8.0 says, "It is always safe to delete the item most recently returned by each..."

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

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

    How do I use this? | Other CB clients
    Other Users?
    Others pondering the Monastery: (5)
    As of 2014-10-25 09:44 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (142 votes), past polls