in reply to Compare 3 files and print matches in Perl

Sure, if you can do it with two files, just repeat with a third file.

Store file 1 in a hash, with the keys being the comparison key between files. Then read file 2, and modify your hash values for each item in file 2. You could either keep in the hash items that are common to the first two files, and then use it as a test for file 3; or you could implement each hash value as a counter, and output any hash key where the counter reaches 3.

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

Replies are listed 'Best First'.
Re^2: Compare 3 files and print matches in Perl
by Anonymous Monk on Oct 26, 2015 at 00:51 UTC

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

      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.