How can I diff two files in Perl?

拥有回忆 提交于 2019-12-10 12:55:25

问题


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

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

How can I do such a diff from within Perl? Does Perl have a inbuilt diff or do I need to use the unix diff utility? 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. That was just an example.


回答1:


You could try using Text::Diff

Alternatively, the UNIX utility could be an option.




回答2:


If I only needed to know that they were the same (i.e. not discover how they are different), I'd just use Digest::MD5 to see if they come up with the same digest. There's a vanishingly small chance that two different files could have the same MD5 digest, so you might even try Digest::SHA1.

If you want to find out which lines are different, then you can use Algorithm::Diff, perhaps in conjunction with 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. 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.




回答3:


No, Perl doesn't have an inbuilt "diff" facility. 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. This method assumes your files are sorted. Another not so elegant way is to call "diff" from Perl, but I advise against that.

Lastly, if Perl is not a must, just use the Unix diff utility (write a shell script).



来源:https://stackoverflow.com/questions/3581749/how-can-i-diff-two-files-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!