我想在Perl6中制作一个
modulino (a file that can run as either a module or a script).
@H_404_2@以下代码从命令行“处理”文件名:
sub MAIN ( *@filenames ) { for @filenames -> $filename { say "Processing $filename"; } }@H_404_2@保存为main.pm6我可以运行它并且它可以工作:
perl6 main.pm6 hello.txt world.txt Processing 'hello.txt' Processing 'world.txt'@H_404_2@所以,我希望这是一个模块,以便我可以添加功能并使测试更容易.但是,当我向它添加模块声明时,它不再输出任何内容:
module main; sub MAIN ( *@filenames ) { for @filenames -> $filename { say "Processing '$filename'"; } }@H_404_2@这导致什么输出:
perl6 main.pm6 hello.txt world.txt@H_404_2@那么,我如何在Perl6中构建modulino? @H_404_2@我使用的是从January 2015 release of Rakudo Star开始在MoarVM运行的Perl6. @H_404_2@更新: @H_404_2@当我尝试将模块包装在大括号中时:
module main { sub process (@filenames) is export { for @filenames -> $filename { say "Processing '$filename'"; } } }; sub MAIN ( *@filenames ) { process(@filenames) }@H_404_2@我也得到错误:
===SORRY!=== Error while compiling main.pm6 Undeclared routine: process used at line 14. Did you mean 'proceed'?
解决方法
MAIN子需要在模块外声明,但它仍然必须能够看到进程.
@H_404_2@有多种方法可以实现这一点,例如,根本不要声明模块
sub process(@filenames) { for @filenames -> $filename { say "Processing '$filename'"; } } sub MAIN(*@filenames) { process(@filenames); }@H_404_2@通过使进程成为我们的范围并通过其长名称调用它
module main { our sub process(@filenames) { for @filenames -> $filename { say "Processing '$filename'"; } } } sub MAIN(*@filenames) { main::process(@filenames); }@H_404_2@或者通过导出流程并将其导入MAIN主体
module main { sub process(@filenames) is export { for @filenames -> $filename { say "Processing '$filename'"; } } } sub MAIN(*@filenames) { import main; process(@filenames); }@H_404_2@在我看来,最合适的选择是将MAIN添加到模块并将其导入脚本的主线.这样,模块中声明的所有内容在MAIN中都是可见的,而不必显式导出所有内容:
module main { sub process(@filenames) { for @filenames -> $filename { say "Processing '$filename'"; } } sub MAIN(*@filenames) is export(:MAIN) { process(@filenames); } } import main :MAIN;@H_404_2@请注意,默认情况下这不会导出MAIN,即模块的用户只有在提供:MAIN标记时才会获取MAIN.