如何在Perl中编写测试以查看我的文件是直接运行还是从其他来源导入?我想这样做可以很容易地将所有内容捆绑在一个文件中,但仍然可以针对这些函数编写单元测试。我的想法是有这样的事情:
if (running_directly()) {
main();
}
def main {
this();
that();
}
def this {
# ...
}
def that {
# ...
}
然后在一个单独的perl脚本中,我可以加载原始文件并调用此&作为单元测试。
我记得以前看过这件事,但我不记得怎么做了。我想避免针对某个已知值测试$ 0,因为这意味着用户无法重命名脚本。
答案 0 :(得分:11)
首先,Perl没有def
个关键字。 :)
但您可以通过执行以下操作来检查模块是直接执行还是包含在其他地方:
__PACKAGE__->main unless caller;
如果您位于调用堆栈的顶部,caller
将不会返回任何内容,但如果您位于use
或require
内,则会返回。
有些人已将可怕的新词“modulino”分配给此模式,因此将其用作Google加油。
答案 1 :(得分:4)
您可能会想到brian d foy's "modulino" recipe,它允许将文件作为独立脚本或模块加载。
Perl Journal的"Scripts as Modules"文章以及Perlmonks的“How a Script Becomes a Module"”也对此进行了更深入的描述。
答案 2 :(得分:1)
请参阅我的related question有关测试Perl脚本的信息。您可能还有兴趣使用相关模块运行REPL:
package REPL;
use Modern::Perl;
use Moose;
sub foo {
return "foo";
}
sub run {
use Devel::REPL;
my $repl = new Devel::REPL;
$repl->load_plugin($_) for qw/History LexEnv Refresh/;
$repl->run;
}
run if not caller;
1;
然后在命令行上:
$ perl REPL.pm
$ REPL->new->foo;
bar
^D
$ perl -MREPL -E "say REPL->new->foo"
bar