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

I have a problem replacing tekst in a HTML file, I drilled it down to a few lines of code as follows:
#!/usr/bin/perl $inputstring=qq{startstring <strong>(substring)</strong> endstring}; $t=qq{<strong>(substring)</strong>}; $r=qq{<b>(substring)</b>}; $inputstring=~s/$t/$r/; print $inputstring; #The final string should be: startstring<b>(substring)</b> endstring
But it isn't changed. When I remove the ( and ) the replacement works well, but I've no influence on the inputstring. So what I want to achive is that $t is handled as a "exact search string" and not as a to be interpreted regular expression. Help is very appreciated.

Replies are listed 'Best First'.
Re: replace not working as expected
by toolic (Bishop) on Feb 04, 2014 at 19:26 UTC
    quotemeta
    $inputstring=qq{startstring <strong>(substring)</strong> endstring}; $t=quotemeta qq{<strong>(substring)</strong>}; $r=qq{<b>(substring)</b>}; $inputstring=~s/$t/$r/; print $inputstring; __END__ startstring <b>(substring)</b> endstring
Re: replace not working as expected
by Anonymous Monk on Feb 04, 2014 at 19:32 UTC

    The (...) is being interpreted as a regular expression group. Try:

    $inputstring=~s/\Q$t/$r/;

    The \Q quotes any special characters following it so they lose their special meaning, so your $t will be matched literally.

    For details see quotemeta and perlre.