in reply to Helping with sorting

Heres another way to do it. Though it will give warnings with -w or the warnings pragma.
use strict; my @array = qw(2aa 2ba 12kf 9cn 9vn 21sg); my @sorted = sort {$b <=> $a || $b cmp $a } @array; print $_,$/ foreach @sorted;

update: the above does both (letters and numbers) in descending order what I think the OP wanted was descending numbers ascending letters. so the following should work:

my @array = qw(2aa 2ba 12kf 9cn 9vn 21sg); my @sorted = sort {$b <=> $a || $a cmp $b } @array; print $_,$/ foreach @sorted;

-enlil

Replies are listed 'Best First'.
Re: Re: Helping with sorting
by pg (Canon) on Apr 02, 2003 at 05:58 UTC
    Wow! (This is the kind of feeling you don't have very often) This solution is really graceful, simple and straight.

    Enlil played at least three very neat tricks here:
    1. He forced the number portion to be extracted and compared. (this gives some warnings, but compare to the elegance he showed us in this one liner, those warnings are really nothing)

      If you really want to avoid the warnings, do this:
      my @sorted = sort {($b =~ /(\d*)/)[0] <=> ($a =~ /(\d*)/)[0] || $a cmp + $b} @array;
    2. That || triggered the second condition to be evaluated, if the first condition evaluates to false, two elements have the same number portion are ordered by the string as a whole.
    3. If two elements have the same number portion, then logically, to order them by the string portion following the number portion results the same sequence as to order by the whole string.
Re: Re: Helping with sorting
by rinceWind (Monsignor) on Apr 02, 2003 at 12:27 UTC
    There's just a minor problem with this - granted the sort works with the data supplied. How about text with leading zeros?
    2ah 02bl 01hz
    I guess that to answer the question of leading zeros, we need to know what the specified requirements are. Still, it's another test scenario for you.
Re2: Helping with sorting
by dragonchild (Archbishop) on Apr 02, 2003 at 15:59 UTC
    Note: This will only work because the numbers are before the letters. If the letters were first, the numeric comparison would be a no-op.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.