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

From a form I have input containing both $ signs and @ signs. These are put into $intext. How can I change $intext to $outtext, which has all of the $ and @ turned into \$ and \@ ?

Replies are listed 'Best First'.
Re: How can I replace special characters?
by blakem (Monsignor) on Oct 16, 2001 at 02:39 UTC
    Take a look at the quotemeta operator, which escapes lots of things includeing $ and @. You might also try the regex  s/([\$\@])/\\$1/g which will only escape $ and @, as in:
    #!/usr/bin/perl -wT use strict; my $txt = '$a @b $c %d'; my $out1 = quotemeta($txt); (my $out2 = $txt) =~ s/([\$\@])/\\$1/g; print "txt = $txt\n"; print "out1 = $out1\n"; print "out2 = $out2\n"; =OUTPUT txt = $a @b $c %d out1 = \$a\ \@b\ \$c\ \%d out2 = \$a \@b \$c %d

    -Blake

Re: How can I replace special characters?
by Zaxo (Archbishop) on Oct 16, 2001 at 03:43 UTC

    You need to post code, too. In most circumstances, once $ and @ are safely tucked away in a string variable you don't need to worry about escaping them. If, on the other hand, you

    1. use them in a regex,
    2. eval them, or
    3. pass them to the shell through exec, system, or backticks,
    you may need to escape them. What you need to escape depends on what is to evaluate them and what your intentions are.

    Update: Clarified language introducing the list of exceptions.

    After Compline,
    Zaxo

Re: How can I replace special characters?
by merlyn (Sage) on Oct 16, 2001 at 02:17 UTC
    It's pretty rare that you'd need that level of escaping. What's using the result such that $ and @ are dangerous characters?