I have the below hash structure, hash of hash. I need to sort the inner hash referenced by test1, test2, test3, test4. The outer keys need not be changed.
$VAR1 = { '191' => { 'test1' => { 'score' => '9.18' }, 'test2' => { 's +core' => '2.84' }, 'test3' => { 'score' => '15.62' }, 'test4' => { ' +score' => '11.84' }, '190' => { 'test1'=> { 'score' => '13.28' }, 'test2' => { 's +core' => '-47.56' }, 'test3' => { 'score' => '18.50' }, 'test4' => { ' +score' => '14.88' } } }
I am trying to sort the hash based on the 'score' value. The sorting should happen only among whats inside of the main keys '191' and '190' . See below hash structure for expected result.
$VAR1 = { '191' => {'test3' => { 'score' => '15.62' }, 'test4' => { 's +core' => '11.84' } 'test1' => { 'score' => '9.18' }, 'test2' => { 'sc +ore' => '2.84' }, ​ '190' => { 'test3' => { 'score' => '18.50' }, 'test4' +=> { 'score' => '14.88' } 'test1'=> {'score' => '13.28' }, 'test2' => { 'sco +re' => '-47.56' } } }
Sorting is to be done based on descending score value. I have tried out the below code but it kind-of sorts based on the main-key. I need output as shown in the expected hash structure.
my @sort_by_rank; for my $key1 (keys %rankBased) { for my $key2 (keys %{$rankBased{$key1}}) { @sort_by_rank = sort{ $rankBased{$b}{$key2}{score} <=> $rankBa +sed{$a}{$key2}{score} } keys %rankBased; } }
Here %rankBased is the hash. Please help.

In reply to 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.