Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

How do I compare key from one hash with values from other?

by mug (Initiate)
on Dec 06, 2001 at 15:55 UTC ( [id://129889]=perlquestion: print w/replies, xml ) Need Help??

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

I have two hashes. The keys of %hash1 are values in %hash2. %hash2 can have multiple values for the same key. I want to find the missing set of values (that is, keys of %hash1) for each key in %hash2.

Example:

my %hash1 = ( A => 5, B => 7, C => 2, D => 8, ); my %hash2 = ( 1234 => "A,C", 4567 => "A,B,D", 5678 => "C", );

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I compare key from one hash with values from other?
by 2501 (Pilgrim) on Dec 06, 2001 at 21:08 UTC

    I am not quite sure I understood your question. Try this out..I think this kludge might be what you are looking for.

    use strict; my %hash1 = ( A => 5, B => 7, C => 2, D => 8, ); my %hash2 = ( 1234 => "A,C", 4567 => "A,B,D", 5678 => "C", ); my %hash3; foreach my $key2 ( keys %hash2 ) { my %temphash = %hash1; foreach ( split /,/, $hash2{$key2} ) { delete $temphash{$_}; $hash3{$key2}= join ',', sort keys %temphash; } } foreach my $key ( keys %hash3 ) { print "$key : $hash3{$key}\n"; }
Re: How do I compare key from one hash with values from other?
by aspect_khaliq (Novice) on Jan 18, 2007 at 11:00 UTC

    This will print missing set of values for keys from Hash1.

    use strict; my %hash1 = ( A => 5, B => 7, C => 2, D => 8, ); my %hash2 = ( 1234 => "A,C", 4567 => "A,D", 5678 => "C", ); my @a = split ",", join ',', values %hash2; my $found = 0; foreach my $key ( keys %hash1 ) { $found = 0; foreach my $val ( @a ) { $found = 1 if $val eq $key; } print "$key => $hash1{$key}\n" if !$found; }

    Output:

    B => 7
Re: How do I compare key from one hash with values from other?
by jdporter (Paladin) on Jan 18, 2007 at 16:00 UTC

    Well, you said "for each hash2 key", not "for all hash2 keys", so my solution is a bit different from the previous ones.

    use strict; my %hash1 = ( A => 5, B => 7, C => 2, D => 8, ); my %hash2 = ( 1234 => "A,C", 4567 => "A,B,D", 5678 => "C", ); while ( my( $key2, $val2 ) = each %hash2 ) { my %keys1; @keys1{ split /,/, $val2 } = (); my @missing = grep { not exists $keys1{$_} } keys %hash1; print "hash2 key '$key2' is missing values '@missing'\n"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-03-29 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found