Reputation: 71
I have two files I have read into 2 seperate hashes. The first file has two columns and looks like:
123456789 11111
234567891 22222
345678912 33333
The second file has one column, which looks like:
123456789
010124561
100324531
I want to compare the two hashes and whenever there is a match between the first columns of the two files, it should print to a new file with the results of the first column. This is what I have so far...
#!/usr/bin/perl
use Sys::Hostname;
use lib "$ENV{HOME}/common/lib/perl";
use strict;
use warnings;
my %oid;
my %oid2;
my %atom;
my %newline;
my $oid;
my $atom;
my @line = ();
my @line2 = ();
my @oid = ();
my @oid2 = ();
my $input = 'file.txt';
my $input2 = 'file2.txt';
my $output = 'outputfile.txt';
open (IN, "<$input");
open (IN2, "<$input2");
open (OUT, "+>$output");
for my $line (<IN>) {
chomp $line;
my @line = split /\t/, $line;
push( @oid, $line[0] );
$oid{ $line[0] } = $line[0];
$atom{ $line[0] } = $line[1];
}
for my $line2 (<IN2>) {
chomp $line2;
my @line2 = split /\t/, $line2;
push( @oid2, $line2[0] );
$oid2{ $line2[0] } = $line2[0];
}
Upvotes: 2
Views: 257
Reputation: 39158
Too much code. Know your Unix toolbox!
comm -12 <(cut -d' ' -f1 file1|sort) <(sort file2)
Upvotes: 2
Reputation: 16974
One way:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
$\="\n";
open my $fh1, '<', 'f1' or die $!;
open my $fh2, '<', 'f2' or die $!;
my %h1;
while (<$fh1>){
chomp;
my ($x,$y)=split;
$h1{$x}=$y;
}
while(<$fh2>){
chomp;
print if exists $h1{$_};
}
Upvotes: 1