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

Dear Monks,

I have searched both this list and perlbug, and I don't find anything about this (exactly). The following code 1. works fine and the result is correct. But when I put a '+' character in front of the pattern variable in 2., I get an error.

This is reproducible on all version of perl that I have from 5.6.1 through 5.12.1

Is this an error, or should I be testing for '+' in the first position of the pattern variable? Note: I usually have no idea what /pattern/replacement/ actually contain.

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

2. perl -e '$in="+44"; $out=$in; $out =~ s/$in//; print "Result: |$in|$out|\n";'
Quantifier follows nothing in regex; marked by <-- HERE in m/+ <-- HERE 44/ at -e line 1.

Thank you

Replies are listed 'Best First'.
Re: Substitution, '+' in first position of Pattern
by DrHyde (Prior) on Oct 01, 2010 at 09:21 UTC
    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.

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