in reply to Make a variable safe for a regex.

Quote everything that could be a metacharacter before using the variable: s/(\W)/\\$1/g

There's also quotemeta, but I've been using the above pattern for years.

Replies are listed 'Best First'.
Re^2: Make a variable safe for a regex.
by Anno (Deacon) on Feb 25, 2007 at 22:55 UTC
    Well, they appear to do the same, at least in the one-byte character range:
    my $str = join '', map chr, 0 .. 255; my $qm = quotemeta( $str); ( my $kyle = $str) =~ s/(\W)/\\$1/g; my $quoted_qm = join '', $qm =~ /\\(.)/g; my $quoted_kyle = join '', $kyle =~ /\\(.)/g; printf "quotemeta: %d, kyle: %d (%s)\n", length $quoted_qm, length $quoted_kyle, $quoted_qm eq $quoted_kyle ? "same" : "differernt";
    That prints
    quotemeta: 192, kyle: 192 (same)
    Anno

      \Q and quotemeta() are the same function.

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        True, but kyle's alternative (which I compared with quotemeta) isn't based on \Q.

        Anno