Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Perl's "sort" put these hash keys in numeric order?

Tags:

sorting

perl

Consider:

#!/usr/bin/perl
use strict;
use warnings;

my %hash;
foreach (1 .. 10) {
    $hash{$_} = $_;
}
foreach(sort(keys %hash)) {
    print $_ . ":  " . "$hash{$_}" . "\n";
}

When I execute the above code, the result is as below:

1:  1
10:  10
2:  2
3:  3
4:  4
5:  5
6:  6
7:  7
8:  8
9:  9

I expect "10: 10" to be the last one that is printed. Why does Perl give me a surprise in this case?

like image 742
Haiyuan Zhang Avatar asked Mar 09 '10 09:03

Haiyuan Zhang


1 Answers

sort always defaults to string comparison.

If you want a numeric sort, you have to be explicit.

sort {$a <=> $b} (keys %hash)
like image 69
Quentin Avatar answered Sep 18 '22 15:09

Quentin