for my $i (@array2) { for my $line (@array1) { my $key = "gi|$i|"; if (substr($line, 0, length $key) eq $key) { print $line; } } }