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