Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: compare two files by column and return second (matching) column

by Kenosis (Priest)
on Aug 06, 2012 at 20:36 UTC ( #985828=note: print w/ replies, xml ) Need Help??


in reply to compare two files by column and return second (matching) column

Excellent suggestions have been given. Here's another option:

use Modern::Perl; open my $fhA, '<', 'FileA.txt' or die $!; my %hash = map { /(.+)\t(.+)/; $1 => $2 } grep /\S/, <$fhA>; close $fhA; open my $fhB, '<', 'FileB.txt' or die $!; say for map { chomp; $hash{$_} } grep /\S/, <$fhB>; close $fhB;

Output:

zzzzz bbbbb xxxxx

The first map uses a regex to grab the key/value pairs from FileA for placement into %hash. The second map uses the single entry from FileB to show that entry's associated value from FileA. Since there were blank lines in the files (from your data set), grep /\S/ was used to filter those.

Hope this helps!


Comment on Re: compare two files by column and return second (matching) column
Select or Download Code
Re^2: compare two files by column and return second (matching) column
by ejbiers (Initiate) on Aug 07, 2012 at 13:45 UTC

    This is perfect! Thanks! However, is there a way to print the results into an output file?

      You're most welcome, ejbiers! Yes, the script below includes printing the results to a file:

      use Modern::Perl; open my $fhA, '<', 'FileA.txt' or die $!; my %hash = map { /(.+)\t(.+)/; $1 => $2 } grep /\S/, <$fhA>; close $fhA; open my $fhB, '<', 'FileB.txt' or die $!; my @output = map { chomp; $hash{$_} } grep /\S/, <$fhB>; close $fhB; open my $fhO, '>', 'Output.txt' or die $!; say $fhO $_ for @output; close $fhO;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2015-07-07 14:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (89 votes), past polls