#strip the id, repeating for each @sample array as necessary foreach (@sample){ s/^ID\d+\s+(.*)/$1/; } #set an array to catch the mathcing lines my @matches #now compare each array element in @sample1 to each array element in @sample2 my ($line1, $line2); foreach $line1 (@sample1){ foreach $line2 (@sample2){ push(@matches, $line2) if ($line2 eq $line1); } } print join("\n", @matches);