Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Deleting Hash Entries while Iterating

by rmalhotra (Initiate)
on Jun 27, 2002 at 12:56 UTC ( [id://177696]=perlquestion: print w/replies, xml ) Need Help??

rmalhotra has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

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

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: Deleting Hash Entries while Iterating
by ariels (Curate) on Jun 27, 2002 at 13:06 UTC
    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.

Re: Deleting Hash Entries while Iterating
by thelenm (Vicar) on Jun 27, 2002 at 15:49 UTC
Re: Deleting Hash Entries while Iterating
by davido (Cardinal) on Oct 06, 2003 at 23:05 UTC
    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..."

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-18 03:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found