Maybe one way:
c:\@Work\Perl\monks>perl -wMstrict -le
"my @GI = (
'gi|Q384722390|emb|WP_938420210.1|Gene name',
'gi|342546780|emb|WP_934203412.1|Gene name',
'gi|342546780|emb|WP_93420341211|Gene name',
'gi|987654321|emb|WP_555555555.1|Jean name',
);
;;
my @Accession = qw(WP_938420210.1 WP_934203412.1);
my ($rx_acc) =
map qr{ $_ }xms,
join q{|},
map quotemeta,
@Accession
;
;;
GENE:
for my $gi (@GI) {
next GENE unless my ($acc) = $gi =~ m{ \b ($rx_acc) \b }xms;
print qq{'$acc' in '$gi'};
}
"
'WP_938420210.1' in 'gi|Q384722390|emb|WP_938420210.1|Gene name'
'WP_934203412.1' in 'gi|342546780|emb|WP_934203412.1|Gene name'
Updates:
-
Noticed accession numbers have . (dot) metacharacter in them: added map quotemeta, step to building accession number regex to make dot an ordinary literal character.
-
Added some negative matches to @GI test cases.
-
The match expression m{ (?<= [|]) ($rx_acc) (?= [|]) }xms
may be preferable | is almost certainly better because | (pipe) characters are exactly what must match before and after an accession number (\b just requires a word boundary). (Tested; same output.)
-
Usually, the regex engine begins searching a string from the beginning of the string. If you know that a match cannot possibly start before a certain character offset in the string, this information can be used to allow the RE to jump ahead in its search, skipping over characters in which there can be no match and potentially speeding a match. Further, if it is known that interpolated regex components (like $n and $rx_acc below) will not change during script execution, the /o regex modifier (see m/PATTERN/ in the Regexp Quote-Like Operators section of perlop) can be used to prevent regex re-compilation on each pass through the loop, again potentially speeding matches. So a loop like:
my $n = 12;
GENE:
for my $gi (@GI) {
next GENE unless
my ($acc) = $gi =~ m{ \A .{$n,}? (?<= [|]) ($rx_acc) (?= [|]) }xms
+o;
print qq{'$acc' in '$gi'};
}
(tested; same output) may be significantly faster; this can only be determined for certain by some kind of Benchmark-ing.
-
Actually, in answer to the question posed by hippo in the reply below, I think a hash-based approach would probably be more appropriate (insofar as I understand the problem): simpler, more maintainable, likely much faster than a regex approach.
Give a man a fish: <%-(-(-(-<