Perl - Compare 2 Arrays

Hi all,

I have the following script where the contents of file1 and file2 would be something like this:

file1:

56790,0,0,100998765
89756,0,0,100567876
867645,1,3,678777654

file2:

56790,0,0,100998765
65776,0,0,4766457890
+5896,0,0,675489876

What I then want to do is check if each of the 4 comma separated values on each line exists somewhere in the other file. So in the above case clearly the line that says 56790,0,0,100998765 is in both files so I'd like it to return true. I'd like to return false for any line that doesn't exist in the other file. The order of the values in each csv line is also important.

So far I have:

$input_file1="home/file1";
open(DAT1, $input_file1) || print "Could not open file1!";
@raw_data1=<DAT1>;
close(DAT1);

$input_file2="home/file2";
open(DAT2, $input_file2) || print "Could not open file2!";
@raw_data2=<DAT2>;
close(DAT2);

foreach $line (@raw_data1)
{
chop($line);
($v1,$v2,$v3,$v4)=split(/,/,$line);
if ($v1 ......

It's at this point that I get stuck. I've seen plenty of examples that compare just one value from each array but I want to make sure that all 4 of my comma seperated values exist in the other array in exactly the same order.

Any ideas?

Many thanks in advance.

The customary solution is to read the first file into a hash, and then if the hash key exists for a line you read from the second file, then it obviously existed in the first file.

Hi,

Is it ok for you to use some other command.

try below one:

paste -d"," file1 file2 > temp.txt
awk '{
if ($1=$5 && $2==$6 && $3==$7 && $4==$8)
print true
}' temp.txt
rm temp.txt

That requires two passes over the input data, and uses a temporary file. You can do better with just awk.

awk 'NR == FNR { a[$0]++; next } { if (a[$0]) next; print }' file1 file2

... will print all the lines which exist in file2 but not in file1.

The same in Perl:

perl -nle 'if ($. == ++$i) { $a{$_}++; close ARGV if eof; next; }
print unless $a{$_}' file1 file2

Perfect, thanks.

I used the last Perl soultion which works brilliantly.