如何在与该程序相同的文件中声明和使用Perl 6模块? [英] How can I declare and use a Perl 6 module in the same file as the program?

查看:67
本文介绍了如何在与该程序相同的文件中声明和使用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 );

这篇关于如何在与该程序相同的文件中声明和使用Perl 6模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆