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

Here is what I have:
use strict; my %hash = (name1 => {iid1 => '6', iid2 => '3', iid3 => '4'}, name2=> { iid4 => '3', iid6 => '5', iid2 => '2'} ); foreach my $name (keys %hash) { my $count=0; print "Name: $name\n"; foreach my $iid (keys %{$hash{$name}}) { print "$hash{$name}{$iid}\t\t $iid\n"; $count=$hash{$name}{$iid} + $count; } print "$count\t\t TOTAL\n\n"; }
Here is what I get:
Name:   name2
3   iid4
5   iid6
2   iid2
10   TOTAL

Name:   name1
6   iid1
3   iid2
4   iid3
13   TOTAL

Here is what I want:

Name:   name2
5   iid6
3   iid4
2   iid2
10   TOTAL

Name:   name1
6   iid1
4   iid3
3   iid2
13   TOTAL

How do I get where I need to be?? Much thanks in advance.

Replies are listed 'Best First'.
Re: Sorting an HoH (Or Something?)
by Limbic~Region (Chancellor) on Mar 26, 2004 at 16:10 UTC
    Anonymous Monk,
    I am guessing that you want the first level sorted in decending ASCIIBetical order and the second level sorted decending numerically by value.
    #!/usr/bin/perl use strict; use warnings; my %hash = ( name1 => {iid1 => 6, iid2 => 3, iid3 => 4}, name2 => {iid4 => 3, iid6 => 5, iid2 => 2} ); for my $name ( sort {$b cmp $a} keys %hash ) { my $count; print "Name: $name\n"; for my $iid ( sort {$hash{$name}{$b} <=> $hash{$name}{$a}} keys %{ + $hash{$name} } ) { print "$hash{$name}{$iid}\t\t $iid\n"; $count += $hash{$name}{$iid}; } print "$count\t\t TOTAL\n\n"; }
    Cheers - L~R
Re: Sorting an HoH (Or Something?)
by borisz (Canon) on Mar 26, 2004 at 16:14 UTC
    sort your keys by the value. Replace your second foreach line with this line.
    foreach my $iid ( sort { $hash{$name}{$b} <=> $hash{$name}{$a} } keys + %{$hash{$name}}) {
    Boris
Re: Sorting an HoH (Or Something?)
by Art_XIV (Hermit) on Mar 26, 2004 at 16:33 UTC

    More details:

    Remember that the $a and $b in your sort method are going to be doing comparisons based upon what might other wise be in your $_, so, if you need to sort the based upon the values that you would access like so:

    $hash{$name}{$_}

    You'd sort with $a and $b almost the same way:

    $hash{$name}{$b} <=> $hash{$name}{$a}

    The $b goes before the $a to ensure descending order.

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"