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 31, 2001 at 00:27 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://109198]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-03-28 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found