📜  使用 Perl 比较文件的内容

📅  最后修改于: 2022-05-13 01:54:48.150000             🧑  作者: Mango

使用 Perl 比较文件的内容

在 Perl 中,我们可以使用File::Compare模块轻松比较两个文件的内容。该模块提供了一个名为compare的函数,它有助于比较指定给它的两个文件的内容作为参数。如果两个文件中存在的数据相同,则函数返回0作为输出,如果传递的文件中的数据不同,则返回值为1 ,如果在访问指定/传递时发生任何错误文件,它将值返回为-1句法:

use File::Compare;
$compare = compare('FILE_NAME_1', 'FILE_NAME_2');

笔记:

例子:文件夹中存在的文件。
当文件的内容相同时:

#!/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 Occured. \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 Occured. \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;

输出: