in reply to Deleting specific element in array in FOREACH loop

foreach (and for) build a list containing aliases to the elements passed in. You can delete elements from the underlying array as long as you are iterating linearly over the array, it's to say not relying on the index. Oh well, that sounds like mumble (examples & pitfalls not yet promised :-). Anyways, it seems that doing
while(@array) { my $element = $array[0]; # do tons of stuff... if($result eq 'foo') { shift @array; } }

is a better approach, since you want to consume the array with your loop.

<update> - reread post - this doesn't fit.</update>

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^2: Deleting specific element in array in FOREACH loop
by graff (Chancellor) on Sep 15, 2006 at 22:18 UTC
    Um, with your approach, if you don't actually shift every element off of @array, it'll be an infinite loop, I think. Maybe you meant something like:
    my @keep = (); while (@array) { my $element = shift @array; # do stuff push @keep, $element unless ( $result eq 'foo' ); }
    In any case, just doing  my @keep = grep { somefunc($_) } @array; (as suggested in earlier replies) feels easier and cleaner somehow.