in reply to Reverse sort array

A similar approach, but likely slower due to more levels of indirection:
>perl -wMstrict -le "sub ascending { $a cmp $b } sub descending { - ascending() } my @ra = qw(q w e r t y u i o p); my $sorter = 'descending'; @ra = sort $sorter @ra; print qq{@ra}; $sorter = 'ascending'; @ra = sort $sorter @ra; print qq{@ra}; " y w u t r q p o i e e i o p q r t u w y

Replies are listed 'Best First'.
Re^2: Reverse sort array
by johngg (Canon) on Aug 20, 2009 at 13:24 UTC

    You can get by with just one sorting routine by reversing the arguments as needed.

    $ perl -Mstrict -wle ' > my @arr = qw{ q w e r t y u i o p }; > my $sc = sub { my( $a, $b ) = @_; $a cmp $b }; > my $rev = 0; > my @asc = sort { $rev ? $sc->( $b, $a ) : $sc->( $a, $b) } @arr; > $rev = 1; > my @des = sort { $rev ? $sc->( $b, $a ) : $sc->( $a, $b) } @arr; > print qq{@arr\n@asc\n@des};' q w e r t y u i o p e i o p q r t u w y y w u t r q p o i e $

    I hope this is of interest.

    Cheers,

    JohnGG