is export and binding in Perl 6

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.

Leave a Comment