my %b_lookup; for (<$file_b>) { my ($num, $data) = split(/ /, $_, 2); $b_lookup{$num} = "$num $data"; } for (<$file_a>) { my ($num, $data) = split(/ /, $_, 2); if (exists $b_lookup{$num}) { print $file_c $b_lookup{$num}."\n"; } else { print $file_c "$_\n"; } }