Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Iterating over hash while deleting elements

by Eily (Monsignor)
on Feb 06, 2020 at 17:02 UTC ( #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...

  • Comment on Re: Iterating over hash while deleting elements

Replies are listed 'Best First'.
Re^2: Iterating over hash while deleting elements
by LanX (Sage) 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? | Other CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2023-03-24 18:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (61 votes). Check out past polls.

    Notices?