in reply to Re: Substitution, '+' in first position of Pattern
in thread Substitution, '+' in first position of Pattern

I do know that '+' is a special character, but in any other place besides the first position, it works correctly. I have previously tried "\+44", and received the same error message.

But as you suggest, I changed the code to

perl -e '$in=quotemeta("+44"); $out=$in; $out =~ s/$in//; print "Result: |$in|$out|\n";'

However, the result was incorrect: Result: |\+44|\|

Thank you.

Replies are listed 'Best First'.
Re^3: Substitution, '+' in first position of Pattern
by JavaFan (Canon) on Oct 01, 2010 at 10:40 UTC
    The problem is that your test is wrong. Try this:
    $ perl -le '$out = "+44"; $in=quotemeta $out; $out =~ s/$in//; print " +Result: |$in|$out|\n";' Result: |\+44||
    Note that '$in' is the pattern, not the original value of '$out'.

    Alternatively, you may write:

    $ perl -le '$in = "+44"; $out = $in; $out =~ s/\Q$in//; print "Result: + |$in|$out|\n";' Result: |+44||
Re^3: Substitution, '+' in first position of Pattern
by suhailck (Friar) on Oct 01, 2010 at 10:44 UTC
    Is this what you looking for??
    perl -e '$in=quotemeta("+44");$out=$in; $out=~s/\Q$in\E//;print "Result: |$in|$out|\n";' Result: |\+44||

    Or

    perl -e '$in="+44";$out=$in; $out=~s/\Q$in\E//;print "Result: |$in|$out|\n";' Result: |+44||

      Both JavaFan and suhailck solutions work correctly.

      The quotemata or \Q is what I need in my code. The $in / $out were just to show a sample of the problem. Sorry, I didn't noticed the reversing of pattern at the time, since I got the same error message.

      The actual code has only 1 variable, but without the backslash of '+' my solution didn't work in all case.

      Thank you.

Re^3: Substitution, '+' in first position of Pattern
by Anonymous Monk on Oct 01, 2010 at 10:41 UTC
    but in any other place besides the first position, it works correctly.

    It does not work; it just does not die with a syntax error; there is a difference.

Re^3: Substitution, '+' in first position of Pattern
by gobisankar (Acolyte) on Oct 01, 2010 at 10:25 UTC

    Hi,
    Can you give the expected result which you want for

    perl -e '$in="+44"; $out=$in; $out =~ s/$in//; print "Result: |$in|$ou +t|\n";'
    --
    Thanks&Regards,
    Gobi S.