in reply to Substitution, '+' in first position of Pattern

You are aware that '+' is a special character in regexes, right? As are a whole bunch of other characters. The quotemeta function will help you.

Replies are listed 'Best First'.
Re^2: Substitution, '+' in first position of Pattern
by flexvault (Monsignor) on Oct 01, 2010 at 09:48 UTC

    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.

      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||
      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.

      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.

      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.