Question

I would like to compare 2 files numerically for each instance name and output any mismatch property.

Ref.txt:

CELLA CELLA 0.0000 0.0000 0 0 50 47 100 390 798 1000 3349 2938
CELLA/I0/I0 INV 0.0200 0.2210 0 0 20 200 30 100 430 770 230 940
CELLA/I0/I2 INV 1.0400 0.2210 0 0 530 200 250 261 1230 670 1240 390

New.txt:

CELLA CELLA 0.0000 0.0000 0 0 50 47 100 390 798 1000 3349 2938
CELLA/I0/I2 INV 1.0400 0.2218 0 0 530 200 250 261 1230 670 1240 390
CELLA/I0/I0 INV 0.0200 0.2210 0 0 20 200 30 100 430 770 230 940

Expected Output(CELLA/I0/I2 which 0.2218 is not equal to 0.2210):

-ERROR: CELLA/I0/I2 has mismatch property.

My code so far,how should I fix my code?

use strict;

my %hash;

sub read_hash {
  my $fname = shift;
  open(my $fh, "<", $fname) or die "$!";
  while (<$fh>) {
    chomp;
    my ($occurname, $tempname, $x, $y, $reflection, $rotation, $xy1, $xy2, $xy3,$xy4,  
 $xy5, $xy6, $xy7, $xy8, $xy9, $xy10, $xy11, $xy12, $xy13) = split /\s+/, $fh;
  }
}

my %hash1 = read_hash("Ref.txt");
my %hash2 = read_hash("New.txt");

if ($hash1{$x}{$y}{$reflection}{$rotation}{$xy1}{$xy2}{$xy3}{$xy4}{$xy5}{$xy6}{$xy7}{$xy8}{$xy9}{$xy10}{$xy11}{$xy12}{$xy13}
    != $hash2{$x}{$y}{$reflection}{$rotation}{$xy1}{$xy2}{$xy3}{$xy4}{$xy5}{$xy6}{$xy7}{$xy8}{$xy9}{$xy10}{$xy11}{$xy12}{$xy13}) {
  print "$occurname has mismatch property";
}
else {
  print "Match\n";
}
Was it helpful?

Solution

I'm sorry, but I'm not inclined to work through your code explaining all the problems. The biggest error is that nested hashes don't work like that. Here is a complete revision that does what you ask.

use strict;
use warnings;

my %ref_data;

open my $fh, '<', 'Ref.txt' or die $!;
while (<$fh>) {
  chomp;
  my ($occurname, $tempname, @data) = split;
  $ref_data{$occurname} = \@data;
}

open $fh, '<', 'New.txt' or die $!;
while (<$fh>) {
  my ($occurname, $tempname, @data) = split;
  my $ref_data = $ref_data{$occurname};
  unless ($ref_data and grep($data[$_] != $ref_data->[$_], 0..$#data) == 0) {
    print "$occurname has mismatch property\n";
  }
}

output

CELLA/I0/I2 has mismatch property

OTHER TIPS

You're not returning anything from your sub read_hash.

Add something like $hash{$x}{$y}.... = $occurname; in the while loop and return %hash at the end of the sub.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top