tags:

views:

252

answers:

3

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?

+14  A: 
Chas. Owens
I don't understand the documentation you quoted. Maybe I'm unclear on the implications of "dynamically scoped." So what is the answer to the question?
Rob Kennedy
See http://perl.plover.com/FAQs/Namespaces.html
Sinan Ünür
@Rob Kennedy I have clarified what dynamic scoping means. You might also want to look at http://perldoc.perl.org/perlfaq7.html#What%27s-the-difference-between-dynamic-and-lexical-(static)-scoping%3F--Between-local()-and-my()%3F
Chas. Owens
The term "dynamic scope" seems only to be defined in terms of what "local" does, but since "local" isn't used in regex matches, it's a little harder to see that it's in effect. Thanks for clarifying. Sinan, your linked page doesn't actually contain the word "dynamic," so it's not much help.
Rob Kennedy
@ Rob: I believe that the connection is that Perl's `local` creates dynamic scope. See the follow-up to the article Sinan posted, especially here: http://perl.plover.com/local.html#5_Dynamic_Scope
Telemachus
+2  A: 

The variables will be valid until the next time they are written to in the flow of execution.

But really, you should be using something like:

my ($match1, match2) = $var =~ /(\d+)\D(\d+)/;

Then use $match1 and $match2 instead of $1 and $2, it's much less ambiguous.

ReaperUnreal
+4  A: 

By making a couple of small alterations to your example code:

sub bla {
    my $x = shift;
    print "$1\n";
    $x =~ s/(\d+)/$1 $1/;
    return $x;
}
my $y = "hello world9";

# some code that manipulates $y

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

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

print "$1 $2\n$z\n";

we get the following output:

hello
hello world9
world9 9

showing that the $1 is limited to the dynamic scope (ie the $1 assigned within bla ceases to exist at the end of that function (but the $1 assigned from the $y regex is accessible within bla until it is overwritten))

Cebjyre
More importantly, I think, it shows that $1 *outside* of bla is not affected by what happens *inside* of bla.
Rob Kennedy