Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have the following code:
use Data::Dumper; while (<DATA>){ next if /^$/; ($f,$s) = split /\|/,$_; $h{$f} += $f; $h->{$f}{'s'} += $s; } for my $k (sort {$h{$b} <=> $h{$a} } keys %h){ print "Key = $k\nElement 1: $h{$k}\nElement 3: $h->{$k}{'s'}\n"; }; #print Dumper{%{$h}}; __DATA__ 1|2 2|4 2|4 4|3 4|5 5|1 5|2
I want to sort by $h->{$f}{'s'} so that the total of the third element is sorted as: 8 8 3 2 rather than by element two: 10 8 4 1. How can I achieve this? Thanks.

Replies are listed 'Best First'.
Re: Sorting a Hash of Hashes by Value
by ikegami (Patriarch) on Oct 29, 2007 at 13:46 UTC

    Short answer:

    sort { $h->{$b}{s} <=> $h->{$a}{s} } keys %$h

    Do you realize you have two identically-keyed hashes (%h and %$h)? Let's merge the two.

    use strict; use warnings; my %totals; while (<DATA>){ next if /^$/; my ($f,$s) = split /\|/,$_; $totals{$f}{f} += $f; $totals{$f}{s} += $s; } for my $k (sort { $totals{$b}{s} <=> $totals{$a}{s} } keys %totals) { print "Key = $k\n" print "Element 1: $total{$k}{f}\n"; print "Element 3: $total{$k}{s}\n"; }
      I like this approach better of having all total counts merged into one single hash. Thanks for the guidance. Much appreciated.
Re: Sorting a Hash of Hashes by Value
by Anonymous Monk on Oct 29, 2007 at 13:45 UTC
    ?!
    sort { $h->{$b}{'s'} <=> $h->{$a}{'s'} }