Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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 ?
Re^2: foreach array - delete current row ?
by AnomalousMonk (Abbot) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2014-12-22 14:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (119 votes), past polls