Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of $1 through $9 in Perl?

Tags:

scope

regex

perl

What is the scope of $1 through $9 in Perl? For instance, in this code:

sub bla {
    my $x = shift;
    $x =~ s/(\d*)/$1 $1/;
    return $x;    
}

my $y;

# some code that manipulates $y

$y =~ /(\w*)\s+(\w*)/;

my $z = &bla($2);
my $w = $1;

print "$1 $2\n";

What will $1 be? Will it be the first \w* from $x or the first \d* from the second \w* in $x?

like image 478
Nathan Fellman Avatar asked Jun 27 '09 15:06

Nathan Fellman


1 Answers

from perldoc perlre

The numbered match variables ($1, $2, $3, etc.) and the related punctuation set ($+ , $& , $` , $' , and $^N ) are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See ""Compound Statements"" in perlsyn.)

This means that the first time you run a regex or substitution in a scope a new localized copy is created. The original value is restored (à la local) when the scope ends. So, $1 will be 10 up until the regex is run, 20 after the regex, and 10 again when the subroutine is finished.

But I don't use regex variables outside of substitutions. I find much clearer to say things like

#!/usr/bin/perl

use strict;
use warnings;

sub bla {
    my $x = shift;
    $x =~ s/(\d*)/$1 $1/;
    return $x;    
}

my $y = "10 20";

my ($first, $second) = $y =~ /(\w*)\s+(\w*)/;

my $z = &bla($second);
my $w = $first;

print "$first $second\n";

where $first and $second have better names that describe their contents.

like image 112
Chas. Owens Avatar answered Sep 21 '22 18:09

Chas. Owens