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

Hi,

Is there a difference between using $1 and \1 to remember things matched? If I understand it correctly, $1 can used outside the matching or substitution expression but \1 can't. Am I right?

cheers,

kiat

Edit kudra, 2001-12-23 Changed title

Replies are listed 'Best First'.
Re: regex question...
by Zaxo (Archbishop) on Dec 23, 2001 at 12:39 UTC

    Yes. the regex centered ops s/// and m// take \1 in the regex itself for the first fully matched pattern in parentheses. $1 means the same in the second argument or until the next regex.

    After Compline,
    Zaxo

      Additionally:
      Although you can use \(digit) in the right side of a s/// operation, you shouldn't. This was included (i would guess) just to appease the sed junkies out there ;)

      Generally the only time \(digit) should be used is on the LHS of a s///, or within a m//.
      Example:
      /(foo)\1/; # is effectively the same as /(foo){2}/;
Re: regex question: $1 vs. \1
by robin (Chaplain) on Dec 23, 2001 at 18:32 UTC
    \1 and $1 mean different things, most of the time.
    • In ordinary code, $1 refers to the text that was matched by the first pair of parentheses in the last regular expression match or substitution. On the other hand, \1 is a reference to the constant scalar 1:
      [robin@robin robin]$ perl -le 'print \1' SCALAR(0xd8b8)
    • In a regular expression, $1 refers to the text matched by the first pair of parentheses in the previous regular expression, whereas \1 refers to the text matched by the first pair of parentheses in the current regular expression. So this program:
      shift() =~ /(.*)/; shift() =~ /($1)x\1/ && print "yes!\n"
      will print yes! if you pass it a pair of strings like foo fooxfoobar
    • In a substitution string (i.e. the yyy part of a s/xxx/yyy/ command), \1 and $1 both refer to the same thing - the text matched by the first pair of parentheses in the pattern. It's usually considered poor style to use the \1 version here.
Re: regex question: $1 vs. \1
by tachyon (Chancellor) on Dec 23, 2001 at 16:02 UTC

    Also $1 is not initialised on the LHS of the regex whereas \1 is...

    use warnings; $_ = 'oooooo'; s/(o)$1/foo/; s/(o)\1/foo/; s/(o)/\1/; s/(o)/$1/; __END__ Use of uninitialized value in concatenation (.) at script line 3. \1 better written as $1 at script line 5.

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: regex question: $1 vs. \1
by mrbbking (Hermit) on Dec 24, 2001 at 05:55 UTC
    I happened across this today, in the third edition of the Camel Book. On page 152, in the discussion of the s/// operator...
    In the replacement string, $1 returns what the first ... pair of parentheses captured. (You could use also \1 as you would in the pattern, but that usage is deprecated in the replacement. ...)