如何在与该程序相同的文件中声明和使用Perl 6模块?
有时候,我不需要多重文件,尤其是当我在想保持一个很好的结构以便以后再转换时.我想做这样的事情:
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
阅读 Perl 6模块"文档,我看不到任何方法这样做是因为各种动词都希望在特定文件中查找.
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.
子例程声明是词法的,因此&foo
在模块主体之外不可见.您需要在主线代码中添加导入语句以使其可见:
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 );
仅作记录,您还可以在主线中手动声明一个&foo
变量,然后在模块内将其分配给该变量:
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 );