This morning I came across this problem, see the below code. For a while, I obviously had the wrong impression, thought hash keys would keep its own "type". Now I realized that Perl actually stringify the hash keys, so when I do a sort keys, it actually gave me the alphabetical order, not the numeric order I was expecting.
I am thinking whether it is more reasonable, to make the native order as the default order, unless:
- there is no native order for that type (for example, I have an OO class called Book, it world be nice if I have a way to define the native order for this class as sort by ISDN number, which is an attribute of the Book class), or
- keys are in different types (for example, some are numbers, some are strings)
then use the stringified order.
use Data::Dumper;
use strict;
my $hash = {};
for (1..100) {#keys are all numbers, from the users' point of view
$hash->{$_} = "a";
}
my @keys = keys %$hash;#this is the internal order, I don't care
print(join(",", @keys));
print "\n", "=" x 70, "\n";
my @sorted = sort @keys;#this will sort as strings!!
print(join(",", @sorted));
print "\n", "=" x 70, "\n";
my @sorted_as_num = sort {$a <=> $b} @keys;#force it to sort as number
print(join(",", @sorted_as_num));
print "\n", "=" x 70, "\n";
print Dumper($hash);