Hashes are always unordered (unless you use special modules), and so the two hashes you have posted above are identical. The most common desire is to output hashes in a sorted manner, or, in your case, you seem to want to store the keys in a sorted order in an array. However, note that the way you have posted the data above is not runnable code, and it makes it unclear what the actual hash format is - see How do I post a question effectively? and Short, Self-Contained, Correct Example. I have made a guess about the hash's format below.

As far as I can tell, you only need to loop over the keys of the outer hash, and then sort the keys of the inner hash based on their value. That would look like this:

use warnings; use strict; use Data::Dumper; my %rankBased = ( 190 => { test1 => { score => '13.28' }, test2 => { score => '-47.56' }, test3 => { score => '18.50' }, test4 => { score => '14.88' }, }, 191 => { test1 => { score => '9.18' }, test2 => { score => '2.84' }, test3 => { score => '15.62' }, test4 => { score => '11.84' }, }, ); for my $key1 (keys %rankBased) { my @sort_by_rank = sort { $rankBased{$key1}{$b}{score} <=> $rankBased{$key1}{$a}{score} } keys %{$rankBased{$key1}}; print Dumper(\@sort_by_rank); } __END__ $VAR1 = [ 'test3', 'test4', 'test1', 'test2' ]; $VAR1 = [ 'test3', 'test4', 'test1', 'test2' ];

Update: See also "How do I sort a hash (optionally by value instead of key)?" in perlfaq4 and "Access and Printing of a Hash of Hashes" in perldsc.


In reply to Re: Sorting perl hash by haukex
in thread Sorting perl hash by paul05

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.