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

I want to replace '$' in the string. I tries s/// in so many ways. But not working properly. Finally I got this one. Is there any other simple ways to do it???

#!/usr/bin/perl use strict; use warnings; my $string = 'i am us$ing moni$ka expressi$on'; my @array = (split /\$/,$string); my $flag = 0; my $line = ""; foreach my $element (@array) { if ($flag == 0) { $line = $element; $flag =1; } else { $line = $line.'\$'.$element; } } print $line;

Replies are listed 'Best First'.
Re: How to replace '$' in strings
by choroba (Cardinal) on Dec 14, 2015 at 09:40 UTC
    $string =~ s/\$/\\\$/g;

    The replacement behaves like qq: \\ becomes \, and the dollar sing needs to be backslashed, too, to prevent the interpretation of $/.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      alternative regex delimiter can prevent also strange syndrome..
      perl -e "print $ARGV[0]=~s{\$}{\\\$}r" a$dollar a\$dollar or perl -e "print $ARGV[0]=~s{([\$\@\%])}{\\\1}gr" a$dollar@rray%%hashes a\$dollar\@rray\%\%hashes


      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

        Even simpler: use the special regex delimiter ' (single quote) to suppress interpolation:

        #! perl use strict; use warnings; my $string = 'i am us$ing moni$ka expressi$on'; $string =~ s'\$'\$'g; print $string, "\n";

        Output:

        23:12 >perl 1483_SoPW.pl i am us\$ing moni\$ka expressi\$on 23:14 >

        Hope that helps,

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: How to replace '$' in strings
by johngg (Canon) on Dec 14, 2015 at 11:24 UTC

    To avoid some of the backslash confusion you can use the \xnn hexadecimal ordinal and a look-ahead.

    $ perl -Mstrict -Mwarnings -E ' my $str = q{i am us$ing moni$ka expressi$on}; say $str; $str =~ s{(?=\$)}{\x5c}g; say $str;' i am us$ing moni$ka expressi$on i am us\$ing moni\$ka expressi\$on $

    I hope this is helpful.

    Cheers,

    JohnGG