Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: Find common values in a hash and print the respective keys

by Jim (Curate)
on May 27, 2013 at 01:48 UTC ( #1035345=note: print w/ replies, xml ) Need Help??


in reply to Re: Find common values in a hash and print the respective keys
in thread Find common values in a hash and print the respective keys

Here's a version optimized for clarity and verisimilitude.

#!perl # # farm.pl use strict; use warnings; # Lookup table of farm animals by home my %home_of = ( Cat => 'House', Cow => 'Field', Dog => 'Yard', Goat => 'Barn', Hamster => 'House', Hen => 'Coop', Horse => 'Barn', Sheep => 'Barn', Pig => 'Sty', Rooster => 'Yard', ); my %animals_by; # Add each animal to a list of farm animals by home... while (my ($animal, $home) = each %home_of) { push @{ $animals_by{$home} }, $animal; } # Print ordered lists of animals by an ordered list of homes... for my $home (sort keys %animals_by) { my $list_of_animals = join ', ', sort @{ $animals_by{$home} }; print "$home\t$list_of_animals\n"; } __END__ Barn Goat, Horse, Sheep Coop Hen Field Cow House Cat, Hamster Sty Pig Yard Dog, Rooster


Comment on Re^2: Find common values in a hash and print the respective keys
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1035345]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (13)
As of 2015-07-03 09:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (51 votes), past polls