J
jason
Hello.
I'm trying to merge two files by a common key field.
file1.csv format:
B1,B2,B3,B4,BK
file2.csv format:
A1,AK,A3,A4
Need to produce:
file3.csv:
A3,A4,B2,B3,B4,BK
Where file1.csv is using BK=AK to lookup A3 and A4. Every record in
file1.csv must end up in file3.csv
Here's the code I have :
#!/usr/bin/perl
open FILEC, '>filec.csv' or die "could not open 'matched.csv' $!";
my %a;
open FILEA, 'filea.csv' "could not open 'filea' $!";
while ( <FILEA> ) {
$_ =~ s/"([^"]*)"/&comma_fixer($1)/ge;
my @f = split /,/;
my $key = $f[4];
#print $key;
if ( exists $a{$key} )
{
print "Duplicate key found in ", $key ," ",$_," ", @f,"\n";
}
else
{
$a{$key} = \@f;
}
}
open FILEB, 'fileb.csv' or die "could not open 'fileb' $!";
while ( <FILEB> ) {
my @b = split /,/;
my $key = $b[1];
#BELOW IS THE SUSPECT LINE
if ( exists $a{$key} ) {
my $m = join ',', $key,
$a{$key}[2],
$b[1],
$b[2],
$b[3];
print FILEC "$m\n";
print "entry found\n";
}
else
{
# print "key not found ",$key,"\n";
}
}
close FILEA;
close FILEB;
close FILEC;
sub comma_fixer {
$string = @_[0];
$string =~ s/,/ /g; ## replace , with blank,
return $string;
=====
Every single line spits out "key not found".
What am I doing wrong and is there a better way to approach this?
I'm trying to merge two files by a common key field.
file1.csv format:
B1,B2,B3,B4,BK
file2.csv format:
A1,AK,A3,A4
Need to produce:
file3.csv:
A3,A4,B2,B3,B4,BK
Where file1.csv is using BK=AK to lookup A3 and A4. Every record in
file1.csv must end up in file3.csv
Here's the code I have :
#!/usr/bin/perl
open FILEC, '>filec.csv' or die "could not open 'matched.csv' $!";
my %a;
open FILEA, 'filea.csv' "could not open 'filea' $!";
while ( <FILEA> ) {
$_ =~ s/"([^"]*)"/&comma_fixer($1)/ge;
my @f = split /,/;
my $key = $f[4];
#print $key;
if ( exists $a{$key} )
{
print "Duplicate key found in ", $key ," ",$_," ", @f,"\n";
}
else
{
$a{$key} = \@f;
}
}
open FILEB, 'fileb.csv' or die "could not open 'fileb' $!";
while ( <FILEB> ) {
my @b = split /,/;
my $key = $b[1];
#BELOW IS THE SUSPECT LINE
if ( exists $a{$key} ) {
my $m = join ',', $key,
$a{$key}[2],
$b[1],
$b[2],
$b[3];
print FILEC "$m\n";
print "entry found\n";
}
else
{
# print "key not found ",$key,"\n";
}
}
close FILEA;
close FILEB;
close FILEC;
sub comma_fixer {
$string = @_[0];
$string =~ s/,/ /g; ## replace , with blank,
return $string;
=====
Every single line spits out "key not found".
What am I doing wrong and is there a better way to approach this?