Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Replace multiple strings in a string

by choroba (Cardinal)
on May 07, 2014 at 15:10 UTC ( [id://1085327]=note: print w/replies, xml ) Need Help??


in reply to Replace multiple strings in a string

You are almost there.
  1. Remove the double quotes in the regular expression. They have no special meaning, so Perl tries to search for double quotes in the string - but there are none.
  2. ? has a special meaning in a regex. To be able to match it literally, you have to escape it. To escape the content of a variable, use the \Q.
  3. Your code as shown doesn't compile. There are some misnamed variables.

Here is the fixed version:

#!/usr/bin/perl use warnings; use strict; my $a = "aRep"; my $b = "bRep"; my $c = "cRep"; my @Search = ("?a?", "?b?", "?c?"); my @Replace = ($a, $b, $c); my $string = '?a? ?b? ?c?'; print "old string: $string\n"; for (my $i = 0; $i < $#Search + 1; $i++) { $string =~ s/\Q$Search[$i]/$Replace[$i]/g; } print "new string: $string\n"
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Replace multiple strings in a string
by Axlex (Initiate) on May 07, 2014 at 15:34 UTC

    Thank You Choroba for your fast Reply.

    It didn't compile because i tried several ways and copied one, changing the variables, but obviously not all.

    I already tried escaping, but in the wrong way it seems. ( "\?" and single quoted '?')

    Big Thx :D

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-23 17:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found