my %data; my @fieldlist1 = split(/,/,); while() { my ($key,@rest) = split(/,/,$_); push @{$data{$key}}, @rest; } my @fieldlist2 = split(/,/,); shift @fieldlist2; # throw away the first field b/c it is the id while( ) { my ($key,@rest) = split(/,/,$_); #if you want to JOIN these two files, # and skip records where there is not next unless $data{$key}; push @{$data{$key}},@rest; } my @fields = (@fieldlist1,@fieldlist2); # assuming the PK is numeric print join(',',@fields),"\n"; foreach my $id ( sort { $a <=> $b } keys %data ) { # if you wanted to skip the lines where there # was data in ONE but not in TWO # you need a count of the number of fields you expect # which is handily avaialable in @fields -1 (ignoring id) next unless scalar @{$data{$id}} == (scalar @fields -1); print join(',', $id, @{$data{$id}}),"\n"; }