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

hi monks,
I have one string "/morse_value" that i want to convert it into "\morse_value"
for this i am using s/// operator and my code is as below.
$a="/morse_value"; $b=$a =~ s///\/g; print "$a\n";
after running this i am getting error as below
Search pattern not terminated at x.pl line 3. solution for this will be a greate help for me.. thx in advace ....for reply.

Replies are listed 'Best First'.
Re: Problem in sustitution of a string
by GrandFather (Saint) on Aug 14, 2007 at 03:48 UTC

    Actually, that is not the message I see (nor quite what I would expect). I see:

    Backslash found where operator expected at noname.pl line 5, near "s// +/\" syntax error at noname.pl line 5, near "s///\" Search pattern not terminated at noname.pl line 5.

    The rule is: resolve the first error first. Perl is expecting to see either flag characters or a termination character such as ; - Perl doesn't expect to see a \, it makes no sense there.

    What were you trying to achieve with the regex substitution? Replace the / with \? Instead try:

    $a =~ s!/!\\!g;

    Note the use if ! to delimit the regex so that / can be used unquoted, and also that \ needs to be quoted.

    BTW: avoid the use of $a and $b except in the special context of sort.


    DWIM is Perl's answer to Gödel
Re: Problem in sustitution of a string
by dynamo (Chaplain) on Aug 14, 2007 at 06:38 UTC
    Your only real issue was that you have to backslash (verb) the slash (noun) and the backslash (noun) in that expression. Also, you weren't using $b, so I'd drop it:
    $a = "/morse_value"; $a =~ s/\//\\/g; print "$a\n";
    Good luck.