knexus has asked for the wisdom of the Perl Monks concerning the following question:
To illustrate, I borrowed an example from perldoc/perldsc on Hashes of Arrays
In the last part of the example I can print out the list by creating a temporary list of all the names in the arrays, then sort and print it. However, at that point I no longer have the "family name" hash entry association. So, I then re-iterate through the hash and arrays to match the sorted members list with their original hash entries and print from there.
What I want is something like this:
astro:jetsons, barney:flinstones, bart:simpsons, elroy:jetsons, fred:flintstone, ...
BTW: normally sorting by hash key (and then possibly within an array) is what I want, so I "think" I have the correct data structure. However, sometimes I will want to sort over all items in all arrays.
The code below works but I just can't help to think that there's an easier or better way to do it.
Any help finding the better way is appreciated.
Thanks
#!/usr/bin/perl -w use strict; use Data::Dumper; my %HoA = ( simpsons => [ "homer", "marge", "bart" ], flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy", "astro" ], ); # # This is the type of sorting normally needed. # print "Sorted by number of members then name\n"; foreach my $family (sort {@{$HoA{$b}} <=> @{$HoA{$a}} || $a cmp $b } k +eys %HoA){ print " $family: \t", join(", ", sort @{ $HoA{$family} }), "\n"; } # # Sometimes this sort will be needed. # my @members; # Dump all names into a single array foreach my $family (keys %HoA ) { push (@members, @{$HoA{$family}} ); } #Sort it and find it's family association for printing foreach my $name (sort @members) { foreach my $family (keys %HoA) { foreach my $test (@{$HoA{$family}}) { print " $name : $family\n" if ($test eq $name); } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Hash of Arrays - Sort over all array entries (flatten first)
by tye (Sage) on Sep 09, 2003 at 21:49 UTC | |
|
Re: Hash of Arrays - Sort over all array entries
by Abigail-II (Bishop) on Sep 09, 2003 at 21:37 UTC | |
by knexus (Hermit) on Sep 09, 2003 at 22:32 UTC | |
by Abigail-II (Bishop) on Sep 09, 2003 at 22:36 UTC | |
by tye (Sage) on Sep 10, 2003 at 16:06 UTC |