Search code examples
arraysperlcomparisonnumerical

Compare two texts numerically


I have these two files which I would like to compare its contents numerically.

Text1:

C_A C_A 0.0000 0.0000 0 0 50 47 100 390
C_A/I0/I0 INV 0.0200 0.2210 0 0 20 200 30 100
C_A/I0/I2 INV 1.0400 0.2210 0 0 530 200 250 261

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 30 100
C_A/I0/I2 INV 1.04 0.2210 0 0 530 200.00 250 261

Desired Output:

C_A/I0/I0 INV has mismatch property.

I have tried this so far but I got errors of use of uninitialized value. Please do advise me. Thanks for your help in advance.

Edited CODE:

use strict;
use warnings;
my %ref_data;

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

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

Solution

  • How about the smartmatch operator?

    while (<$fh>) {
        my ($occurname, $tempname, @data1) = split;
        my $data = $ref_data{$occurname};
        print "$occurname $tempname has mismatch property\n" unless @$data ~~ @data1;
    }
    

    If your Perl is not new enough (< 5.10.1), just use TLP's idea.

    EDIT: Added check for matching array lengths to stifle uninitialized value warnings when arrays are not the same size.

    if (@data1 != @$data || grep { $data1[$_] != $data->[$_] } 0 .. $#data1) {
        print "$occurname $tempname has mismatch property\n";
    }
    

    See grep

    Also section on arrays here for $#array