Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

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

by abualiga (Scribe)
on Aug 06, 2012 at 19:41 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://985810]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-04-18 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found