in reply to How can I delete an element in a foreach cycle?

TIMTOWTDI. You could remember the indices and splice the goners out, highest first:

my @goners; for (0 .. $#ARGV) { unshift @goners, $_ if $ARGV[$_] eq 'hello'; } splice @ARGV, $_, 1 for @goners;

update: $#ARGV instead of @ARGV-1 as per dsheroh's comment below.

Replies are listed 'Best First'.
Re^2: How can I delete an element in a foreach cycle?
by dsheroh (Monsignor) on Feb 27, 2010 at 11:10 UTC
    Any particular reason for @ARGV-1 instead of $#ARGV?

      Other than TIMTOWTDi, no ;-) But $#ARGV is better, since it needn't be calculated. - corrected, thanks.

        In 5.10.0 and 5.10.1, $#a adds magic, so there's a performance penalty to $#a too. Either way, the cost has got to be minor.

        Note that $#a only adds magic when $#a is used in an lvalue context in 5.12.

Re^2: How can I delete an element in a foreach cycle?
by jasonk (Parson) on Mar 02, 2010 at 04:35 UTC

    Or just go backwards...

    for my $i ( reverse 0 .. $#ARGV ) { splice( @ARGV, $i, 1 ) if $ARGV[$i] eq 'hello'; }

    www.jasonkohles.com
    We're not surrounded, we're in a target-rich environment!