Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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:


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)/

Replies are listed 'Best First'.
Re^2: Difference between $1 and \1.
by lidden (Curate) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1010491]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2017-11-25 10:10 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (355 votes). Check out past polls.