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

Re: Iterating over hash while deleting elements

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


in reply to Iterating over hash while deleting elements
in thread Iterating over an hash while removing keys

each has no problem if you delete the current element
Nice to know but I wouldn't rely on it. I think "don't use each if the hash changes" is an easier rule to follow/understand. And it's safer against possible future changes as well (you might start by only deleting the current key, and then find out you can delete a few more at the same time).

Question to follow ;-P
Spooky...

Replies are listed 'Best First'.
Re^2: Iterating over hash while deleting elements
by LanX (Saint) on Feb 06, 2020 at 17:05 UTC
    > Nice to know but I wouldn't rely on it

    It's documented.

    > Exception: It is always safe to delete the item most recently returned by each, so the following code works properly:

    >

    while (my ($key, $value) = each %hash) { print $key, "\n"; delete $hash{$key}; # This is safe }

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      Oh I didn't mean I don't trust perl with that. It's whoever is using perl I have trust issues against ;-)

        point is you must delete the current key to avoid an endless loop.

        not sure how an idiot proof algo would look like.

        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://11112502]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-03-29 04:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found