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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |