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

How do i find the $ character in a string and replace it with some other value. I used =~s/\$/tmp/g, but is not working.

Replies are listed 'Best First'.
Re: Finding $ character
by Joost (Canon) on Dec 28, 2004 at 12:50 UTC
    Sure it works. Your code is incomplete, though, so I'll just guess that you don't actually have a $ in your input string. You are probably interpolating an uninitalized variable in your string. Using warnings and strict should have cought that. Also "is not working" is not really a good description of an error. It's always doing something - it just doesn't do what you expect:

    #!/usr/local/bin/perl -w use strict; my $string = 'begin$end'; $string =~ s/\$/tmp/g; print "$string\n";
    output:
    begintmpend
    See also strict, warnings and try searching for "interpolated" in perldata.
Re: Finding $ character
by Corion (Patriarch) on Dec 28, 2004 at 12:49 UTC

    Your error must lie elsewhere, as the following code works for me:

    #!/usr/bin/perl use strict; my $string = 'The price for one night is 10$, the price for two nights + is 100$, cash!'; print "String before:\n"; print "$string\n"; $string =~ s!\$! dollar!g; print "String after:\n"; print "$string\n";
Re: Finding $ character
by ambrus (Abbot) on Dec 28, 2004 at 12:50 UTC

    That works for me, I think you'll have to search for the problem elsewhere. Make sure the dollar signs are in the sting at first place, you have to escape them in a double-quoted string, like:

    $x = "The large one costs \$3.50, the small one \$2.50.\n"; $x=~s/\$/tmp/g; print $x;
Re: Finding $ character
by wfsp (Abbot) on Dec 28, 2004 at 12:54 UTC
    I managed to get:
    my $string = 'aa$aa'; $string =~ s/\$/tmp/g; print "$string\n";
    to produce:
    aatmpaa
    What was in your string? What output did you get and what did you expect?
Re: Finding $ character
by gube (Parson) on Dec 28, 2004 at 14:02 UTC
    'just try this \Q is for convert special character to Normal character
    $a = '$priyal'; $a =~ s/\Q$\E/tmp/g; print $a; o/p:tmppriyal
    Regards, Gubendran.L

      This is plain wrong. It just can't work. Did you try it before posting? Do you know what \Q is for? (It's for escaping regexp metacharacters from strings interpolated in regexen.)

      From perlop, section Quote and Quote-like Operators:

      You cannot include a literal "$" or "@" within a "\Q" sequence. An unescaped "$" or "@" interpolates the corresponding variable, while escaping will cause the lit- eral string "\$" to be inserted. You'll need to write something like "m/\Quser\E\@\Qhost/".

      It doesn't produce that output when I run it. In fact it doesn't change the string at all. Did you actually test it?

      Makeshifts last the longest.