Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to replace a long string with another and it seems to be working fine except for the "?" Here is what I am tring to do:
$temp1='http://test.com/web/main?'; $temp2='https://test.com/web1/test1'; $proc_string =~ s/$temp1/$temp2/g;
The replace works but the ? still stays there How can i get this replaced? I cannot exclusively replace the ? since there are other instances which I dont want to replace. Is there a way to get around it? Thanks

Replies are listed 'Best First'.
Re: String Replace
by moritz (Cardinal) on Jun 17, 2009 at 18:06 UTC
    The question mark has a special meaning in regexes, see perlreintro for details.

    To rob it off its special meaning, you can do

    $proc_string =~ s/\Q$temp1\E/$temp2/g;
Re: String Replace
by gwadej (Chaplain) on Jun 17, 2009 at 18:07 UTC

    Change the last line to:

    $proc_string =~ s/\Q$temp1\E/$temp2/g;

    s/// does a regular expression substitute, you need \Q to quote meta-characters so they are matched exactly.

    G. Wade
Re: String Replace
by kennethk (Abbot) on Jun 17, 2009 at 18:06 UTC
    Your issue is that '?' is a control character in regular expressions - it means match zero or one of the preceding character/pattern. You need to escape the '?' to get a literal '?', i.e.:

    $temp1='http://test.com/web/main\?'; $temp2='https://test.com/web1/test1'; $proc_string =~ s/$temp1/$temp2/g;

    See Regular Expressions, in particular the section on quantifiers, for details.

      Thank you. That worked.