Take the 2-minute tour ×
$text_to_search = "example text with [foo] and more";
$search_string = "[foo]";

if($text_to_search =~ m/$search_string/) print "wee";

Please observe above code. For some reason I would like to find the text "[foo]" in the $text_to_search variable and print "wee" if I find it. To do this I would have to ensure that the [ and ] is substitued with [ and ] to make perl treat it as characters instead of operators.

Question: How can I do this without having to first replace [ and ] with \[ and \] using a s/// expression?

share|improve this question
I would say get into the habit of using the qr// construct for regular expressions and escaping special regex chars if literal is needed. Quotemeta will quote ALL special regex chars. If you just want to find a literal string in another, use index() instead. –  sln Jan 6 '11 at 17:01

3 Answers 3

Use the quotemeta function:

$search_string = quotemeta "[foo]";

print "wee" if ($text_to_search =~ /$search_string/);
share|improve this answer

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";
share|improve this answer
++. Merely for completeness: You could use the quotemeta function for a similar outcome: $text_to_search = quotemeta "example text with [foo] and more"; /$search_string/ But this will change $text_to_search, rather than quotemeta'ing only inside the regex. –  Hugmeir Jan 6 '11 at 15:20
@Hugmeir: That's why you want to quotemeta the substring to search for instead. See my answer. –  Platinum Azure Jan 6 '11 at 15:28
Whoops, yeah, my bad. –  Hugmeir Jan 6 '11 at 15:31

As guys already written you can use quotemeta (\Q \E) if you Perl is 5.16+ but if below you can simply avoid using regexp at all.

for example by using index command

if (index($text_to_search, $search_string) > -1){
    print "wee";
share|improve this answer

Your Answer


