raku - 如果需要该文件,Perl 6 是否应该运行 MAIN?

标签 raku modulino

这是一个简短的 Perl 6 程序,它声明了 MAIN子程序。如果我直接执行程序,我应该只看到输出:

$ cat main.pm6
sub MAIN { say "Called as a program!" }

当我直接执行程序时,我看到了输出:
$ perl6 main.pm6
Called as a program!

如果我将它作为一个模块加载,我看不到任何输出:
$ perl6 -I. -Mmain -e "say 'Hey'"
Hey

如果我 use 也一样从程序内部,我看不到任何输出:
$ perl6 -I. -e 'use main'

但是,如果我使用 require ,我得到输出:
$ perl6 -I. -e 'require <main.pm6>'
Called as a program!

Synopsis 06从字面上看,编译单元是直接调用的,而不是被要求的。是否还有其他原因,因为 require在运行时工作(尽管 S06 不排除它)?

Rakudo Star 2016.07 和 2016.10 的行为相同。

最佳答案

首先我们来看看require应该表现得:

根据(非权威)design documents ,

Alternately, a filename may be mentioned directly, which installs a package that is effectively anonymous to the current lexical scope, and may only be accessed by whatever global names the module installs:





Only explicitly mentioned names may be so imported. In order to protect the run-time sanctity of the lexical pad, it may not be modified by require.



结合 S06

This call is performed if and only if:

a) the compilation unit was directly invoked rather than by being required by another compilation unit [...]



据我了解,子 MAIN不应运行未显式导入到主线词法范围中的内容。

可悲的是,user documentation在通过文件名导入运行时的情况下很安静,快速浏览一下(权威)test suite (特别是 S11-modules/require.t )也没有给出答案,尽管我可能错过了它。

现在,让我们看看 Rakudo 的行为方式:

正如预期的那样,通过静态或动态模块名称进行运行时导入
require main;

或者
require ::('main');

不会运行 MAIN除非都声明为 is export并明确导入,即
require main <&MAIN>;


require ::('main') <&MAIN>;

分别。

但是通过文件名导入
require 'main.pm6';

将立即运行 MAIN .

事实上,如果你通过
require 'main.pm6' <&MAIN>;

sub 将被执行两次:一次是在加载编译单元时,第二次是在运行时查找并运行任何 MAIN 时。 sub 在主线范围内。

Rakudo 显然对待 require文件名参数或多或少类似于 EVALFILE并执行其主线,包括任何子 MAIN它遇到。

这不是我所期望的,可能只是一个错误。

关于raku - 如果需要该文件,Perl 6 是否应该运行 MAIN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40778852/

相关文章:

raku - 多行定义或 "//"

regex - 我可以在方法中更改 Perl 6 俚语吗?

Raku .hyper() 和 .race() 示例不起作用

asynchronous - 运行 Perl6 套接字服务器时 MOAR 进程膨胀

perl - 如何在 TextMate 中运行专为证明表单而设计的测试 perl 脚本?

raku - 为什么默认的 Raku if/while/loop/when block 都具有相同的标识值 (.WHICH)?

perl - 如果要测试的模块不可用,我应该如何终止 perl 测试脚本?

perl - 在不知道模块名但知道文件名的情况下加载和使用perl模块

python - 相当于 Perl Modulino for Ruby, Python?

system - 如何在 Perl6 中制作模数?