Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Sorting perl hash

by haukex (Bishop)
on Mar 06, 2021 at 17:52 UTC ( #11129201=note: print w/replies, xml ) Need Help??


in reply to Sorting perl hash

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.

Replies are listed 'Best First'.
Re^2: Sorting perl hash
by LanX (Cardinal) on Mar 06, 2021 at 17:55 UTC
    > 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 -

    my guess is it's not the first time this OP is here, he just created a new account.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      my guess is it's not the first time this OP is here, he just created a new account.

      Personally I don't think it matters. The question is of good enough quality and includes a pretty much runnable code sample (it's only missing a single "}," whose location is easy enough to guess).

      Sorry, if i have not given much details. It's my first time here.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11129201]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2021-04-16 09:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?