我是 Perl 的菜鸟,而且我很难完成这件事。我有两个单列 CSV 文件,我正在尝试将差异打印到第三个文件。
File1:
123
124
125
126
File2:
123
124
127
Expected Output:
125
126
127
这是我到目前为止所得到的,但不起作用:
#!/usr/bin/perl
use strict;
use warnings;
my $sheet_1;
my $sheet_2;
my $count1 = 0;
my $count2 = 0;
my $file1 = 'file1.csv';
my $file2 = 'file2.csv';
my $file_out = 'output.csv';
open (FILE1, "<$file1") or die "Couldn't open input file: $!";
open (FILE2, "<$file2") or die "Couldn't open input file: $!";
while( <FILE1> ) {
chomp;
$count1++;
#skip header;
next unless $count1;
my $row_1;
@$row_1 = split( /,/, $_ );
push @$sheet_1, $row_1;
}
@$sheet_1 = sort { $a->[0] <=> $b->[0] } @$sheet_1;
while( <FILE2> ) {
chomp;
$count2++;
#skip header;
next unless $count2;
my $row_2;
@$row_2 = split( /,/, $_ );
push @$sheet_2, $row_2;
}
@$sheet_2 = sort { $a->[0] <=> $b->[0] } @$sheet_2;
OUTER: {
foreach my $row_1 ( @$sheet_1 ) {
foreach my $row_2 ( @$sheet_2 ) {
if (@$row_1[0] eq @$row_2[0]){
last OUTER
}
else{
print "@$row_1[0]\n";
}
}
}
}
close FILE1;
close FILE2;
您可以使用文本::差异 http://search.cpan.org/~adamk/Text-Diff-1.37/lib/Text/Diff.pmPerl 模块可以做到这一点。否则,请参见下文:
这是一种进行比较的算法。
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";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)