Also, please note that there is a performance penalty if you have perl evaluate something like
/$variable/
every time. If you don't give perl a hint that $variable never changes, it will recompile the regex every time. To avoid that, use
/$variable/o
to tell "this is a variable, but it never changes, so you need to compile it only once". Here's a benchmark program to show the difference:
use Benchmark; my $qr_regex = qr/ab{1,}c{1,}/; my $str_regex = "ab{1,}c{1,}"; my $string = "asdabdabc"; timethese(10000000, { 'string' => sub { $string =~ /$str_regex/ }, 'string/o' => sub { $string =~ /$str_regex/o }, 'qr' => sub { $string =~ /$qr_regex/ }, });
And here are the results:
Benchmark: timing 10000000 iterations of qr, string, string/o... qr: 11 wallclock secs (10.60 usr + 0.00 sys = 10.60 CPU) @ 943396.23/s (n=10000000) string: 11 wallclock secs (11.80 usr + 0.00 sys = 11.80 CPU) @ 847457.63/s (n=10000000) string/o: 7 wallclock secs ( 9.40 usr + 0.02 sys = 9.42 CP U) @ 1061571.13/s (n=10000000)
-- saintmike

In reply to Re: Storing Regex Patterns in Scalars by saintmike
in thread Storing Regex Patterns in Scalars by iana

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.