问题
Why isn't the value of a variable with :=
binding exported?
$ cat myModule.pm6
our $a is export = 42;
our $b is export := $a;
$ cat program.p6
use myModule;
say $a;
say $b;
$ perl6 program.p6
42
(Any) # Why?
回答1:
An our
-scoped variable is really just a lexical variable (like my
) that - instead of having a Scalar
freshly created per scope - is initialized by being bound to a symbol of that name in the Stash
of the current package. So effectively, this:
our $foo;
Is doing this:
my $foo := $?PACKAGE.WHO<$foo>;
And so:
our $foo = 42;
Is doing this:
(my $foo := $?PACKAGE.WHO<$foo>) = 42;
Rebinding the symbol thus means it's no longer associated with the Scalar
container stored in the Stash
.
Exporting an our
-scoped variable exports the Scalar
container from the stash that the variable is bound to at scope entry time. Thus the assignment assigns into that exported Scalar
container. By contrast, binding replaces the lexical with something entirely different and unrelated to what was exported.
This is why you aren't allowed to export a my
-scoped variable: a fresh Scalar
is bound every scope entry, but exportation is a compile-time thing, so there would be no way to ever modify the thing that was exported.
来源:https://stackoverflow.com/questions/52873708/is-export-and-binding-in-perl-6