Perl's documentation for sort provides the following example:

# sort numerically ascending @articles = sort {$a <=> $b} @files;

So applying that to your code, it would look like this:

foreach my $key ( sort { $a <=> $b } keys %base_position ) { ...

Perl's sort defaults to sorting ASCII-betically. If you want it to sort numerically, you need to supply a code block that uses the <=> operator (perlop).

Update:

Your second question is a good one. One area where you could improve would be to use an array instead of a hash as an accumulator. Although both array and hash lookups are O(1), the constant factor involved in hash lookups is more expensive than for array lookups. Since you're doing lookups 40 to 50 times per line from the file, and since all of your indices seem to be within a narrow numeric range from zero to fifty, an array makes a lot of sense. This would also eliminate the need to sort.

However, it's possible you're IO bound anyway, and that the time spent in calculating hash lookups is shadowed by waiting for input. ....profiling would tell a lot.


Dave


In reply to Re: How to sort hash keys numerically? by davido
in thread How to sort hash keys numerically? by rnaeye

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.