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

I have a variable $album that can be any musical artist.

$artist = "Pat's Friend's life";

I need a way (possibly a regex) to make the single quotes in to \' in another variable ($artist_qfix).

can anybody help me with this?
-Pat

Replies are listed 'Best First'.
Re: Substitution Question
by pfaut (Priest) on May 05, 2003 at 20:55 UTC

    If you are doing this to insert the data in a database, I'd recommend making the problem go away by learning how to use placeholders. Look in Tutorials for guides on using DBI and placeholders.

    Anyway, this regex should do what you want.

    $artist =~ s/'/\\'/g;

    You may also have to do substitutions for the escape character itself if it might ever appear in any of your strings.

    90% of every Perl application is already written.
    dragonchild
•Re: Substitution Question
by merlyn (Sage) on May 05, 2003 at 20:53 UTC
    I'm wary of your question. How are you going to be using this new string? If it's to launch a child process, you should consider the shell-less multi-arg version of system or exec. If it's for a DBI query, consider using placeholders.

    Simply backwhacking your quotes is often not necessary, nor is it ever sufficient.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Substitution Question
by artist (Parson) on May 05, 2003 at 20:57 UTC
    (my $artist_qfix= $artist) =~ s['][\\']g; print $artist_qfix;
    • Note : Gives us more of the problem if you wish, we may have better solution for you.

    artist

Re: Substitution Question
by Abigail-II (Bishop) on May 05, 2003 at 23:34 UTC
    ($artist_qfix = $artist) =~ s/'+/\Q$&/g;

    Abigail