Why is "my @variable" inside sub and modified sub / sub behaves so weird

I have a weird instruction (for a Python programmer) that simplifies as follows:

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:

inside: $VAR1=[ 1 ]
outside: $VAR1 = [ 1 ]
inside: $VAR1=[1, 1]
outside: $VAR1= []

I thought that when called &a, @xthere is an empty array after " my @x" and has one element after " &b" and then dead. Every time I call &a, it's the same. therefore, the exit should be everything $VAR1 = [ 1 ].

Then I read something like a named routine, which is defined once in the symbol table, then I do " my $b = sub { ... }; &$b;", it seems to me that makes sense.

How to explain?

+4
source share
1

man- perlref:

named , [.. "" ] . , , .

, ( b) @x, "" @x, , a , b 1 @x, , . a @x , b , 1 (), a , () ().

, , my $b = sub { ... }, @x "" a lexical @x.

+12

Source: https://habr.com/ru/post/1663195/


All Articles