open my $fh1, '<', 'file1.txt' or die $!; open my $fh2, '<', 'file2.txt' or die $!; open my $outfh, '>', "outputfile.txt" or die $!; my %lines; while (<$fh2>) { chomp; my ($key, $n) = /(.*)\s(\d+)$/; $lines{$key} = $n; } while (<$fh1>) { chomp; if (exists $lines{$_}) { print $outfh "$_ $lines{$_}\n"; } else { print $outfh "$_ 0\n"; } }