tags:

views:

169

answers:

2
#!/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. I just need someone to explain why Perl gives me a surprise in this case.

+23  A: 

sort always defaults to string comparison.

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

sort {$a <=> $b} (keys %hash)
David Dorward
A: 

Don't forget that the keys in a Perl hash are always stored as strings so the output does make sense.

andeyatz
Perl stores them both as strings _and_ as numbers. The problem here is that by default sort sorts the strings.
mirod
The keys of a hash are stored as strings, but even if they were stored as numbers `sort` still sorts using string comparison.
Brad Gilbert