Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Replace multiple strings in a string

by InfiniteSilence (Curate)
on May 07, 2014 at 15:51 UTC ( [id://1085333]=note: print w/replies, xml ) Need Help??


in reply to Replace multiple strings in a string

Although you already have your answer for the given code I should point out the inefficiency of repeatedly running regexes in that fashion:

use strict; use warnings; use Benchmark qw|timethese cmpthese|; my $a = "aRep"; my $b = "bRep"; my $c = "cRep"; my @Search = ("?a?", "?b?", "?c?"); my @Search1 = (qr|\?a\?|,qr|\?b\?|,qr|\?c\?|); my @Replace = ($a,$b,$c); my $i=0; my $string = '?a? ?b? ?c?'; print "old string: $string\n"; print qq~ one --- \n~; &std_replace; print qq|String is now $string\n|; print qq~ two --- \n~; &improved_replace; print qq|String is now $string\n|; print qq~ Comparison --- \n~; timethese (100_000, {'STD_REPLACE'=>\&std_replace, 'IMP_REPLACE'=>\&improved_replace}); sub std_replace { $string = '?a? ?b? ?c?'; for (my $i = 0; $i < $#Search + 1; $i++) { $string =~ s/\Q$Search[$i]/$Replace[$i]/g; } } sub improved_replace { $string = '?a? ?b? ?c?'; for (;$i<$#Search1+1;$i++) { $string =~ s/$Search1[$i]/"$Replace[$i]"/g; } } 1;
Produces,
old string: ?a? ?b? ?c? one --- String is now aRep bRep cRep two --- String is now "aRep" "bRep" "cRep" Comparison --- Benchmark: timing 100000 iterations of IMP_REPLACE, STD_REPLACE... IMP_REPLACE: 0 wallclock secs ( 0.10 usr + 0.00 sys = 0.10 CPU) @ 1 +000000.00/s (n=100000) (warning: too few iterations for a reliable count) STD_REPLACE: 6 wallclock secs ( 4.99 usr + 0.00 sys = 4.99 CPU) @ 2 +0040.08/s (n=100000)

But I suppose this only matters when the number of comparisons increases significantly.

Celebrate Intellectual Diversity

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (1)
As of 2024-04-25 00:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found