Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: foreach array - delete current row ?

by sundialsvc4 (Abbot)
on Jun 03, 2013 at 02:11 UTC ( #1036642=note: print w/replies, xml ) Need Help??

in reply to foreach array - delete current row ?

Instead of deleting the items that you want to discard from an array that you are iterating over ... which is a very dicey proposition in any programming language ... just create a new list and push the entries that you want to keep onto it.   (The grep function might do this in one fell swoop.)   Then, replace the original list with the new one.

@list = grep( &keep_me, @list);

In almost every case, the two lists consist of references to some bit of information ... and a reference, no matter what monstrosity it may refer to, is small and cheap.   You’re actually not moving the contents (big) around, just references-to (small) them.   As you build the new list, the reference-counts of all its contents briefly rises to “2,” then, when the new list replaces the old one (and the old one vanishes into the gloom of the garbage-collector ...) they all go down again.

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

Replies are listed 'Best First'.
Re^2: foreach array - delete current row ?
by AnomalousMonk (Chancellor) on Jun 03, 2013 at 07:01 UTC
    @list = grep( &keep_me, @list);

    I would add that the  keep_me() function of the example must operate on the  $_ default scalar, which is topicalized by grep.

    >perl -wMstrict -le "sub keep_me { return m{ [[:upper:]] }xms; } ;; my @list = qw(a b K d E f g h E P m e); @list = grep &keep_me, @list; print qq{@list}; " K E E P

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2018-05-27 18:09 GMT
Find Nodes?
    Voting Booth?