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

Hi

How can I read a sorting array from the last to begining...could somebody guide me ?

TQ, bh_perl

  • Comment on reading array from the last into begining

Replies are listed 'Best First'.
Re: reading array from the last into begining
by davido (Cardinal) on Oct 08, 2003 at 04:02 UTC
    Q: How do I iterate over an array in reverse order:
    foreach my $element ( reverse @array ) { print "$element\n"; }
    Q: How do I sort an array in reverse order (descending instead of ascending):
    @sorted_array = reverse sort @array;
    or
    @sorted_array = sort { $b <=> $a } @array;
    (That's for numeric values. For strings try....)
    @sorted_array = sort { $b cmp $a } @array;
    Hmm.... a few others with map and unshift:
    @reversed_array = map { $array[$_] } reverse 0..$#array;
    or....
    foreach $element ( @array ) { unshift @reversed_array, $element; }

    Have at it!


    Dave


    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
Re: reading array from the last into begining
by vek (Prior) on Oct 08, 2003 at 03:15 UTC
Re: reading array from the last into begining
by BrowserUk (Patriarch) on Oct 08, 2003 at 04:20 UTC

    One way{grin}

    P:\test>perl -le"@a = 1.. 10; print for sort{1} @a 10 9 8 7 6 5 4 3 2 1

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail