in reply to Sorting multi-hash values

This was my take on the problem:

#!/usr/bin/perl use warnings; use strict; my %hash = (); my %value_hash = (); while(<DATA>) { chomp; my ($first_key, $second_key, $value ) = split /\s+/; $hash{$first_key}{$second_key} = $value; } # # Map the hash of a hash of a value into a # hash of the value containing an array of key pairs. # Then sort on the new hash. # for my $colour ( sort keys %hash ) { for my $device ( sort keys %{$hash{$colour}} ) { my $val = $hash{$colour}{$device}; printf "%-15s %-15s %5d\n", $colour, $device, $val; push @{$value_hash{ $val }} , [ $colour, $device ]; } } print "\n\nSorted Result:\n\n"; for my $val ( sort { $b <=> $a } keys %value_hash ) { for my $key_pair ( @{$value_hash{$val}} ) { printf "%-15s %-15s %5d\n", @$key_pair[0], @$key_pair[1], $val; } } __DATA__ red bike 5 red car 4 red shoes 20 yellow shoes 1 yellow skates 1000
And the output is:

C:\Code>perl multi_hash_sort.pl red bike 5 red car 4 red shoes 20 yellow shoes 1 yellow skates 1000 Sorted Result: yellow skates 1000 red shoes 20 red bike 5 red car 4 yellow shoes 1

Replies are listed 'Best First'.
Re^2: Sorting multi-hash values
by papai (Novice) on Aug 24, 2007 at 13:51 UTC
    I believe this is very close but the problem now is my new hash, "$value_hash", can only hold one unique key. Therefore if I have list of values like:
    colour device value ---------------------- red bike 1000 red shoes 1000 blue car 4 black plane 6 blue boat 1000 pink shoes 5 red car 5
    The $value_hash will only have the following list:
    colour device value ------------------------ blue boat 1000 black plane 6 red car 5 blue car 4
    A hashes' keys must be unique, otherwise they get over written with the most recent entry. To prevent losing data, incase I have count values which are duplicates, I recreate a new hash with 3 keys and a value. The keys are "value", "colour", and "device". Creating New Hash "value_hash" (2nd hash):
    foreach my $colour ( keys %hash) { foreach my $device ( keys %{$hash{$colour}}) { my $val = $hash{$colour}{$device}[0]; $value_hash{$val}{$colour}{$device}[0]++; } }
    After that I then print the key (value) in order:
    for my $value (sort {$b <=> $a} keys %value_hash) { for my $colour ( keys %{$value_hash{$value}}) { for my $os ( keys %{$value_hash {$value}{$colour}}) { printf("\n%-55s %-50s %-10s", $colour, $os, $value); } } }
    Which now produces table...
    colour device value ---------------------- red bike 1000 red shoes 1000 blue boat 1000 black plane 6 pink shoes 5 red car 5 blue car 4
    Thank you for pointing me in the right direction monks...Papai