Perl FAQ 4.22: How can I quote a variable to use in a regexp?

Perl FAQ 4.22

How can I quote a variable to use in a regexp?

From the manual:

    $pattern =~ s/(\W)/\\$1/g;

Now you can freely use /$pattern/ without fear of any unexpected meta- characters in it throwing off the search. If you don't know whether a pattern is valid or not, enclose it in an eval to avoid a fatal run- time error.

Perl5 provides a vastly improved way of doing this. Simply use the new quotemeta character (\Q) within your variable.


Other resources at this site: