Checking if a value in one hash exists in another

M

mwthayer

Hi
I have searched the groups and haven't found exactly what I need. If
this is a duplicate, forgive me.

I need to compare to hashes. I want to know if the value to a certain
key from one hash is found as a value in another hash then print the
key from both hashes where the match.
Example:
Hash 1
Key.......Value
21A00001 Brown Fox
21A00002 Brown Fox
Hash 2
Key....Value
212121 Brown Fox
Result after the compare (a tab delimited file)
21A00001 {tab or \t} 212121
21A00002 {tab or \t} 212121

Grateful for any suggestions
 
X

xhoster

Hi
I have searched the groups and haven't found exactly what I need. If
this is a duplicate, forgive me.

I need to compare to hashes. I want to know if the value to a certain
key from one hash is found as a value in another hash

That isn't what hashes do. If you want to look up by the value, then
you should have made that the key rather than the value.

then print the
key from both hashes where the match.
Example:
Hash 1
Key.......Value
21A00001 Brown Fox
21A00002 Brown Fox

Your values-turned-keys are not unique, so you need a HoA.

my %inverted1;
while (my ($k,$v) = each %hash1) {
push @{$inverted{$v}}, $k
};

Xho
 
J

John Bokma

Hi
I have searched the groups and haven't found exactly what I need. If
this is a duplicate, forgive me.

I need to compare to hashes. I want to know if the value to a certain
key from one hash is found as a value in another hash then print the
key from both hashes where the match.
Example:
Hash 1
Key.......Value
21A00001 Brown Fox
21A00002 Brown Fox
Hash 2
Key....Value
212121 Brown Fox
Result after the compare (a tab delimited file)
21A00001 {tab or \t} 212121
21A00002 {tab or \t} 212121


How about:

hash 1:

'Brown Fox' => [ '21A00001', '21A00002' ],
:
:


hash 2:

'Brown Fox' => [ '212121' ],
:
:


and then:

for my $key ( keys %hash1 ) {

exists $hash2{ $key } or next;

my @items = @{ $hash1{ $key } };

for my $item ( @items ) {

print join( "\t", $item, @{ $hash2{ $key } } ), "\n";
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top