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

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 perlop for more details). Remember also that any regex 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 regex would also spuriously match "di".
Back to perlfaq6