2 text files comparison and identify type of mismatches

痴心易碎 提交于 2019-12-12 03:09:05

问题


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

code:

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;
    }
  }
}

Output:

C_A/I0/I0 INV has mismatch property 
C_A/I0/I2 INV has mismatch property 

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.

Desired Output:

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

回答1:


Since the meaning that I assumed gives the output that you require, I am posting this solution.

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;
}

output

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


来源:https://stackoverflow.com/questions/20673462/2-text-files-comparison-and-identify-type-of-mismatches

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!