in reply to Re: Help me not use codefor($i=0;$i=$#array;$i++)/code...Please!
in thread Help me not use for($i=0;$i=$#array;$i++)...Please!

I wouldn't use the splice construct inside of a loop iterating over the array. It'll get rid of the right elements, but it'll keep the array the same size due to autovivification at the end. (This may depend on the version of Perl.) Running under strict exposes this:
my @array = (0 .. 9); $" = " "; for my $i (0 .. $#array) { splice @array, $i, 1 if $array[$i] == 5; print "$i: @array\n"; } print "Array is ", scalar @array, " elements long.\n";
Bang, uninitialized value and @array is 9 elements long at the end. Yikes.
  • Comment on Re: Re: Help me not use codefor($i=0;$i=$#array;$i++)/code...Please!
  • Download Code

Replies are listed 'Best First'.
Re: Help me not use codefor($i=0;$i=$#array;$i++)/code...Please!
by Abigail (Deacon) on Jun 21, 2001 at 05:12 UTC
    And what's worse, if you have consequetive elements equal to 5, only of them is removed. Because the splice moves everything following one down, but the next iteration ups the counter.

    -- Abigail

      If you need to splice in a loop there is an easy solution, just count down to zero rather than counting up in the normal way.

      -- iakobski