Anicet Ebou
Anicet Ebou

Reputation: 21

output values from hash using values from another hash perl

I have two hash:

my %hash1 = {
   "GOKIN_0_1" => "alpha",
   "GOKIN_4_6" => "omega",
   ....
}

my %hash2 = {
   "alpha" => "aaa",
   "omega" => "bbb",
   ...

}

What I want to do is, to print in a file lines a value of hash1 that match key of hash2 to have a file like that:

GOKIN_0_1    aaa  
GOKIN_4_6    bbb
....

Here is part my code to do that:

 my $v1 = values %hash1;

 for my $k1 (keys(%hash1)) {
     print OUT "$v1\t$hash2{$k1}\n";
 }

Thanks you so much.

Upvotes: 0

Views: 74

Answers (2)

Chris Turner
Chris Turner

Reputation: 8142

So first off, your two hashes are declared incorrectly. You've got braces where you want regular brackets. Turning on warnings with use warnings; should highlight that mistake.

my %hash1 = (
   "GOKIN_0_1" => "alpha",
   "GOKIN_4_6" => "omega",
   );

my %hash2 = (
   "alpha" => "aaa",
   "omega" => "bbb",
   );

Once you've got two hashes you can use the value from one - $hash1{$k1} - as the key to the second one like this to link the key $k1 to the second hashes value.

for my $k1 (keys(%hash1)) {
  print OUT "$k1\t$hash2{$hash1{$k1}}\n";
}

Upvotes: 0

stevieb
stevieb

Reputation: 9306

First, hashes are declared with (), not {}. The latter denotes a hash reference.

Now, what you can do is loop over the keys and values of %hash1, check if the value is in %hash2 as a key, then print the required variables if the value does exist as a key:

use warnings;
use strict;

my %hash1 = (
   "GOKIN_0_1" => "alpha",
   "GOKIN_4_6" => "omega",
   "GOKIN_4_9" => "blah",
);

my %hash2 = (
   "alpha" => "aaa",
   "omega" => "bbb",
);

while (my ($k, $v) = each %hash1){
    if (exists $hash2{$v}){
        print "$k\t$hash2{$v}\n";
    }
}

Output:

GOKIN_4_6   bbb
GOKIN_0_1   aaa

Upvotes: 2

Related Questions