tags:

views:

154

answers:

2

I'm debugging some code and wondered if there is any practical difference between $1 and \1 in Perl regex substitutions

For example:

my $package_name = "Some::Package::ButNotThis";

$package_name =~ s{^(\w+::\w+)}{$1};  

print $package_name; # Some::Package

This following line seems functionally equivalent:

$package_name =~ s{^(\w+::w+)}{\1};

Are there subtle differences between these two statements? Do they behave differently in different versions of Perl?

+8  A: 

From perldoc perlre:

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. But it can potentially clash with octal escapes. This happens when the backslash is followed by more than 1 digits.

eugene y
Could this cause an error if $1 was set previously?
Mr Foo Bar
If you have at least one capture buffer within the regex, whatever was previously stored in $1 will be overwritten.
Jordan Lewis
It should be noted that in a replacement (`s/.../.../`), the first part is a match, the second is not.
Svante
+12  A: 
Sinan Ünür
And if you want a laugh, you'll also install [warnin's](http://wonkden.net/modules.html). :)
Ether