Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

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

by faq_monk (Initiate)
on Oct 08, 1999 at 00:25 UTC ( [id://663]=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

The Perl parser will expand $variable and @variable references in regular expressions unless the delimiter is a single quote. Remember, too, that the right-hand side of a s/// substitution is considered a double-quoted string (see the perlop manpage for more details). Remember also that any regexp special characters will be acted on unless you precede the substitution with Q. Here's an example:

    $string = "to die?";
    $lhs = "die?";
    $rhs = "sleep no more";

    $string =~ s/Q$lhs/$rhs/;
    # $string is now "to sleep no more"

Without the Q, the regexp would also spuriously match ``di''.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2025-03-27 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (70 votes). Check out past polls.

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.