Use join
and the qr//
operator:
my $strings = join "|", getPileOfStrings();
my $re = qr/$strings/; #compile the pattern
if ($text =~ /$re(*.?)$re/)
If you wish for the same word to delimit the stuff in the middle say:
if ($text =~/($re)(.*?)\1/)
If the strings could contain characters that are considered special by Perl regexes, you may want to use map
and quotemeta
to prevent them from being used by the regex:
my $strings = join "|", map quotemeta, getPileOfStrings();
And, as Michael Carman points out, if getPileOfStrings()
is not designed to return the strings in the order you desire them to be matched in, you may want to use sort
to force the longest match to be first in the alternation (items earlier in the alternation will match first in Perl 5):
my $strings = join "|" map quotemeta,
sort { length $a <=> length $b } getPileOfStrings();
Remember to sort before running quotemeta since "a..."
(length 4) will be transformed into "a\\.\\.\\."
(length 6) which is longer than "aaaaaa"
(length 5).