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

I have a regex to replace dashes between words with spaces, like this

$newName =~ s/(\w)-(\w)/\1 \2/g;

It works fine, but I get a warning saying

\1 better written as $1 at newstuff_rename.pl line 46. \2 better written as $2 at newstuff_rename.pl line 42.

This seems to contradict the documentation, which says:

Although $1 and \1 represent the same thing, care should be taken to use matched variables $1 , $2 ,... only outside a regexp and backreferences \1 , \2 ,... only inside a regexp; not doing so may lead to surprising and unsatisfactory results.

Am I misunderstanding this?

EDIT

Got it. Thanks for the clarification!

Replies are listed 'Best First'.
Re: Regex backreferences
by ikegami (Patriarch) on Mar 20, 2011 at 07:06 UTC

    The replacement argument of the substitution operator is not a regular expression. You shouldn't use \1 in it since \1 means "match what the first set of captures captured".

    For example, you'd use something like the following to put brackets around repeated characters:

    s/((.)\2+)/[$1]/g

    Update: Added example.

Re: Regex backreferences
by jwkrahn (Abbot) on Mar 20, 2011 at 07:07 UTC

    s/(\w)-(\w)/\1 \2/g has two parts, the first part /(\w)-(\w)/ is the regexp, and the second part /\1 \2/ is just the same as any double quoted string so you have to use $1 and $2 here instead of \1 and \2.