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.
|
|---|
| 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 | |
by radiantmatrix (Parson) on Sep 20, 2005 at 17:53 UTC |