Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How do I remove an element from any array while iterating over it in a loop?

by IraTarball (Monk)
on Aug 30, 2001 at 20:27 UTC ( #109198=note: print w/replies, xml ) Need Help??


in reply to How do I remove an element from any array while iterating over it in a loop?

grep is probably best here, as meowchow said. But now that I've said that, I think if you just decrement the index before doing the next you're code will do what you expect. Here's my snippet:
use strict; use warnings; my @arry = qw ( 1 5 5 5 5 2 ); my $i = 0; print "@arry\n"; for ($i = 0; $i < @arry; $i++) { next unless $arry[$i] == 5; splice (@arry, $i, 1); --$i; } print "@arry\n";
I personally think this is ugly and more difficult to follow than:
use strict; use warnings; my @arry = qw ( 1 5 5 5 5 2 ); my $i = 0; print "@arry\n"; @arry = grep { $_ != 5 } @arry; print "@arry\n";
but maybe that's just me.

Ira,

"So... What do all these little arrows mean?"
~unknown

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2019-06-25 18:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (107 votes). Check out past polls.

    Notices?