如何使用Perl来确定两个文件的内容是否相同? [英] How can I use Perl to determine whether the contents of two files are identical?

查看:1139
本文介绍了如何使用Perl来确定两个文件的内容是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题来自于需要确保我对代码所做的更改不会影响其输出到文本文件的值。理想情况下,我会滚动一个子文件,以接受两个文件名和返回1 返回0 是否相同,空格和所有。

This question comes from a need to ensure that changes I've made to code doesn't affect the values it outputs to text file. Ideally, I'd roll a sub to take in two filenames and return 1or return 0 depending on whether the contents are identical or not, whitespaces and all.

由于文本处理是Perl的功能,应该很容易比较两个文件,并确定它们是否相同(未经测试的代码)。

Given that text-processing is Perl's forté, it should be quite easy to compare two files and determine whether they are identical or not (code below untested).

use strict;
use warnings;

sub files_match {

    my ( $fileA, $fileB ) = @_;
    open my $file1, '<', $fileA;
    open my $file2, '<', $fileB;

    while (my $lineA = <$file1>) {

        next if $lineA eq <$file2>;
        return 0 and last;
    }

    return 1;
}

我可以想到的唯一方法就是打开两个文件,并逐行读取它们,直到找到差异。如果没有找到差异,文件必须是相同的。

The only way I can think of (sans CPAN modules) is to open the two files in question, and read them in line-by-line until a difference is found. If no difference is found, the files must be identical.

但是这种方法有限和笨拙。如果总线在两个文件中不同怎么办?我应该打开和关闭以确定行数,然后重新打开以扫描文本? Yuck。

But this approach is limited and clumsy. What if the total lines differ in the two files? Should I open and close to determine line count, then re-open to scan the texts? Yuck.

我在中没有看到任何内容perlfaq5

推荐答案

它在核心

use File::Compare;

if (compare("file1", "file2") == 0) {
  print "They're equal\n";
}

这篇关于如何使用Perl来确定两个文件的内容是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆