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

Dear monks,

I have some paired values which i've mapped into a hash.

The data looks something like this (one is the key, the other is the value):

my %hash = map {$gp1[$_] => $gp2[$_]} 0 .. $#gp1; #13488050:c183911-182727 57165207:6809301-6810488
I also have a large space-delimited table with keys and values as above in the first and second columns. I want to find all lines that match each key-value pairs as the first and second values in each row ($1 and $2 in the loop below) and print them with the rest of the data in each line.

I have a loop going though the table below, but am not sure how to check if $1 and $2 are equal to a key-value pair in the hash. Hope someone can help!

foreach my $line (@blast) { if ($line =~ /gi\|(\d+.{1,2}\d+\-.{0,1}\d+)\s+gi\|(\d+.{1,2}\d ++\-.{0,1}\d+)\s+(\d{0,2}.{0,2}\d{0,2}.{0,2}\d{0,3})\s+\d+\s+(\d+.{0,3 +}\d+)\s+\d+\s+\d+\s+\d+\/\d+\s+(\d+)/) { ###print "$1\t$2\t$5\n"; my $n1 = $1; push @id1, "$1 "; push @id2, "$2 "; push @percent_id, "$5 "; # need to here check whether $1 eq key and $2 eq value + but am stuck! } }

Replies are listed 'Best First'.
Re: hash confusion
by jhourcle (Prior) on Jul 18, 2005 at 18:26 UTC
    if (exists($hash{$1}) and $hash{$1} eq $2) { ... }

    Basically, you make sure that $1 is in the hash, and that its associated value is the same as $2

Re: hash confusion
by jimbojones (Friar) on Jul 18, 2005 at 18:22 UTC
    if ( $hash{$1} eq $2 ) { print "$1 is in hash with a value of $2\n"; }
    That's if the values of the hash are strings. Possibly you'd have to use == instead of eq if they are numbers. I'm not 100% sure based on your post, but it looks like the hash key and values have ":" and "-" in them.

    - j

Re: hash confusion
by socketdave (Curate) on Jul 18, 2005 at 18:21 UTC
    I believe that you're looking for this:

    if ( $hash{$1} == $2 )
Re: hash confusion
by hubb0r (Pilgrim) on Jul 19, 2005 at 01:36 UTC
    Just as a side note, you may want to add some comments and whitespace to the gigantic unintelligible regex you have there. Read perldoc perlre... what you are looking for is the /x modifier.