Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
XP is just a number
 
PerlMonks  

Re: Difference between $1 and \1.

by 7stud (Deacon)
on Dec 27, 2012 at 10:50 UTC ( #1010491=note: print w/ replies, xml ) Need Help??


in reply to Difference between $1 and \1.

$str = aa;

Unless you have a variable named aa somewhere, that line will give you an error.

The rule is: $1 is used inside strings and \1 is used inside regexes.

Examine the inputs for the substitution operator:

s/regex/string/

Here are some examples:

my $line = 'abbc'; $line =~ s/(.)\1/XX/g; say $line; --output:-- aXXc
my $line = 'abbc'; $line =~ s/(.)/X$1X/g; say $line; --output:-- XaXXbXXbXXcX
my $line = 'abbc'; $line =~ s/(.)/$1$1/g; say $line; --output:-- aabbbbcc

I used the following regex to find repeating characters in a string.

$str = aa; $str =~ /(a)$1/; print "$&";
This does not match 'aa'. It matched only 'a'.

A regex acts like a double quoted string with respect to variable interpolation (and with respect to string escape sequences). $1 has not been assigned a value by a previous match, so $1 is equal to undef. And when undef is used like a string, perl converts it to a blank string. Interpolating undef into a double quoteish context, like your regex, means you are interpolating a blank string, so your regex is equivalent to: /(a)/


Comment on Re: Difference between $1 and \1.
Select or Download Code
Re^2: Difference between $1 and \1.
by lidden (Deacon) on Dec 31, 2012 at 23:05 UTC
    $str = aa;

    Unless you have a variable named aa somewhere, that line will give you an error.

    It is only an error when strict subs are in effect.
    { no strict 'subs'; my $str = aa; say $str; }
    Though having strict on is almost always a good thing.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1010491]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2014-04-21 10:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (492 votes), past polls