Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: foreach array - delete current row ?

by Laurent_R (Abbot)
on Jun 02, 2013 at 22:36 UTC ( #1036629=note: print w/replies, xml ) Need Help??

in reply to foreach array - delete current row ?

Deleting elements from an array while iterating over it is explicitly documented as 'So don't do that' in perlfunc.

Yes, this is really getting bad and messy. But for some reason, it seems that it sort of works fine with a hash. I had a program where I was progressively "improving" my hash by deleting useless elements, and everything went fine. Then I thought that it might be more efficient to use an array instead, and I figured out that it did not work at all. The array got completely messed up. In brief, it seems that you can delete records from a hash while processing it, but can"t do it in an array. OK, maybe I got it wrong and did not understand fully what was going on, but I got the feeling that you can modify a hash while processing it with the keys function, but not an array fith the foreach function.

Does any monk here have an explanation for this apparently different behavor?

  • Comment on Re: foreach array - delete current row ?

Replies are listed 'Best First'.
Re^2: foreach array - delete current row ?
by davido (Archbishop) on Jun 02, 2013 at 22:43 UTC

    As documented in each, it is safe to use the each iterator to iterate over a hash and delete the element most recently returned. It is also safe to generate a list of keys, and then delete hash elements by iterating over those keys -- you're not deleting elements from the list returned by keys, you're deleting elements from the hash that were listed by keys; a subtle but important difference.

    With an array, deleting elements requires rearranging the array, which (as the C++ folks like to say) invalidates the iterator, or as you mentioned, the array gets "completely messed up."


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1036629]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (13)
As of 2017-01-16 16:21 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (151 votes). Check out past polls.