in reply to Re^2: Efficient array element deletion
in thread Efficient array element deletion

for ( reverse 0 .. $#array ) flattens the list.for ( -@array .. -1 ) is better.

Except I don't think that will work either.

J:\> perl -le "@arr = ( 1 .. 10 ); print $arr[ $_ ] for -@arr .. -1;" 1 2 3 4 5 6 7 8 9 10 J:\>

From the documentation (Range Operators, my emphasis): In list context, it returns a list of values counting (up by ones) from the left value to the right value so I don't think it can be persauded to decrement. So doing

J:\> perl -le "@arr = ( 1 .. 10 ); print $arr[ $_ ] for -1 .. -@arr;" J:\>

results in nothing useful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^4: Efficient array element deletion
by ikegami (Patriarch) on Dec 05, 2008 at 13:07 UTC

    I thought you were referring to the off-by-one error, and didn't notice it also iterated backwards.

    Solutions:
    for ( -$#array..0 ) { ... $array[-$_] ... }
    for ( my $i=@array; $i--; ) { ... $array[$i] ... }

      Here's another approach to accessing the elements of an array in reverse order without creating a list:

      @a = 1 .. 9;; print "$_ : -$_ : $a[ -$_ ]" for 1 .. @a;; 1 : -1 : 9 2 : -2 : 8 3 : -3 : 7 4 : -4 : 6 5 : -5 : 5 6 : -6 : 4 7 : -7 : 3 8 : -8 : 2 9 : -9 : 1

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        This is actually what I meant to do originally, I just didn't quite understand how negative indices were interpreted.