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


In reply to Re: Replace multiple strings in a string by InfiniteSilence
in thread Replace multiple strings in a string by Axlex

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.