2

This is my code:

$html = 'Is this a question? Maybe.';
$old = 'question?';
$new = 'reply?';

$html =~ s/$old/$new/g;
print $html; exit;

Output is:

Is this a reply?? Maybe.

Desired output:

Is this a reply? Maybe.

What am I doing wrong?

3 Answers 3

9

Use quotemeta to escape the ?:

$html = 'Is this a question? Maybe.';
$old = quotemeta 'question?';
$new = 'reply?';

$html =~ s/$old/$new/g;
print $html; exit;
0
6

In regexes, the question mark is an operator meaning one or none. Therefore, we have to escape it:

s/question\?/reply?/g

Note that it isn't special in strings. Because interpolating random strings into regexes can have such unwanted effects, you should quotemeta them first.

  • Either by using the quotemeta function: $old = quotemeta "question?"
  • Or by using a \Q...\E region in the regex:

    s/\Q$old\E/$new/g
    
2

? has a special meaning in regular expressions. You just need to escape it in your pattern:

$old = 'question\?';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.