In modern Perls -- I'm not sure which versions qualify here, maybe 5.6+ -- Perl will check whether the contents of the variable has changed. If the content of the variable has not changed, the regexp is not recompiled.
For example, compare
my @words = (
'foo',
'bar',
);
foreach (@array) {
foreach my $word (@words) {
if (/\Q$word/) { # BAD!! $word always changes.
print;
last;
}
}
}
to
my @words = (
'foo',
'bar',
);
foreach my $word (@words) {
foreach (@array) {
if (/\Q$word/) { # GOOD!! regexp only recompiled when needed.
print;
last;
}
}
}
It's not always practical to change the order of the loops. For example, when one of them reads from a file. In that case, the solution is to precompile the regexps. For example, compare
my @words = (
'foo',
'bar',
);
while (<FILE>) {
foreach my $word (@words) {
if (/\Q$word/) { # BAD!! $word always changes.
print;
last;
}
}
}
to
my @words = (
'foo',
'bar',
);
# Precompile the regexps.
my @regexps = map { qr/\Q$_/ } @words;
while (<FILE>) {
foreach my $regexp (@regexps) {
if (/$regexps/) { # GOOD!! $regexp is a compiled regexp.
#if ($_ =~ $regexp) { # GOOD!! Alternate syntax.
print;
last;
}
}
}
If you're trying to match constant strings rather than regexps, then I recommend Regexp::List:
use Regexp::List ();
my @words = (
'foo',
'bar',
);
my $regexp = Regexp::List->new()->list2re(@words);
while (<FILE>) {
print if /$regexp/;
#print if $_ =~ $regexp; # Alternate syntax.
}
By the way,
for ($loop_index = 0; $loop_index < $#patterns; $loop_index++) {
is much less readable and no more efficient than
for my $loop_index (0..$#patterns) {
You could also have used
foreach (@patterns) {
Finally, in your case, I'd use
my @patterns = qw(
create
drop
delete
update
insert
);
my $regexp;
$regexp = Regexp::List->new(modifiers => 'i')->list2re(@patterns);
$regexp = qr/\b(?:$regexp)\b/;
...
while ($data = $sth->fetchrow_arrayref()) {
# index is faster than regexps on constant strings.
next if index(lc($data->[10]), 'tempdb') >= 0;
if ($data->[13] =~ $regexp) {
print "$data->[3] $data->[9] $data->[10] $data->[13]\n";
last;
}
}
Update: Bug Fix: Changed $word to $_ in map's code block.
|