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

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?

by Corion (Patriarch)
on Apr 02, 2018 at 09:10 UTC ( [id://1212143]=note: print w/replies, xml ) Need Help??


in reply to 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?

You will be much better suited by using a proper parser than hoping to do the parsing through a regular expression.

That said, it seems to me that you only want to replace variable names and not function names, so, barring any special/convenient notation for your variable names, I can only suggest that you build a proper regular expression out of your variable names:

my $variables = join "|", map { "\\b$_\\b" } reverse sort keys %cats; $variables = qr/$variables/; $texttosub =~ s|($variables)|$cats{ $1 }|g; # now there are no more variables, so we can evaluate the thing

You have two logic errors in your code:

While your string still contains variable names, it makes no sense to try to evaluate it.

Your code assumes that variable names should be matched independent of case, but your replacement can only replace the case that was stored in %cats. Your code will never replace blackCat with the value for blackcat.

  • Comment on 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?
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Is there any way to ignore certain words when substituing?
by haukex (Archbishop) on Apr 02, 2018 at 09:54 UTC
    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://1212143]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-19 12:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found