Re: compare 2 data files and extract fields for matched lines





#!/usr/bin/perl
use warnings;
use strict;

my $File_In1 = 'dat1.txt';
my $File_In2 = 'dat2.txt';

open FILE_IN2, '<', $File_In2 or die "cannot open '$File_In2' $!";

my %population;
while ( <FILE_IN2> ) {
my ( $county, $state, $pop ) = /\A([^|]+)\|([^|]+)\|(\d+)\Z/;
$population{ "$state|$county" } = $pop;
}

close FILE_IN2;

open FILE_IN1, '<', $File_In1 or die "cannot open '$File_In1' $!";

while ( my $line = <FILE_IN1> ) {
chomp $line;
my ( $key ) = $line =~ /\|([^|]+\|[^|]+)\z/;
print "$line|", $population{ $key } || '0000', "\n";
}

close FILE_IN1;

__END__

John

Dear all,

Thanks for showing me how to do this. And an added thanks to John for
teaching good programming techniques in perl.

I was able to literally use the above and it worked like a charm.

Shree


.



Relevant Pages