lrl1997 has asked for the wisdom of the Perl Monks concerning the following question:
I feel the code I provided below is not fast enough, I would really need some help to improve it's efficiency.
I have two hash tables,
hash1: (keys and values separated by tab)
k_a1 k_b1,k_b2,k_b3
k_a2 k_b4,K_b5
hash2:(keys and values separated by tab)
k_b1 val_a1
k_b2 val_a2
k_b3 val_a3
k_b4 val_a4
k_b5 val_a5
I want to loop through both hash tables and foreach keys in hash2, if the value can be found in the value of hash1, then print out the corresponding keys from both hash1 and hash2 (keys would be keys from hash2, values would be values for hash2 and keys of hash1, all separated by tab): e.g.
k_b1 val_a1 k_a1
k_b2 val_a2 k_a1
k_b3 val_a3 k_a1
k_b4 val_a4 k_a2
k_b5 val_a5 k_a2
This is the code
use strict; sub read_hash { my $fname = shift; open (my $fh, "<",$fname) or die "$!"; my %hash=(); while (<$fh>) { my $line=$_; chomp $line; my ($key,$value)=split /\t/, $line, 2; $hash{$key}=$value; } return \%hash; } my $hash1=shift; my $hash2=shift; my $h1=read_hash("$hash1"); my $h2=read_hash("$hash2"); my @fields; while (my ($k1, $v1) = each %$h1) { @fields=split /,/, $h1->{$k1}; while (my ($k2, $v2) = each %$h2) { if ( grep( /^$k2$/, @fields ) ) { print $k2, "\t", $v2, "\t", "$k1", "\n" } } }
|
|---|