Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^2: Is there any way to ignore certain words when substituing?

by haukex (Archbishop)
on Apr 02, 2018 at 09:54 UTC ( [id://1212145]=note: print w/replies, xml ) Need Help??


in reply to Re: Is there any way to ignore certain words and keep it as it is when substituing hash values to a matched pattern in a string?
in thread Is there any way to ignore certain words and keep it as it is when substituing hash values to a matched pattern in a string?

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-04-19 05:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found