我有这个代码比较两个示例文本文件并报告任何数字不匹配。
文本1:
C_A C_A 0.0000 0.0000 0 0 50 47 100 390
C_A/I0/I2 INV 1.0400 0.2210 0 0 530 200 250 261
C_A/I0/I0 INV 0.0200 0.2210 0 0 20 200 30 100
文本2:
C_A C_A 0.0000 0 0 0 50 47 100 390
C_A/I0/I0 INV 0.0200 0.2213 0 0 20 200 40 100
C_A/I0/I2 INV 1.00 0.2210 1 1 535 200.00 250 261
代码:
use strict;
use warnings;
my %ref_data;
open my $fh, '<', 'Text1' or die "Could not open to read: $!";
while (<$fh>) {
chomp;
my ( $occurname, $tempname, @data1) = split;
$ref_data{$occurname} = \@data1;
}
open $fh, '<', 'Text2' or die "Could not open to read: $!";
while (<$fh>) {
my ( $occurname, $tempname, @data2 ) = split;
my $data1 = $ref_data{$occurname};
for ( 0 .. $#data2 ) {
if ( $data1->[$_] != $data2[$_] ) {
print "$occurname $tempname has mismatch property\n";
last;
}
}
}
输出:
C_A/I0/I0 INV has mismatch property
C_A/I0/I2 INV has mismatch property
我想增强我的代码,其中输出以下序列($x_os $y_os $reflection $rotation @nodes)
中@data的内容以及错误消息,以方便用户进行调试。
期望的输出:
C_A/I0/I0 INV has mismatch property (y_os,nodes)
C_A/I0/I2 INV has mismatch property (x_os,reflection,rotation,nodes)
答案 0 :(得分:1)
由于我假设的含义给出了你需要的输出,我发布了这个解决方案。
主要区别在于,只要找到任何差异,就会比较所有字段,而不是打印邮件并转移到下一个哈希元素并在阵列@diffs
上推送任何不同字段的名称。如果@diffs
不为空,则在所有进行比较后打印消息。
use strict;
use warnings;
my %ref_data;
open my $fh, '<', 'Text1' or die "Could not open to read: $!";
while (<$fh>) {
chomp;
my ( $occurname, $tempname, @data1) = split;
$ref_data{$occurname} = \@data1;
}
my @fields = qw/ x_os y_os reflection rotation /;
open $fh, '<', 'Text2' or die "Could not open to read: $!";
while (<$fh>) {
chomp;
my ( $occurname, $tempname, @data2 ) = split;
my $data1 = $ref_data{$occurname};
my @diffs;
for my $i ( 0 .. $#data2 ) {
if ( $data1->[$i] != $data2[$i] ) {
if ($i < 4) {
push @diffs, $fields[$i];
}
else {
push @diffs, 'nodes';
last;
}
}
}
printf "%s %s has mismatch property (%s)\n", $occurname, $tempname, join(', ', @diffs) if @diffs;
}
<强>输出强>
C_A/I0/I0 INV has mismatch property (y_os, nodes)
C_A/I0/I2 INV has mismatch property (x_os, reflection, rotation, nodes)