简体   繁体   English

如何在 Perl 中区分两个文件?

[英]How can I diff two files in Perl?

I have two text files which need to have the same values.我有两个需要具有相同值的文本文件。

$ diff A.txt B.txt
4a5
> I have this extra line.
$

Open files in Perl在 Perl 中打开文件

open (ONE, "<A.txt");
open (TWO, "<B.txt");

How can I do such a diff from within Perl?我怎样才能在 Perl 中做这样的差异? Does Perl have a inbuilt diff or do I need to use the unix diff utility? Perl 有内置差异还是我需要使用 unix diff实用程序? I don't want to implement my own diff algorithm for this.我不想为此实现我自己的差异算法。

I do need the information as to where my files differ, but I do not need to use the unix diff utility necessarily.我确实需要有关我的文件在哪里不同的信息,但我不一定需要使用 unix diff实用程序。 That was just an example.那只是一个例子。

You could try using Text::Diff您可以尝试使用Text::Diff

Alternatively, the UNIX utility could be an option.或者,UNIX 实用程序可能是一个选项。

If I only needed to know that they were the same (ie not discover how they are different), I'd just use Digest::MD5 to see if they come up with the same digest.如果我只需要知道它们是相同的(即不知道它们有什么不同),我只需使用Digest::MD5来查看它们是否得出相同的摘要。 There's a vanishingly small chance that two different files could have the same MD5 digest, so you might even try Digest::SHA1 .两个不同的文件可能具有相同的 MD5 摘要的可能性微乎其微,因此您甚至可以尝试Digest::SHA1

If you want to find out which lines are different, then you can use Algorithm::Diff , perhaps in conjunction with Tie::File .如果您想找出哪些行不同,那么您可以使用Algorithm::Diff ,也许与Tie::File结合使用。 However, there is also a diff program that comes with Algorithm::Diff if you don't have a diff tool on your target platform.但是,如果您的目标平台上没有 diff 工具, Algorithm::Diff也有一个diff程序。 Although you can shell out to that, you might just want to copy what it does into a subroutine.尽管您可以为此付出代价,但您可能只想将其功能复制到子例程中。 Text::Diff is built on top of Algorithm::Diff , so it might already do want you want. Text::Diff 建立在Algorithm::Diff之上,所以它可能已经想要你想要的了。

No, Perl doesn't have an inbuilt "diff" facility.不,Perl 没有内置的“差异”工具。 Either you use an external module, or use Perl's data structures(hashes, arrays etc) or you create filehandles for both files, and iterate the files using the filehandle (while loops), comparing them line by line.要么使用外部模块,要么使用 Perl 的数据结构(散列、数组等),或者为两个文件创建文件句柄,并使用文件句柄(while 循环)迭代文件,逐行比较它们。 This method assumes your files are sorted.此方法假定您的文件已排序。 Another not so elegant way is to call "diff" from Perl, but I advise against that.另一种不太优雅的方法是从 Perl 调用“diff”,但我建议不要这样做。

Lastly, if Perl is not a must, just use the Unix diff utility (write a shell script).最后,如果 Perl 不是必须的,只需使用 Unix diff实用程序(编写一个 shell 脚本)。

You can the core module File::Compare :您可以使用核心模块File::Compare

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

Documentation is here .文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM