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

Dear Perl monks, i have written a perl program and after parsing, now my array contains, abc1 abc32 abc64 abc8 abc16 i have to sort these array in descending order (last digits) i.e, array should look like, abc64 abc32 abc16 abc8 abc1 Thanks in advance

Replies are listed 'Best First'.
Re: sort an array based on pattern
by ikegami (Patriarch) on Oct 22, 2010 at 07:20 UTC
    sort can take a compare function. Extract the digits and compare them.
    @array = sort { my ($digits_from_a) = $a =~ /(\d+)\z/; my ($digits_from_b) = $b =~ /(\d+)\z/; $digits_from_b <=> $digits_from_a } @array;

    Same, but a bit more terse:

    @a = sort { ($b =~ /(\d+)\z/)[0] <=> ($a =~ /(\d+)\z/)[0] } @a;

    The aforementioned Schwartzian Transform is an attempt to optimise this.

Re: sort an array based on pattern
by morgon (Priest) on Oct 22, 2010 at 07:10 UTC
    Use a Schwartzian-transformation, e.g.
    use strict; my @array = qw(abc1 abc32 abc64 abc8 abc16); my @sorted_array = map { $_->{string} } sort { $b->{number} <=> $a->{number} } map { /(\d+$)/; { string => $_, number => $1 } } @array;
Re: sort an array based on pattern
by AnomalousMonk (Archbishop) on Oct 22, 2010 at 17:43 UTC