I have a strange behaved (to Python programmer) subroutine, which simplified as the following:
use strict;
use Data::Dumper;
sub a {
my @x;
sub b { push @x, 1; print "inside: ", Dumper(\@x); }
&b;
print "outside: ", Dumper(\@x);
}
&a;
&a;
I found the result is:
inside: $VAR1=[ 1 ]
outside: $VAR1 = [ 1 ]
inside: $VAR1=[1, 1]
outside: $VAR1= []
What I thought is when calling &a
, @x
is empty array after "my @x
" and has one element after "&b
", then dead. Every time I call &a
, it is the same. so the output should be all $VAR1 = [ 1 ]
.
Then I read something like named sub routine are defined once in symbol table, then I do "my $b = sub { ... }; &$b;
", it seems make sense to me.
How to explain?