Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Efficient way to replace a set of values with another set of values

by tobyink (Canon)
on Nov 23, 2012 at 10:12 UTC ( [id://1005243]=note: print w/replies, xml ) Need Help??


in reply to Efficient way to replace a set of values with another set of values

Maybe a little something like this?

my $string = q{ 1. This is just a sample. 2. This is to check 3. How a set of values 4. can be replaced by another 5. set of values and that too 6. in the most efficient way. }; my %replacements = ( '1.' => 'a.', '2.' => 'b.', '3.' => 'c.', '4.' => 'd.', '5.' => 'e.', '6.' => 'f.', ); my $regexp = join '|', map quotemeta, keys %replacements; $string =~ s/($regexp)/$replacements{$1}/g; print $string;
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
  • Comment on Re: Efficient way to replace a set of values with another set of values
  • Download Code

Replies are listed 'Best First'.
Re^2: Efficient way to replace a set of values with another set of values
by ColonelPanic (Friar) on Nov 23, 2012 at 10:19 UTC
    Nice solution. In this case, all cases are at the beginning of the line. It might be a good idea to add an anchor in order reduce the likelihood of false positive matches:
    $string =~ s/^($regexp)/$replacements{$1}/gm;
    (The m switch had to added so that ^ would match on each line).


    When's the last time you used duct tape on a duct? --Larry Wall

      Indeed. I was in two minds about whether to include it or not. The substitutions in the examples were consistently at the start of lines, but the OP never explicitly specified that that would always be the case, so I decided to go for the more general "anywhere in the string" match.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
        Yeah, I agree that it depends on exact requirements. I thought it was worth mentioning though, because it's such a simple pattern that I would be worried about it popping up elsewhere in the data.


        When's the last time you used duct tape on a duct? --Larry Wall

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-20 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found