http://www.perlmonks.org?node_id=985744

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hello, i have found a strange thing, with an array a while loop and a negative index, it seems to travel trough the array but with beginning by the end. $i=-1 => last element, $i=-2 => the one before the last .... and so on. for me it's ok now that i know it, but is it normal ?

Replies are listed 'Best First'.
Re: through an array in reverse
by choroba (Cardinal) on Aug 06, 2012 at 15:01 UTC
    It is a feature. See Subscripts
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      yep, i just seen it on the site, but it's strange on the first time (but powerful now that i'm thinking about it) thanks ^_^
Re: through an array in reverse
by blue_cowdawg (Monsignor) on Aug 06, 2012 at 15:56 UTC

    Backwards in an array? Simple...

    use strict; my @j=qw/ a b c d e f g /; while ( my $i=pop @j){ printf "%s\n",$i; }


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

      OK, but let’s not forget the reverse function:

      #! perl use strict; use warnings; my @j = ('a' .. 'g'); print join("\n", reverse @j);

      ;-)

      Athanasius <°(((><contra mundum

            but let’s not forget the reverse function

        TIMTOWTDI exemplified!


        Peter L. Berghold -- Unix Professional
        Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: through an array in reverse
by Anonymous Monk on Aug 06, 2012 at 20:03 UTC
    That's what negative indexes do.   It is a reasonable way to handle what is, after all, a very common business requirement.
Re: through an array in reverse
by linuxkid (Sexton) on Aug 06, 2012 at 15:37 UTC

    Of Course! it wouldn't be perl if there wasn't more than one way to do it!

    --linuxkid


    imrunningoutofideas.co.cc