2文本文件比较和识别不匹配类型 [英] 2 text files comparison and identify type of mismatches

查看:148
本文介绍了2文本文件比较和识别不匹配类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码,比较两个示例文本文件,并报告任何数字不匹配。

I have this code which compare two sample text files and report any numeric mismatch.

Text1:

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

Text2:

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 

我想增强我的代码,@data的内容在($ x_os $ y_os $ reflection

I would like to enhance my code which the content of @data in below sequence ($x_os $y_os $reflection $rotation @nodes) are output along with error message to ease user for debugging.

希望的输出:

C_A/I0/I0 INV has mismatch property (y_os,nodes)
C_A/I0/I2 INV has mismatch property (x_os,reflection,rotation,nodes)


推荐答案

主要的区别在于,不是打印消息,而是一旦移动到下一个哈希元素,发现任何差异,它比较所有字段,并推送数组 @diffs 上的任何不同字段的名称。如果 @diffs 不为空,则在全部后进行比较。

The main difference is that, instead of printing a message and moving on to the next hash element as soon as any difference is found, it compares all of the fields and pushes the name of any differing field on array @diffs. The message is printed after all the comparisons have been made if @diffs isn't empty.

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)

这篇关于2文本文件比较和识别不匹配类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆