Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by Anonymous Monk
on May 27, 2013 at 00:30 UTC ( [id://1035344]=note: print w/replies, xml ) Need Help??


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

The invert() function from the Var::Pairs module can also do what you want:
my %your_hash = ( aa => 1, bb => 2, cc => 3, dd => 4, ee => 2, ff => 5, gg => 3, hh => 2, ); use Var::Pairs; my %keys_for_each_value = invert(%your_hash); use Data::Dumper 'Dumper'; warn Dumper \%keys_for_each_value;

Replies are listed 'Best First'.
Re^2: Find common values in a hash and print the respective keys
by Jim (Curate) on May 27, 2013 at 01:48 UTC

    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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-19 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found