For regexes with variables in them, it rebuilds the machine every time it uses the regex.
No it doesn't. If the contents of the interpolated variable doesn't change, the pattern isn't recompiled.
$ perl -Mre=debug -e'/$_/ for 1..2' 2>&1 | grep Compiling Compiling REx "1" Compiling REx "2" $ perl -Mre=debug -e'$x="foo"; /$x/ for 1..2' 2>&1 | grep Compiling Compiling REx "foo"
You certainly also know that this program can be optimized with the o-flag:
The following would be fine since $pat is the same for every pass of the loop:
my $pat = 'id\\d+'; while (<>) { print if /$pat/; }
You could also use qr// instead of /o.
my $pat = qr/id\d+/; while (<>) { print if /$pat/; }
It's even simpler to write patterns using qr// than as strings. (Note the extra slash above.)
Obviously the /../o trick won't work here,
Yet another reason to use qr//.
my @pats = ( qr/fo*/, qr/ba./, qr/w+3/ ); while (<>) { for my $pat (@pats) { print if /$pat/; } }
But the problem is: I can't use the trick shown above (join all patterns into one string with '|')
No need for it
my @handlers = ( { pattern => qr/.../, callback => sub { ... } }, { pattern => qr/.../, callback => sub { ... } }, { pattern => qr/.../, callback => sub { ... } }, ); for my $line (@lines) { for my $handler (@handlers) { if (my @params = ($line =~ $handler->{$pattern})) { my $func = $handler->{callback}; $func->(@params) if $func; } } }
By using an array instead of hash, you even get the bonus of being able to place the most commonly matched handlers first.
In reply to Re: Optimize a pluggable regex matching mechanism
by ikegami
in thread Optimize a pluggable regex matching mechanism
by dredd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |