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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.