Tuesday, July 10, 2007

Numerical sort in Perl

If trying to sort a hash based on key where keys are numerical, using just
foreach $Key (sort keys %Output_Hash) will sort/output values as follows:
1
10
11
...
2
20
21
...

In order to get proper numerical sort, modify above code as this:
foreach $Key (sort {$a <=> $b} keys %Output_Hash)
This will make a comparison on each of the keys and result will be what is needed:
1
2
3
...
10
11

No comments: