Perl 比较文件的内容
在Perl中,我们可以通过使用 File::Compare 模块轻松地比较两个文件的内容。这个模块提供了一个叫做 compare 的函数,它有助于比较两个文件的内容,并将其作为参数指定给它。如果两个文件中的数据相同,该函数的输出为 0 ,如果传递的文件中的数据不同,返回值为 1 ,如果在访问指定/传递的文件时发生任何错误,返回值为 -1。
语法
use File::Compare;
$compare = compare('FILE_NAME_1', 'FILE_NAME_2');
注释
- 相同的内容。返回值 [0]
- 不同的内容。 返回值 [1]
- 访问文件时出错。返回值 [-1]
例如:
文件夹中存在的文件。
当文件的内容相同时
#!/usr/bin/perl
print "Content-type: text/html\n\n";
# Module to use compare function
use File::Compare;
# compare function to access the passed files.
compare = compare("gfg_a.txt", "gfg_c.txt");
# checking if the files are same
if (compare == 0)
{
print "Files are equal. \n";
}
# checking if the files are different
elsif (compare == 1)
{
print "Files are not equal. \n";
}
# checking if the file is not accessible
elsif(compare == -1)
{
print "Error Occurred. \n";
}
exit;
输出
当文件的内容不同时
#!/usr/bin/perl
print "Content-type: text/html\n\n";
# Module to use compare function
use File::Compare;
# compare function to access the passed files.
compare = compare("gfg_a.txt", "gfg_b.txt");
# checking if the files are same
if (compare == 0)
{
print "Files are equal. \n";
}
# checking if the files are different
elsif (compare == 1)
{
print "Files are not equal. \n";
}
# checking if the file is not accessible
elsif(compare == -1)
{
print "Error Occurred. \n";
}
exit;
输出
当文件无法访问时
#!/usr/bin/perl
print "Content-type: text/html\n\n";
# Module to use compare function
use File::Compare;
# compare function to access the passed files.
compare = compare("gfg_a.txt", "gfg_d.txt");
# checking if the files are same
if (compare == 0)
{
print "Files are equal. \n";
}
# checking if the files are different
elsif (compare == 1)
{
print "Files are not equal. \n";
}
# checking if the file is not accessible
elsif(compare == -1)
{
print "Error occurred. The file is not accessible. \n";
}
exit;
输出