is export and binding in Perl 6

时间秒杀一切 提交于 2021-02-13 15:43:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!