2010-07-14 59 views
2

例如:如何比较Perl中2个文件中的数据?

文件1:

Apple 
Orange 
grapes 

文件2:

Orange 
grapes 
Apple 

我想检查两个文件是否有不同顺序相同的数据。

如何做到这一点,而无需使用任何外部模块?

+0

你可以执行'diff'这样的命令行工具吗? – 2010-07-14 10:49:44

+1

为什么“不使用任何外部模块”? – 2010-07-14 11:04:58

+0

['File :: Compare'](http://perldoc.perl.org/File/Compare.html)是核心并解决了部分问题。 – daxim 2010-07-14 12:17:30

回答

4
use strict; 
use warnings; 

# $d{LINE} = TALLY 
my ($n, %d) = (1); 
while (<>){ 
    $d{$_} += $n; 
    $n *= -1 if eof; 
} 

# Now get whatever kind of lines you are interested in. 
my @same_in_both_files = grep { $d{$_} == 0 } keys %d; 
my @surplus_in_file1 = grep { $d{$_} > 0 } keys %d; 
my @surplus_in_file2 = grep { $d{$_} < 0 } keys %d; 

# Or just get a true-false verdict. 
my $files_differ = 1 if grep $_, values %d; 
+0

一些更可读的Perl我见过一段时间... – 2010-07-14 13:11:42

3

如果您想使用perl来查找两个文件之间的差异,您可以尝试使用Text::Diff CPAN模块。

+1

我不能使用该主机上的任何extenal模块! – Tree 2010-07-14 10:41:58

+5

是的,你可以。该模块是纯粹的Perl,所以如果你可以在主机上保存一个文件,那么你可以使用它。至少你可以在你编码生命的地方创建一个Text dir,在那里保存http://cpansearch.perl.org/src/ADAMK/Text-Diff-1.37/lib/Text/Diff.pm,然后创建一个Diff dir在那里,保存该目录中的http://cpansearch.perl.org/src/ADAMK/Text-Diff-1.37/lib/Text/Diff/Table.pm,镜像http://中找到的lib目录的内容cpansearch.perl.org/src/ADAMK/Text-Diff-1.37/我不是说这是要使用的模块,只是最有可能使用模块,至少是纯Perl模块 – mirod 2010-07-14 10:53:36

+0

优秀 - 它非常棒有用.... – Tree 2010-07-14 14:16:29

3

手动操作是一个简单的练习。将第一个文件读入一行/ linenumber的散列表,然后从该表中删除第二个文件。如果存在一个使用者的话,把它放到第二个表中。表中的任何内容都表示不匹配的内容,并且表中包含不同行的行号。

4

这是一个简单的事情,即将两个文件的每一行读入一个散列,然后比较两个散列的内容。基本上这是一个初学者的编程练习。

+0

我已根据您的意见解决问题 – Tree 2010-07-14 11:34:10

2

这里有一个简单的方法做你想做的事,perl的:

在pfile1:

Apple 
Orange 
grapes 

在pfile2:

Orange 
grapes 
Apple 

perl脚本:

#!/usr/bin/env perl 

open (FILE1, "pfile1") || die ("Can't open file pfile1 for reading"); 
open (FILE2, "pfile2") || die ("Can't open file pfile2 for reading"); 

my @file1 = <FILE1>; 
my @file2 = <FILE2>; 

@sorted_file1 = sort @file1; 
@sorted_file2 = sort @file2; 

die("Your Files are different\n") 
    unless ($#sorted_file1 == $#sorted_file2); 

for my $item (0 .. $#sorted_file1) { 
    if ($sorted_file1[$item] ne $sorted_file2[$item]) { 
    die("Your Files are different\n"); 
    } 
} 
print "Your Files are the same\n"; 

这是通过阅读文件行放入数组中,然后对数组进行排序。它检查两个数组的长度是否相同,如果两个数组之间的相应索引值不同,则会提前退出。

然后您将收到一条消息,指出这些文件是相同的或不相同的。