Perl中的文件比较-逐行或子字符串
我试着比较两个文本文件,得到了下面的perl脚本,但由于某种原因,即使我使用/same/文件作为基础和过滤器,它也不会输出任何内容。我对Perl真的很陌生,所以如果这听起来有任何错误,我深表歉意Perl中的文件比较-逐行或子字符串,perl,file,compare,line,Perl,File,Compare,Line,我试着比较两个文本文件,得到了下面的perl脚本,但由于某种原因,即使我使用/same/文件作为基础和过滤器,它也不会输出任何内容。我对Perl真的很陌生,所以如果这听起来有任何错误,我深表歉意 my $file_base = 'CSP8216.TXT'; my $file_filter = 'CSP8216.TXT'; open my $info_filter, $file_filter or die "Die: Could not open $file_filter: $!"; while
my $file_base = 'CSP8216.TXT';
my $file_filter = 'CSP8216.TXT';
open my $info_filter, $file_filter or die "Die: Could not open $file_filter: $!";
while(my $line_filter = <$info_filter>)
{
open my $info_base, $file_base or die "Die: Could not open $file_base: $!";
while(my $line_base = <$info_base>)
{
if("$line_filter"=="$line_base")
#if(substr($line_filter, 0, 11)==substr($line_base, 0, 11))
{
print $line_base;
}
}
close $info_bae;
}
close $info_filter;
my$file_base='CSP8216.TXT';
my$file_filter='CSP8216.TXT';
打开我的$info\u过滤器、$file\u过滤器或死亡“死亡:无法打开$file\u过滤器:$!”;
while(我的$line\u过滤器=)
{
打开我的$info\u base、$file\u base或die“die:无法打开$file\u base:$!”;
while(我的$line_base=)
{
如果(“$line\u filter”==“$line\u base”)
#if(substr($line_filter,0,11)==substr($line_base,0,11))
{
打印$line_base;
}
}
关闭$info_bae;
}
关闭$info_过滤器;
有人能指出这似乎不起作用的原因吗?使用
eq
来比较字符串:
if($line\u filter eq$line\u base)
也可以使用
使用strict
查看程序中的错误我会做一些不同的事情
显然,如果文件很大,您可能确实希望将其推入数组
use strict;
use warnings;
use Data::Dumper;
my $file_base = '1.TXT';
my $file_filter = '2.TXT';
open ( FILTER, "<$file_filter" )
or die "Die: Could not open $file_filter: $!";
open ( BASE, "<$file_base" )
or die "Die: Could not open $file_base: $!";
my @filterArray = <FILTER>;
my @baseArray = <BASE>;
close BASE;
close FILTER;
unless( arrayDiff( \@filterArray , \@baseArray ) )
{
print "Success!";
}
sub arrayDiff {
my $array1 = shift(@_);
my $array2 = shift(@_);
my %array1_hash;
my %array2_hash;
# Create a hash entry for each element in @array1
for my $element ( @{$array1} ) {
$array1_hash{$element} = @{$array1};
}
# Same for @array2: This time, use map instead of a loop
map { $array2_hash{$_} = 1 } @{$array2};
for my $entry ( @{$array2} ) {
if ( not $array1_hash{$entry} ) {
return 1; #Entry in @array2 but not @array1: Differ
}
}
if ( keys %array1_hash != keys %array2_hash ) {
return 1; #Arrays differ
}
else {
return 0; #Arrays contain the same elements
}
}
使用严格;
使用警告;
使用数据::转储程序;
我的$file_base='1.TXT';
my$file_filter='2.TXT';
打开(过滤器,“使用eq
比较字符串:if($line\u FILTER eq$line\u base)。另外使用strict
查看程序中的错误使用eq时,我编辑了我的问题。谢谢Jens!你不应该更改问题,因为编辑后问题没有意义。我已添加我的评论作为答案。请随意接受和/或删除它