joedoc has asked for the wisdom of the Perl Monks concerning the following question:

This ought to be simple, but I can't figure it out...
My script is a web form that accepts text from the form and drops it into a mysql database table. Certain characters have to be escaped or mysql chokes or does the odd thing. One is the backslash...I'm trying to do this:
s/\/\\/g;
which doesn't work.
I tried various convolutions, such as:
s/\Q/\E/\\/g;
which compiles ;-) but doesn't add the additional backslash. Where am I brain damaged on this?

Replies are listed 'Best First'.
Re: escaping the backslash
by chromatic (Archbishop) on Apr 29, 2003 at 20:59 UTC

    Consider using DBI's quote() method instead, or, better yet, placeholders.

Re: escaping the backslash
by Jenda (Abbot) on Apr 29, 2003 at 21:13 UTC

    chromatic is right, you should use the quote() or even better the placeholders. This is just to explain why what you tried didn't work.

    The replacement string in a s/// is basicaly just a doublequoted string. In such a string if you want to include a literal backslash you have to escape it:

    print "A backslash \\ is here\n";
    In your case you need two literal backslashes so you have to enter four in the replacement.

    Second, the list of characters that need to be escaped in a regular expression is even longer than in a doublequoted string. What they both have in common is that you have to type two backslashes if you want to get a single literal backslash. So the line should look like this:

    s/\\/\\\\/g;
    or better
    s{\\}{\\\\}g ;
    (The second version is a bit more readable.)

    Jenda
    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
       -- Rick Osborne

    Edit by castaway: Closed small tag in signature

      Jenda, chromatic;
      Thanks for the advice. I can see in Jenda's explanation why the substitution wasn't working. I took a crack at the quote() method, but it turns out the text being dumped on the form has newlines, which is another bag of worms for quote(). ;-)
      Since it's time to go home, I'll take a shot with the placeholders tomorrow. Thanks for the great assistance.
      joedoc
        Your newline problem is probably related to the output record separator. You can just assign to it to change the default behaviour.

        $, - output field separator (default: comma)
        $\ - output record separator (default: newline)
        $" - list separator (default: space)