Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Comparing values in same hash?

by Not_a_Number (Parson)
on Jul 22, 2011 at 17:59 UTC ( #916178=note: print w/ replies, xml ) Need Help??


in reply to Comparing values in same hash?

Here's my solution, probably a little more complex than Marshall's above.

It does two passes over the hash. In the first pass, it builds a HoA where the keys are the all the words from 'yourStr' and the values are arrays holding the IDs concerned, which ends up looking like this:

good => [ 'ID3' ], hello => [ 'ID1', 'ID3', 'ID2' ], goodbye => [ 'ID1' ], where => [ 'ID1' ]

On the second pass, it checks if the value of 'myStr' is in the HoA, and prints out any matches, excluding 'internal' matches (ie if for the same ID 'hello' were to appear in both 'myStr' and 'yourStr').

use strict; use warnings; my $h = { ID1 => { myStr => 'hello', description => 'Description 1', yourStr => [ 'goodbye', 'where', 'hello'] }, ID2 => { myStr => 'good', description => 'Description 2', yourStr => [ 'hello', ] }, ID3 => { myStr => 'testvar', description => 'Description 2', yourStr => [ 'hello', 'good' ] }, }; my %yourstr; for my $id ( keys %$h ) { for ( @{ $h->{$id}->{yourStr} } ) { push @{ $yourstr{$_} }, $id; } } for my $id ( keys %$h ) { my $mystr = $h->{$id}->{myStr}; if ( $yourstr{$mystr} ) { my @matches = grep { $_ ne $id } @{ $yourstr{$mystr} }; print "'$mystr' in $id matches @matches\n"; } }

Output:

'hello' in ID1 matches ID3 ID2 'good' in 1D2 matches ID3


Comment on Re: Comparing values in same hash?
Select or Download Code
Re^2: Comparing values in same hash?
by legendx (Acolyte) on Jul 24, 2011 at 17:27 UTC
    This is a great solution as well. I will break the code down to understand it further and post any questions. Thank you

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-07-30 23:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (241 votes), past polls