我想比较我从我编写的perl脚本生成的两个文本文件。 我想从这两个文本文件中打印出匹配的结果。我试着查看人们在stackoverflow上提出的几个答案和问题,但它对我不起作用。这是我尝试过的。
my $file1 = "Scan1.txt";
my $file2 = "Scan2.txt";
my $OUTPUT = "final_result.txt";
my %results = ();
open FILE1, "$file1" or die "Could not open $file1 \n";
while(my $matchLine = <FILE1>)
{
$results{$matchLine} = 1;
}
close(FILE1);
open FILE2, "$file2" or die "Could not open $file2 \n";
while(my $matchLine =<FILE2>)
{
$results{$matchLine}++;
}
close(FILE2);
open (OUTPUT, ">$OUTPUT") or die "Cannot open $OUTPUT \n";
foreach my $matchLine (keys %results) {
print OUTPUT $matchLine if $results{$matchLine} ne 1;
}
close OUTPUT;
我希望输出的输出
FILE1.TXT 数据1 数据2 数据3
FILE2.TXT DATA2 DATA1
OUTPUT 数据1 数据2
答案 0 :(得分:1)
您的问题是您的哈希现在具有以下状态:
这种歧义会使你的检查(hash ne 1)失败。
您的算法所需的最小更改将是:
my $file1 = "Scan1.txt";
my $file2 = "Scan2.txt";
my $OUTPUT = "final_result.txt";
my %results = ();
open FILE1, "$file1" or die "Could not open $file1 \n";
while(my $matchLine = <FILE1>)
{
$results{$matchLine} = 1;
}
close(FILE1);
open FILE2, "$file2" or die "Could not open $file2 \n";
while(my $matchLine =<FILE2>)
{
$results{$matchLine} = 2 if $results{$matchLine}; #Only when already found in file1
}
close(FILE2);
open (OUTPUT, ">$OUTPUT") or die "Cannot open $OUTPUT \n";
foreach my $matchLine (keys %results) {
print OUTPUT $matchLine if $results{$matchLine} ne 1;
}
close OUTPUT;