in reply to Re: Compare 3 files and print matches in Perl
in thread Compare 3 files and print matches in Perl

I am new to Perl, would you show me an example of the code I would need to add to my existing code?

  • Comment on Re^2: Compare 3 files and print matches in Perl

Replies are listed 'Best First'.
Re^3: Compare 3 files and print matches in Perl
by Laurent_R (Canon) on Oct 26, 2015 at 16:31 UTC
    Hi,

    this is a simplified version checking 3 files:

    use strict; use warnings; my %result; open my $A, "<", "file1" or die "could not open file1 $!"; while (<$A>) { chomp; my $key = (split /\t/, $_)[0]; $result{$key} = 1; } close $A; open my $B, "<", "file2" or die "could not open file2 $!"; while (<$B>) { chomp; my $key = (split /\t/, $_)[0]; $result{$key}++; } close $B; open my $C, "<", "file3" or die "could not open file3 $!"; while (<$C>) { chomp; my $key = (split /\t/, $_)[0]; if ($result{$key} == 2) { # this key has been seen in both previou +s files print "Line with $key is present in all three files\n"; } } close $C;
    The value in the %result hash is basically a counter saying how many times you've seen the key. If you find in file3 a key that has already been seen twice, then the key is present in all 3 files. Please note that this assumes that the key cannot be more than once in file2, but only rather small changes would be required to take this possibility into account.

    Update: when reading your answer, I only reread the narrative of your original post, without looking at the file samples. I assumed above that all your three files had the same structure, but only see now that they don't. A few minor changes are needed to cope with the actual structure of your files, but I guess that I still gave you the general idea of the solution.