#!/usr/bin/perl open FILE1,"./a.txt" or die "Cannot open a.txt"; open FILE2,"./b.txt" or die "Cannot open b.txt"; open FILE3,">./r.txt" or die "Cannot create r.txt"; while () { chomp; /[^\ ]*$/; $common = $&; $begin = $`; chop $begin; $array{$common} = $begin; } close FILE1; while () { chomp; /^[^\ ]*\ /; $common = $&; chop $common; $end = $'; print FILE3 "$array{$common} $common\zz$end" if exists $array{$common}; } close FILE2; close FILE3;