in reply to Comparing values in same hash?

This is just a simple nested foreach loop. outer loop iterates over all id's. inner loop iterates over all id's except the current id (skips itself which may or may not be part of the requirements?). Note: grep is used in a scalar context which is the number of matches.
#!/usr/bin/perl -w use strict; my %hash= ( 'ID1' => { 'myStr' => 'hello', 'description' => 'Description 1', 'yourStr' => [ 'goodbye', 'where' ] }, 'ID2' => { 'myStr' => 'good', 'description' => 'Description 2', 'yourStr' => [ 'hello', ] }, 'ID3' => { 'myStr' => 'testvar', 'description' => 'Description 2', 'yourStr' => [ 'hello', 'good' ] }, ); foreach my $id (keys %hash) { my $mystr = $hash{$id}{myStr}; foreach my $compareid (grep{$_ ne $id}keys %hash) { if (grep{ $_ eq $mystr} @{$hash{$compareid}{yourStr}}) { print "$id myStr=$mystr found in $compareid yourStr=@{$hash +{$compareid}{yourStr}}\n"; } } } __END__ ID1 myStr=hello found in ID3 yourStr=hello good ID1 myStr=hello found in ID2 yourStr=hello ID2 myStr=good found in ID3 yourStr=hello good

Replies are listed 'Best First'.
Re^2: Comparing values in same hash?
by legendx (Acolyte) on Jul 24, 2011 at 17:20 UTC
    Thanks, this is a simple approach that works. I tried a nested foreach loop but my results kept printing the wrong information. Adding the grep in works great.