Yes, we are on the same page here! Thanks for emphasizing the difference between ASCII vs numeric sort order!Corion is completely correct about this...there is a difference. I attach some code that I use for a GUI sort gizmo that doesn't know if it is sorting numbers or alpha-number strings. It uses normal string compare unless both items are strictly numeric and in that case, it uses the "spaceship" operator "<=>" for the compare.
sub alpha_num_cmp
{
my($a, $b) = @_;
if (( $a =~ m/\D/) || ($b =~ m/\D/) ) { #look for a non-digit
return ($a cmp $b); #if so, then use string compare
}
return ($a <=> $b); #otherwise straight numeric comparison
}
Ok, a cut-n-paste goof...The above code was one level down in the GUI..Ooops!
That code compares "columns" of similar things.
Here is more code...
#!usr/bin/perl -w
use strict;
my @a=(8,5,2,4,88,1,10,20,5,4,3,2);
my @b = sort @a;
print "alpha sort\n";
print "@b\n";
@b = sort {$a<=>$b}@a;
print "numeric sort\n";
print "@b\n";
@b = sort alpha_num_cmp @a;
print "an any sort\n";
print "@b\n";
sub alpha_num_cmp
{
if ( ( $a =~ m/\D/) || ($b =~ m/\D/) )
{ #look for a non-digit
return ($a cmp $b); #if so, then use string compare
}
return ($a <=> $b); #otherwise straight numeric comparison
}
__END__
prints:
alpha sort
1 10 2 2 20 3 4 4 5 5 8 88
numeric sort
1 2 2 3 4 4 5 5 8 10 20 88
an any sort
1 2 2 3 4 4 5 5 8 10 20 88
|