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:
  1. 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
  2. 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);

In reply to sort hash keys as numbers and maybe even more... by pg

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.