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-)
In reply to Re: How do I completely remove an element from an array?
by jaa
in thread How do I completely remove an element from an array?
by vroom
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |