问题
Sometimes I don't want multiples files, especially if I'm playing around with an idea that I want to keep a nice structure that can turn into something later. I'd like to do something like this:
module Foo {
sub foo ( Int:D $number ) is export {
say "In Foo";
}
}
foo( 137 );
Running this, I get a compilation error (which I think is a bit odd for a dynamic language):
===SORRY!=== Error while compiling /Users/brian/Desktop/multi.pl
Undeclared routine:
foo used at line 9
Reading the Perl 6 "Modules" documentation, I don't see any way to do this since the various verbs want to look in a particular file.
回答1:
Subroutine declarations are lexical, so &foo
is invisible outside of the module's body. You need to add an import statement to the mainline code to make it visible:
module Foo {
sub foo ( Int:D $number ) is export { ... }
}
import Foo;
foo( 137 );
Just for the record, you could also manually declare a &foo
variable in the mainline and assign to that from within the module:
my &foo;
module Foo {
sub foo ( Int:D $number ) { ... } # no export necessary
&OUTER::foo = &foo;
}
foo( 137 );
来源:https://stackoverflow.com/questions/34688662/how-can-i-declare-and-use-a-perl-6-module-in-the-same-file-as-the-program