Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: foreach array - delete current row ?

by Laurent_R (Canon)
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]
[Discipulus]: indeed Monopoli it's a real place marto
[Discipulus]: the skeleton of my module works!

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (8)
As of 2018-01-23 12:46 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (245 votes). Check out past polls.