... # scan second file while (<>) { s/^>//; # remove leading '>' s/>$//; # remove trailing '>' print ">$_" if /^([\w\d]+)/ && $names{$1}; # add ^ }