Friday, December 19, 2014

Perl: membandingkan dua file

Perl compare two files, calculate the closest value between two fields and output field values from another file
more file1.txt
798355.5    3188172.8  
800105.5    3188210.3  
798267.9    3188222.8  

more file2.txt
798355.4    3188172.7   2000.00
800105.4    3188210.2   3000.00
797867.9    3188222.7   1684.05
798267.9    3188222.7   8000.00
798667.9    3188222.7   1700.46

output:
798355.5    3188172.8    2000.00
800105.5    3188210.3    3000.00
798267.9    3188222.8    8000.00


#!/usr/bin/perl
my $file1 = 'file1.txt';
my @data1;
open( FILE1, $file1 ) or die "Can't open file '$file1': $!";
while( <FILE1> ) {
chomp;
my @row1 = split;
push @data1, \@row1;
}
close( FILE1 );

my $file2 = 'file2.txt';
my @data2;
open( FILE2, $file2 ) or die "Can't open file '$file2': $!";
while( <FILE2> ) {
chomp;
my @row2 = split;
push @data2, \@row2;
}
close( FILE2 );

for my $i (0..$#data1)   #no row slave
{
for my $j (0..$#data2)   #no row master
{
$dx[$i]=($data1[$i][0]-$data2[$j][0])*($data1[$i][0]-$data2[$j][0]);  #key1 match
$dy[$i]=($data1[$i][1]-$data2[$j][1])*($data1[$i][1]-$data2[$j][1]);  #key2 match
$dz[$i]=sqrt($dx[$i]+$dy[$i]); #distance
push @dza,$dz[$i];
}
push @dzt,$data2[minindex(\@dza)][2];  #find index of closest distance
@dza=();
}

for my $i (0..$#data1)
{
   print "$data1[$i][0]","\t";
   print "$data1[$i][1]","\t";
   print "$dzt[$i]","\n";
}

sub minindex {
  my( $aref, $idx_min ) = ( shift, 0 );
  $aref->[$idx_min] < $aref->[$_] or $idx_min = $_ for 1 .. $#{$aref};
  return $idx_min;
}

No comments: