Here is the first example:
$g=5;
sub A {
my $x=2; # $x uses static scoping
local $y=3; # $y uses dynamic soping
local $g=7;
print "In A: g=$g, x=$x, y=$y\n";
B();
}
sub B {
print "In B: g=$g, x=$x, y=$y\n";
C();
}
sub C {
print "In B: g=$g, x=$x, y=$y\n";
}
A();
print "In main: g=$g, x=$x, y=$y\n";
Here is the output of first example:
In A: g=7, x=2, y=3
In B: g=7, x=, y=3
In B: g=7, x=, y=3
In main: g=5, x=, y=
Here is the second example:
sub big {
my $var=1;
sub sub1 () {
print " In sub1 var=$var\n";
}
sub sub2 () {
$var = 2;
print "In sub2, var is $var\n";
sub1();
}
sub1();
sub2();
sub1();
}
big();
Here is the second output:
In sub1 var=1
In sub2, var is 2
In sub1 var=2
In sub1 var=2
The question is:
Why in the second example sub B
and sub C
can acess to my $x=2;
while in the first example sub1()
and sub2()
can't acces to my $var=1;
I believe my
used for static scoping, also there is no any other $x
in static scope of sub big
in example 2, I expected no output in the second example, like this: In sub1 var=
.How in the second example,can sub1
and sub2
can acces to $x
altough it has declared with the word my
, why does it not behave like the first example?