How can I declare and use a Perl 6 module in the same file as the program?

 ̄綄美尐妖づ 提交于 2019-12-10 13:34:40

问题


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

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