join "|", map { "\\b$_\\b" } reverse sort keys %cats;
I'd suggest putting a quotemeta in there, just to play it safe. Although I agree that using a proper parser is better! skooma: See also Building Regex Alternations Dynamically.
use warnings;
use strict;
use Test::More;
my %cats = (blackcat=>5, whitecat=>10,orangecat=>20);
my ($regex) = map { qr/\b($_)\b/ } join '|', map {quotemeta}
sort { length $b <=> length $a or $a cmp $b } keys %cats;
diag explain $regex;
sub do_replace {
my $input = shift;
$input =~ s/$regex/$cats{$1}/g;
return $input;
}
is do_replace("log10(blackcat)"), "log10(5)";
is do_replace("log10(blackcat)*whitecat*(log10(orangecat))"),
"log10(5)*10*(log10(20))";
done_testing;
__END__
# qr/\b(orangecat|blackcat|whitecat)\b/
ok 1
ok 2
1..2
-
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.
|