in reply to Numeric Sort for Stringified Value (How to Avoid Warning)

Strings are sorted on a place-basis, while numbers are considered as a whole. For example, if the first chars of a string are different, they will be sorted only on that char. '1' is less than '9' so '10' is less than '9' in string-land.

If it is very important for you to be able to use string-sort without warnings (and you can't locally turn off warnings), you could try:

my @old = ( "10.5 AA", "9 AC", "2 BB"); my $max_len = 0; for (@old) { $max_len = length($_) if length($_) > $max_len } my @new = sort {$b cmp $a} map { my $x=''; $x.='0' for (1..$max_len-length($_)); $x.$_; } @old;

Dumping @new results in:

$VAR1 = [ '10.5 AA', '0009 AC', '0002 BB' ];

You may or may not need to trim the zeroes.

Update: a space works equally well as a 0 for this application, and might be better for post-trimming if you need to preserve leading zeroes in the source.

<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code
"In any sufficiently large group of people, most are idiots" - Kaa's Law

Replies are listed 'Best First'.
Re: Numeric Sort for Stringified Value (How to Avoid Warning)
by benizi (Hermit) on Sep 19, 2005 at 16:42 UTC

    This breaks, e.g. on @old = ("10.5 AA", "100 NO");

    10.5 < 100, but "10.5" gt "0100".

      Excellent catch, and a great test case. My approach was wrong. In order to sort this in a DWIM-like way, this would probably work better:

      my @old = ("10.5 AA", "100 NO"); my @new = map { join(' ',@$_) } sort { ($b->[0] <=> $a->[0]) || ($b->[1] cmp $a->[1]) } map { ($1,$2) if m/(.*?)\s(.*)/ } @old;

      That's a bit cryptic. Basically, split each component of @old into number and string "columns", then use a two-criteria sort (sort on number, then string) and rejoin the "columns" into a string again.

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law