Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: How do I completely remove an element from an array?

by jaa (Friar)
on Mar 21, 2003 at 11:07 UTC ( [id://244828]=note: print w/replies, xml ) Need Help??


in reply to How do I completely remove an element from an array?

Be careful using splice during array iteration.

Note the subtle bug here:

my @items = ( 0..5 ); my $index = 0; for my $value (@items) { print "testing $value\n"; if ( $value == 1 or $value == 3 ) { print "removed value $value\n"; splice @items, $index, 1; } $index++; }

Values 2 and 4 are never actually tested for; iteration skips them completely!

If you want to iterate over an array removing some items, try something like:

my $index = 0; while ($index <= $#items ) { my $value = $items[$index]; print "testing $value\n"; if ( $value == 1 or $value == 3 ) { print "removed value $value\n"; splice @items, $index, 1; } else { $index++; } }

And, this being Perl I bet there are many other safe iteration/splice approaches... 8-)

Replies are listed 'Best First'.
Re: Answer: How do I completely remove an element from an array?
by jasonk (Parson) on Mar 21, 2003 at 15:32 UTC

    You can also avoid the 'sliding' problem of skipping over elements because you removed the element before them by iterating backwards:

    for(reverse (0 .. $#items)) { splice(@items, $_, 1) if ($items[$_] == 1 || $items[$_] == 3); }

    Which is slightly obfuscated, but works because the sliding end of the array contains only the elements you have already checked...


    We're not surrounded, we're in a target-rich environment!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2024-04-19 07:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found