【发布时间】:2014-12-08 13:54:29
【问题描述】:
我是 perl 的新手,并在以下位置发现了解决方案: Perl: Compare Two CSV Files and Print out differences
我已经经历了几十个其他解决方案,这是最接近的,除了我不想找到 2 个 CSV 文件之间的差异,我想找到第二个 CSV 文件在列和行中与第一个文件匹配的位置。我如何修改以下脚本以查找列/行中的匹配项而不是差异。我希望剖析这段代码并从那里学习数组,但想找出这个应用程序的解决方案。非常感谢。
use strict;
my @arr1;
my @arr2;
my $a;
open(FIL,"a.txt") or die("$!");
while (<FIL>)
{chomp; $a=$_; $a =~ s/[\t;, ]*//g; push @arr1, $a if ($a ne '');};
close(FIL);
open(FIL,"b.txt") or die("$!");
while (<FIL>)
{chomp; $a=$_; $a =~ s/[\t;, ]*//g; push @arr2, $a if ($a ne '');};
close(FIL);
my %arr1hash;
my %arr2hash;
my @diffarr;
foreach(@arr1) {$arr1hash{$_} = 1; }
foreach(@arr2) {$arr2hash{$_} = 1; }
foreach $a(@arr1)
{
if (not defined($arr2hash{$a}))
{
push @diffarr, $a;
}
}
foreach $a(@arr2)
{
if (not defined($arr1hash{$a}))
{
push @diffarr, $a;
}
}
print "Diff:\n";
foreach $a(@diffarr)
{
print "$a\n";
}
# You can print to a file instead, by: print FIL "$a\n";
好的,我意识到这正是我想要的:
use strict;
use warnings;
use feature qw(say);
use autodie;
use constant {
FILE_1 => "file1.txt",
FILE_2 => "file2.txt",
};
#
# Load Hash #1 with value from File #1
#
my %hash1;
open my $file1_fh, "<", FILE_1;
while ( my $value = <$file1_fh> ) {
chomp $value;
$hash1{$value} = 1;
}
close $file1_fh;
#
# Load Hash #2 with value from File #2
#
my %hash2;
open my $file2_fh, "<", FILE_2;
while ( my $value = <$file2_fh> ) {
chomp $value;
$hash2{$value} = 1;
}
close $file2_fh;
现在我想搜索 file2 的散列以检查 file1 的散列中是否有任何匹配项。这就是我卡住的地方
有了新的代码建议,代码现在看起来像这样
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw(say);
use autodie;
use constant {
FILE_1 => "masterlist.csv",
FILE_2 => "pastebin.csv",
};
#
# Load Hash #1 with value from File #1
#
my %hash1;
open my $file1_fh, "<", FILE_1;
while ( my $value = <$file1_fh> ) {
chomp $value;
$hash1{$value} = 1;
}
close $file1_fh;
my %hash2;
open my $file2_fh, "<", FILE_2;
while ( my $value = <$file2_fh> ) {
chomp $value;
if ( $hash1{$value} ) {
print "Match found $value\n";
$hash2{$value}++;
}
}
close $file2_fh;
print "Matches found:\n";
foreach my $key ( keys %hash2 ) {
print "$key found $hash2{$key} times\n";
}
我用 split() 更新了一个部分,它似乎可以工作,但必须进行更多测试以确认它是否适合我正在寻找的解决方案,或者我还有更多工作要做
#
# Load Hash #1 with value from File #1
#
my %hash1;
open my $file1_fh, "<", FILE_1;
while ( my $value = <$file1_fh> ) {
chomp $value;
$hash1{$value} = ( %hash1, (split(/,/, $_))[1,2] );
}
close $file1_fh;
【问题讨论】:
-
“匹配”是什么意思?您是指两个不同文件中独立但相同的行吗?您的意思是逐行比较两者,并且当且仅当该特定行在两个文件中包含相同时才“匹配”?我不确定我是否会将您发布的代码称为一个良好的起点 - 它可能会很好地工作,但会遇到通常的 perl 问题,即有点难以理解。
-
例如,我想将第一个 CSV 中的一个列和行中的单个值与第二个 CSV 中的任何列和行中的值进行匹配。我找到了匹配整行的其他解决方案,但我只想匹配单个单元格。第一个 CSV 较小,第二个 CSV 较大。
-
你需要做的是一个哈希。读取您的 CSV 文件,将要查找的字段存储在哈希中。然后遍历其他 CSV 文件并打印与哈希条目匹配的行。
-
好的,我想我明白了。非常感谢:)
-
我已经用更相关的代码更新了这个问题