代码之家  ›  专栏  ›  技术社区  ›  Paul A Jungwirth Mathew Sachin

perl:检查文件是作为模块加载的还是直接运行的

  •  3
  • Paul A Jungwirth Mathew Sachin  · 技术社区  · 16 年前

    如何用perl编写测试以查看我的文件是直接运行的还是从其他源导入的?我想这样做是为了便于将所有内容打包到一个文件中,但仍然可以针对这些函数编写单元测试。我的想法是这样的:

    if (running_directly()) {
      main();
    }
    
    def main {
      this();
      that();
    }
    
    def this {
      # ...
    }
    
    def that {
      # ...
    }
    

    然后在一个单独的perl脚本中,我可以加载原始文件并将其称为单元测试。

    我记得以前看到过这种情况,但我不记得怎么做了。我希望避免对某些已知值测试$0,因为这意味着用户无法重命名脚本。

    3 回复  |  直到 15 年前
        1
  •  11
  •   friedo    16 年前

    首先,Perl没有 def 关键字。:)

    但您可以通过执行以下操作来检查模块是直接执行还是包含在其他地方:

    __PACKAGE__->main unless caller;
    

    自从 caller 如果您位于调用堆栈的顶部,则不会返回任何内容,但如果您位于 use require

    一些人已经将可怕的新词“modulino”分配给了这个模式,所以用它作为google的燃料。

        2
  •  4
  •   Community Mohan Dere    9 年前

    你可能在想 brian d foy's "modulino" recipe ,它允许将文件作为独立脚本或模块加载。

    在他的书中也有更深入的描述。 "Scripts as Modules" Perl日志的文章以及“ How a Script Becomes a Module" 在Perlmonks。

        3
  •  1
  •   Community Mohan Dere    9 年前

    看到我 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