Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Precompiling substitution regex

by wind (Priest)
on Jun 17, 2011 at 22:49 UTC ( #910267=note: print w/ replies, xml ) Need Help??

in reply to Precompiling substitution regex

Use eval to cache the substitution in an anonymous sub:

use strict; use warnings; # Cached Regex's: LHS, RHS, Modifiers my @re_rules = ( ['(?:this|or|that)', 'bob', 'gsi'], ['(?:One|Two|Three)', 'Four', 'gs'], ); my @re_subs = map { my $sub = eval "sub { s/$_->[0]/$_->[1]/$_->[2] for (\@_)}"; die $@ if $@; $sub; } @re_rules; my @strings = ('this one or that other', 'One two Three'); for my $string (@strings) { $_->($string) for (@re_subs); print "$string\n"; }
Or just declare the anonymous subs yourself if you don't need the special markup:
use strict; use warnings; my @re_subs = ( sub { s/(?:this|or|that)/bob/gsi for (@_) }, sub { s/(?:One|Two|Three)/Four/gs for (@_) }, ); my @strings = ('this one or that other', 'One two Three'); for my $string (@strings) { $_->($string) for (@re_subs); print "$string\n"; }

Comment on Re: Precompiling substitution regex
Select or Download Code
Re^2: Precompiling substitution regex
by FreakyGreenLeaky (Sexton) on Jun 18, 2011 at 09:46 UTC
    Thanks. Does the second sample pre-compile the regexes?

      I believe that we're mixing terminology here, as "pre-compile" isn't exactly what you're wanting to ask. Yes, the code is only compiled once and after that point it will not need to be recompiled.

      I've used this type of mechanism to program configurable filters. Letting a user edit a config file where they specify anonymous subs like that which are later eval'd and used in my larger package.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://910267]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-10-21 02:12 GMT
Find Nodes?
    Voting Booth?

    For retirement, I am banking on:

    Results (95 votes), past polls