Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^4: Sorting a hash of hashes

by mrc (Sexton)
on May 15, 2012 at 18:50 UTC ( #970694=note: print w/replies, xml ) Need Help??

in reply to Re^3: Sorting a hash of hashes
in thread Sorting a hash of hashes

Thanks for the update!
I have updated the example with few more values. How to display the first 2 (or more) results not just the biggest value and how to sort by first value1 and add value2 as a pair?
I suppose the values must be added to an array, sorted then display first, second, third etc. element of that array. Hash of hashes or hash of arrays are still unclear for me.
__OUTPUT__ For Test1 SUB2 has value1=2800 and value2=0.05 SUB3 has value1=2700 and value2=0.25 For Test2 SUB2... SUB3... etc.

Replies are listed 'Best First'.
Re^5: Sorting a hash of hashes
by NetWallah (Canon) on May 16, 2012 at 01:00 UTC
    Since you did not specify it, I assume you want the comparison done on "value1" only. Based on that, here is the code:
    my %rehash; for my $SUBNAME (sort keys %HoH){ for my $testname (sort keys %{ $HoH{$SUBNAME} }) { my $val = $HoH{$SUBNAME}{$testname}{value1}; if (exists $rehash{$testname}{$SUBNAME}{value1} and $rehash{$testname}{$SUBNAME}{value1} > $val){ # Do not update - greater value exists }else{ $rehash{$testname}{$SUBNAME} = $HoH{$SUBNAME}{$testname}; } } } for my $testname (sort keys %rehash){ print "For $testname:\n"; for my $SUBNAME(sort keys %{ $rehash{$testname} }){ print " $SUBNAME has " , map( {" $_=$rehash{$testname}{$SUBNAME}{$_};"} sort keys %{$r +ehash{$testname}{$SUBNAME}}), ,"\n"; } } __OUTPUT__ For Test1: SUB1 has value1=2300; value2=0.01; SUB2 has value1=2800; value2=0.05; SUB3 has value1=2700; value2=0.25; For Test2: SUB1 has value1=5000; value2=0.34; SUB2 has value1=5500; value2=0.34; SUB3 has value1=5800; value2=0.45; For Test3: SUB1 has value1=3000; value2=0.10; For Test4: SUB1 has value1=7000; value2=0.33;
    At this point, your original problem has been long solved, so please make further enhancements yourself.

                 I hope life isn't a big joke, because I don't get it.

      Now the code is more readable. Thank you!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://970694]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2018-06-17 22:53 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (107 votes). Check out past polls.