I would suggest this. You can simplify the hash if you are happy to use the substitution pattern as the top level key. The guts of the approach is to build an alternation RE dynamically and use the match value to lookup the replacement value in a hash. This is typically the fastest approach as you leverage the C code in the regex and hashing engines effectively. Note the sort by longest first so we match on the full 'foobar' not 'foo' or 'bar'.
my $res = {
re1 => { foo => 'foo_new' },
re2 => { bar => 'bar_new' },
re3 => { qux => 'bar_new' },
re4 => { foobar => 'foobar_new' }
};
my @required = qw ( re1 re2 re4 );
my %active_re = map{ each %{$res->{$_}} } @required;
my $match = join '|', sort{ length $b <=> length $a } keys %active_re;
$match = qr/($match)/;
$str = 'foo bar baz foobar';
$str =~ s/$match/$active_re{$1}/g;
print $str;
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|