Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find two matched ID in two files, and then use their values to calculate

Tags:

perl

I have two files as following:

FILE#1

A 20.68
B 17.5
C 15.6
D 20.6
E 27.6

FILE#2

C   16.7
X   2.9
E   7.0
A   15.2

First column is ID and second column is score. I am trying to find matched IDs in both files, and then use corresponding scores from FILE#1 calculate final score (Score2 - Score1) in FILE#2. The following is the result I want:

OUTPUT

C 1.1
E -20.6
A -5.48

Through following code, I could get matched ID, but I have no idea how to call corresponding scores from FILE#2 to do calculation in FILE#2. Your help will be greatly appreciated!

open my $A, 'list1.txt';
open my $B, 'list2.txt';
my $h;
map { chomp; $h{(split /\s+/)[0]} ++} <$A>;


while (<$B>) {
    my @split = split(/\s+/,$_);
    my $ID = $split[0];
    my $score = $split[1];
    print "$ID\t$score\n" if $h{$ID};

}
like image 795
Fengchun Lee Avatar asked Nov 11 '22 01:11

Fengchun Lee


1 Answers

You just need to load your first file into a hash of key value pairs. Then when you iterate on the second file, you can test if each key exists in the previous file.

The following script opens file handles to strings to test the logic. But you can easily revert back to opening up the files for your live script.

use strict;
use warnings;
use autodie;

my %score1 = do {
    #open my $fh1, '<', 'list1.txt';
    open my $fh1, '<', \ "A 20.68\nB 17.5\nC 15.6\nD 20.6\nE 27.6\n";
    map {chomp; split ' ', $_, 2} <$fh1>;
};

#open my $fh2, '<', 'list2.txt';
open my $fh2, '<', \ "C   16.7\nX   2.9\nE   7.0\nA   15.2";

while (<$fh2>) {
    chomp;
    my ($key, $score) = split ' ';
    printf "%s %s\n", $key, $score - $score1{$key} if exists $score1{$key};
}

Outputs:

C 1.1
E -20.6
A -5.48
like image 69
Miller Avatar answered Nov 15 '22 06:11

Miller