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

I am trying to escape a charater in a string. For example, if I have a string that looks like this:

This is my string that has a | in it.
I want to change it to this:
This is my string that has a \| in it.

Now, in this specific case I can do it with this simple statement:

$_ =~ s/\|/\\\|/g;
My problem is that the character that needs to be escaped is actually held in a variable ($delim). I tried this:
$_ =~ s/\{$delim}/\\{$delim}/g;
But it doesn't work.

I know that I could go character by character through the sring, but that seems kinda ugly.

Any ideas would be really helpful.
thanks.

Replies are listed 'Best First'.
Re: How to 'escape' a character in a string?
by moritz (Cardinal) on May 23, 2012 at 16:35 UTC
Re: How to 'escape' a character in a string?
by toolic (Bishop) on May 23, 2012 at 16:40 UTC
    quotemeta
    my $delim = quotemeta '|'; my $s = 'This is my string that has a | in it.'; $s =~ s/($delim)/\\$1/g; print "$s\n"; __END__ This is my string that has a \| in it.
Re: How to 'escape' a character in a string?
by ikegami (Patriarch) on May 23, 2012 at 17:33 UTC

    You need to convert the delimiter into a regex pattern that matches the delimiter. That's what quotemeta does.

    my $pat = quotemeta($delim); s/$pat/\\$delim/g;

    quotemeta can be accessed with \Q..\E in regex literals (among others).

    s/\Q$delim\E/\\$delim/g;

    or

    s/\Q$delim/\\$delim/g; # \E is optional at the end of the literal.

      Thanks everyone for your help!

      Love learning about new stuff.