in reply to Deleting specific element in array in FOREACH loop

There are lots of ways to do it. You could build up a new array as you go with only the values you want to keep. You could use an index and splice. For example (untested):
for (my $i = $#array; $i > -1; $i--) { # Delete element here if it matches. splice @array, $i, 1; }
You need to count backwards here so that you don't miss any entries when they shift around.

Replies are listed 'Best First'.
Re^2: Deleting specific element in array in FOREACH loop
by GrandFather (Saint) on Sep 15, 2006 at 20:01 UTC
    for my $index (reverse 0 .. $#array)

    is a more Perlish way to achieve that. It is clearer and avoids fence posts.


    DWIM is Perl's answer to Gödel

      The downside is that
      for my $index (reverse 0 .. $#array)
      creates a list as large as the array, whereas
      for (my $i = $#array; $i > -1; $i--)
      and
      for (my $i = @array; $i--; )
      have no memory cost. That said, it usually doesn't matter.

      On the plus side,
      for my $index (reverse 0 .. $#array)
      could be slower. It is optimized to loop backwards instead of actually calling reverse.

        for modern versions of perl, this is no longer true for normal ranges. does it still create the array for 'reverse' ranges?