Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re^2: string replacement

by haukex (Monsignor)
on Sep 12, 2017 at 18:57 UTC ( #1199222=note: print w/replies, xml ) Need Help??


in reply to Re: string replacement
in thread string replacement

my $pattern = join "|", map quotemeta, keys %replacements;

I think it would be good to also sort on length, as I discussed in Building Regex Alternations Dynamically. Although huck does make a good point that preserving the original ordering may be important too. Update after your reply: Good point about replacements within the replacements, whether the OP wants that or not and which method is more appropriate will depend on their requirements.

Replies are listed 'Best First'.
Re^3: string replacement
by Eily (Parson) on Sep 12, 2017 at 20:44 UTC

    You're right about putting the longest strings first, if one searched string can be the start of another. That would be my $pattern = join "|", map quotemeta, sort {length $b <=> length $a} keys %replacements;.

    With a single substitution operator you don't have to look for the presence of a searched string inside a replacement, because perl will only keep searching after the replaced item, so you can't replace part of a replacement.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1199222]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-10-20 09:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (260 votes). Check out past polls.

    Notices?