- 论坛徽章:
- 145
|
回复 16# inchonline
it hard to say what are different between $1 and \1
simple rule for normal using.
use \1 on the left side of s///. ex: s/(..)\1/.../
use $1 on the right side of s///. ex: s/....../$1/
please refer the "perlre" for detail information or below:
$ perldoc perlre
NAME
perlre - Perl regular expressions
DESCRIPTION
This page describes the syntax of regular expressions in Perl.
...
Capture buffers
The bracketing construct "( ... )" creates capture buffers. To refer to the
current contents of a buffer later on, within the same pattern, use \1 for the
first, \2 for the second, and so on. Outside the match use "$" instead of "\".
(The \<digit> notation works in certain circumstances outside the match. See
"Warning on \1 Instead of $1" below for details.) Referring back to another part
of the match is called a backreference.
...
Warning on \1 Instead of $1
Some people get too used to writing things like:
$pattern =~ s/(\W)/\\\1/g;
This is grandfathered (for \1 to \9) for the RHS of a substitute to avoid
shocking the sed addicts, but it's a dirty habit to get into. That's because in
PerlThink, the righthand side of an "s///" is a double-quoted string. "\1" in
the usual double-quoted string means a control-A. The customary Unix meaning of
"\1" is kludged in for "s///". However, if you get into the habit of doing that,
you get yourself into trouble if you then add an "/e" modifier.
s/(\d+)/ \1 + 1 /eg; # causes warning under -w
Or if you try to do
s/(\d+)/\1000/;
You can't disambiguate that by saying "\{1}000", whereas you can fix it with
"${1}000". The operation of interpolation should not be confused with the
operation of matching a backreference. Certainly they mean two different things
on the left side of the "s///".
|
|