Muruganandam
Muruganandam

Reputation: 19

Compare two text files and print the difference

Compare two different text files.

use List::Compare;
use POSIX qw/strftime/;
use strict;
open (CMP_LIST1, "D:\\Compare\\List1.txt") || die ("cannot open general.txt");
open (CMP_LIST2, "D:\\Compare\\List2.txt") || die ("cannot open search.txt");
undef $/;
my $cmp_list1 = <CMP_LIST1>;
my $cmp_list2 = <CMP_LIST2>;
my @cmp1_array = split /\n/, $cmp_list1;
my @cmp2_array = split /\n/, $cmp_list2;
close CMP_LIST1;
close CMP_LIST2;
my $count = scalar @cmp1_array;
for(my $i=0;$i<$count;$i++){
   &Compare($cmp1_array[$i],$cmp2_array[$i]);
}
print "over";
sub Compare {
    my ($cmp1_filename,$cmp2_filename)=@_;
    my $time = strftime('%H_%M_%S',localtime);
    open(OUT,">$time.txt");
    open (F, "$cmp1_filename")||die("$cmp1_filename File cannot open\n");
    open (S, "$cmp2_filename")||die("$cmp2_filename File cannot open\n");
    my @a=<F>;
    my @b=<S>;
    my $lcma = List::Compare->new(\@a, \@b);
    print OUT "$cmp2_filename\n", $lcma->get_complement,"\n";#extra present in the second array
    print OUT "$cmp1_filename\n", $lcma->get_unique,"\n";#extra present in the First array
    close OUT;
    sleep 1;
}

Compare file list, I have given as loop. But I am not getting the exact output.

Please can any one suggest for this process.

Upvotes: 0

Views: 6628

Answers (1)

user966588
user966588

Reputation:

First of all,I don't know why you are using OUT filehandle in print statements. I don't think, It is required.

Also $lcma->get_unique will give you values only in first file/list.
And $lcma->get_complement will give you values only in second file/list.
For Common values in both use $lcma->get_intersection.

Also, you are supposed to close the filehandles at the end.

Here is a code below for your help (Note: I am considering test1 and test2 files contain list of values s)

test1.txt

12345   
abcde   
00000  
33333  

test2.txt

12345   
abcde   
00999   
33322  

list_difference.pl

use strict;
use warnings;
use List::Compare;

open F, "<test1.txt" or die $!;
open S, "<test2.txt" or die $!;
my @a=<F>;
my @b=<S>;
my $lc = List::Compare->new(\@a, \@b);

my @intersection = $lc->get_intersection;
my @firstonly = $lc->get_unique;
my @secondonly = $lc->get_complement;


print "Common Items:\n"."@intersection"."\n";
print "Items Only in First List:\n"."@firstonly"."\n";
print "Items Only in Second List:\n"."@secondonly"."\n";

print "test1.txt \n", $lc->get_unique,"\n"; 
print "test2.txt \n", $lc->get_complement,"\n"; 

close F;
close S;

Please note that the items/values in the files(test1,test2) should be separated on newline and proper spacing also required.

Upvotes: 1

Related Questions