A few comments... Using string eval to compile an anonymous subroutine created at runtime is not necessarily nonsense. The eval is only executed once; the subroutine can be called many times. Here's a better example, using tr///, for which the search and replace lists have to be defined when the tr/// is compiled:
#!/usr/local/bin/perl sub make_tr { my($search, $replace, $flags) = @_; $flags = '' if not defined $flags; my $code = "sub { \$_[0] =~ tr/$search/$replace/$flags }"; my $sub = eval $code; die "$code\n$@" if $@; return $sub; } my $rotate = shift; $rotate = 13 unless defined $rotate and $rotate =~ /^\d+\z/; $rotate %= 26; $replace = chr(ord('A')+$rotate) . '-ZA-' . chr(ord('A')+$rotate-1); $replace .= lc($replace); my $rotate_sub = make_tr('A-Za-z', $replace, ''); while (<>) { $rotate_sub->($_); print; }
Instead of calling eval every time through the loop, eval is called once ahead of time and an anonymous subroutine is called inside the loop. (Another way to avoid repeated calls to eval would be to wrap the whole loop in an eval.)

You're absolutely right that the original poster's code is equivalent to sub { return 1 if m!foo!o }. Not a very useful application of eval. :) If foo were actually a variable, it would make a tiny bit more sense: eval "sub { return 1 if m!$foo!o }. But as japhy already noted, qr//, rather than eval, should be used for that.

A final aside, in $match = qq@ return (\$1,\$2) if m!(foo)(bar)!; @;, those backslashes are actually escaping the dollars signs from interpolation, rather than creating references. It's a double-quoted string.


In reply to Re: Re: eval routines for faster regexp: how-to... by chipmunk
in thread eval routines for faster regexp: how-to... by gleeco

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.