in reply to updated_again: how to loop through hash tables more efficiently

Perhaps the following will assist you:

use Modern::Perl; use File::Slurp qw/read_file/; my ( $hash1, $hash2 ) = @ARGV or die $!; my %hash1 = map { /(.+?),(.+)/; $1 => $2 } grep /.,./, read_file $hash +1; my %hash2 = map { /(.+?),(.+)/; $1 => $2 } grep /.,./, read_file $hash +2; for my $key2 ( sort keys %hash2 ) { for my $key1 ( sort keys %hash1 ) { say "$key2\t$hash2{$key2}\t$key1" if $hash1{$key1} =~ /\b$hash +2{$key2}\b/; } }

Output:

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

A regex is used within map to initialize the hashes with key/value pairs. The grep /.,./ helps insure that the regex can match--in case there are any blank lines (or other non-matching lines) in the files. Instead of splitting %hash1's values on commas, a word-boundary match is used to see if a value in %hash2 exists as a value in %hash1, and both keys are printed if so.

Hope this helps!

Update: Output modified based upon OP's reply to tobyink.

Replies are listed 'Best First'.
Re^2: how to loop through hash tables more efficiently
by lrl1997 (Novice) on Sep 17, 2012 at 23:19 UTC
    really want to try out this code, but my work only have perl 5.8.8, doesn't have v5.10.0 yet, :( Thanks though, any other more efficiently traditional way to do it?

      Ah! Then the following should work:

      use strict; use warnings; use File::Slurp qw/read_file/; my ( $hash1, $hash2 ) = @ARGV or die $!; my %hash1 = map { /(.+?),(.+)/; $1 => $2 } grep /.,./, read_file $hash +1; my %hash2 = map { /(.+?),(.+)/; $1 => $2 } grep /.,./, read_file $hash +2; for my $key2 ( sort keys %hash2 ) { for my $key1 ( sort keys %hash1 ) { print "$key2\t$hash2{$key2}\t$key1\n" if $hash1{$key1} =~ /\b$ +hash2{$key2}\b/; } }