Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Iterating over hash while deleting elements

by LanX (Saint)
on Feb 06, 2020 at 17:05 UTC ( [id://11112503]=note: print w/replies, xml ) Need Help??


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

> 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

Replies are listed 'Best First'.
Re^3: Iterating over hash while deleting elements
by Eily (Monsignor) on Feb 06, 2020 at 17:07 UTC

    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

        I guess then:

        sub delete_first(\%) { my $hash = shift; keys %$hash; my ($key, $value) = each %$hash; delete $hash->{$key}; wantarray ? ($key, $value) : $key; } while (my $key = delete_first %hash) { do_stuff(); }
        Would be safer. At least delete_first doesn't depend on the current state of the hash's iterator, and the iterator (each) is still valid right after calling it.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-03-19 05:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found