比较两个不同的文本文件。
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;
}
比较文件列表,我给出了循环。但我没有得到确切的输出。
任何人都可以建议这个过程。
答案 0 :(得分:1)
首先,我不知道您在OUT
语句中使用print
文件句柄的原因。
我不认为,这是必需的。
同样$lcma->get_unique
只会在第一个文件/列表中为您提供值
$lcma->get_complement
只会在第二个文件/列表中为您提供值
对于公用值,请使用$lcma->get_intersection
。
此外,您应该在最后关闭文件句柄。
下面的代码是您的帮助(注意:我正在考虑test1和test2文件包含值列表s)
12345
abcde
00000
33333
12345
abcde
00999
33322
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;
请注意,文件中的项目/值(test1,test2)应该在换行符上分开,并且还需要适当的间距。