Hello, Can you please help me in following scenario in Perl scripting? I want to correlate two text files to get output.
CONSIDER TWO CHEMICAL REACTION:-

    (1)     A+E+C--->F+H+L 
    (2)       A+B--->G+I   




   INPUT_FILE1.TXT
#REACTANT    #REACTION NO.
A                 1
E                 1
C                 1
A                 2
B                 2






INPUT_FILE2.TXT
#PRODUCT       #REACTION NO.
F                  1
H                  1
L                  1
G                  2
I                  2

AND THE OUTPUT SHOULD COME OUT AS:-

reactant: E, product: F
reactant: E, product: H
reactant: E, product: L
reactant: C, product: F
reactant: C, product: H
reactant: C, product: L
reactant: A, product: F
reactant: A, product: H
reactant: A, product: L
reactant: A, product: G
reactant: A, product: I
reactant: B, product: G
reactant: B, product: I

i.e.,we want to correlate each reactant to each product in it's corresponding reaction.

Check the script below, it does what you want:

#!/usr/bin/perl
use warnings;
use strict;

my $rec = [];
open my $fh, '<', 'input_file1.txt' or die "can't open file:$!";
while (<$fh>) {
chomp;
next if /^\#/;
my ( $key, $value ) = split /\s+/, $_, 2;
push @$rec, { $key => $value };
}
close $fh or die "can't close file:$!";

my $rec2 = [];
open $fh, '<', 'input_file2.txt' or die "can't open file:$!";
while (<$fh>) {
chomp;
next if /^\#/;
my ( $key2, $value2 ) = split;
push @$rec2, { $key2 => $value2 };
}
close $fh or die "can't close file:$!";

foreach my $products (@$rec) {
 foreach my $pro ( sort keys %{$products} ) {
    foreach my $reactants (@$rec2) {
        foreach my $rect ( keys %{$reactants} ) {
            print " Product: ", $pro, ", Reactant: ", $rect, $/
              if $products->{$pro} == $reactants->{$rect};
        }
    }
 }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.