Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by abualiga (Scribe)
on Aug 06, 2012 at 19:41 UTC ( #985810=note: print w/ replies, xml ) Need Help??


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

Hi there, give this a try and let me know how if you have questions.

#!/usr/local/bin/perl use 5.016; #version >=5.12 turns on strictures by default use warnings; use autodie qw/ open close /; #saves typing die all the time die "Usage: $0 infile1 infile2\n" unless @ARGV == 2; my %count_cols; my @cols; while( <> ) { # perl will read/process one file in whole then move o +n to the next chomp; # get 1st col from each line using an array slice push @cols, ( split( /\t/, $_ ) )[0]; } for ( @cols ) { $count_cols{ $_ }++; # hash value = how many times does col name a +ppear } my @intersects; # store columns that appear in both files for ( keys %count_cols ) { if( $count_cols{ $_ } == 2 ) { push @intersects, $_; } } # open fileA again and extract fields in second column open IN, "<", "fileA"; while( my $line = <IN> ) { chomp $line; next if ! $line; for my $intersect ( @intersects ) { if( $intersect eq ( split( /\t/, $line ) )[0] ) { my $result = ( split( /\t/, $line ) )[1]; say $result; # prints with \n, supported in >5.10 } } } close IN;


Comment on Re: compare two files by column and return second (matching) column
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-08-20 21:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (124 votes), past polls