若不用File::Compare呢
时间: 2024-01-06 08:03:31 浏览: 27
如果不想使用 `File::Compare` 模块,也可以手动逐行比较两个文件的内容。下面是一个示例代码:
```perl
use strict;
use warnings;
my $file1 = 'file1.txt';
my $file2 = 'file2.txt';
my $fh1;
my $fh2;
my $line1;
my $line2;
my $line_num = 0;
my $is_identical = 1;
open($fh1, '<', $file1) or die "Cannot open file $file1: $!";
open($fh2, '<', $file2) or die "Cannot open file $file2: $!";
while (defined($line1 = <$fh1>) and defined($line2 = <$fh2>)) {
$line_num++;
if ($line1 ne $line2) {
print "Line $line_num is different\n";
$is_identical = 0;
last;
}
}
if ($is_identical and eof($fh1) and eof($fh2)) {
print "The contents of $file1 and $file2 are identical\n";
} else {
print "The contents of $file1 and $file2 are different\n";
}
close($fh1);
close($fh2);
```
其中,`$file1` 和 `$file2` 分别为要比较的两个文件的路径。首先,使用 `open` 函数打开两个文件,然后逐行读取它们的内容,比较每一行是否相同。如果发现某一行不同,就输出错误信息,设置 `$is_identical` 为 0,并退出循环。最后,判断两个文件是否已经读取完毕并且内容完全相同。如果是,则输出匹配信息;否则,输出不匹配信息。最后,使用 `close` 函数关闭两个文件句柄。