Perl 是否有相当于 Python 的“if __name__ == '__main__'”?

发布于 2024-07-16 03:45:37 字数 260 浏览 3 评论 0原文

有没有一种方法可以确定当前文件是否是 Perl 源中正在执行的文件? 在 Python 中,我们使用以下构造来实现此目的:

if __name__ == '__main__':
    # This file is being executed.
    raise NotImplementedError

我可以使用 FindBin 和 __FILE__ 来将一些东西组合在一起,但我希望有一种规范的方法可以做到这一点。 谢谢!

Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:

if __name__ == '__main__':
    # This file is being executed.
    raise NotImplementedError

I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

筱果果 2024-07-23 03:45:37
unless (caller) {
  print "This is the script being executed\n";
}

请参阅调用者。 它在主脚本中返回undef。 请注意,这在子例程内部不起作用,仅在顶级代码中起作用。

unless (caller) {
  print "This is the script being executed\n";
}

See caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code.

倾城月光淡如水﹏ 2024-07-23 03:45:37

请参阅 brian d foy 文章的“应用程序子类(第 18 章)”部分五种方法改进您的 Perl 编程

See the "Subclasses for Applications (Chapter 18)" portion of brian d foy's article Five Ways to Improve Your Perl Programming.

谈情不如逗狗 2024-07-23 03:45:37

unless caller 很好,但更直接的并行以及更显式检查是:

use English qw<$PROGRAM_NAME>;

if ( $PROGRAM_NAME eq __FILE__ ) { 
    ...
}

只是想我会把它放在那里。

编辑

请记住,$PROGRAM_NAME(或“$0”)是可写的,因此这不是绝对的。 但是,在大多数实践中(除了意外或模块失控之外),这可能不会改变,或者至多改变本地在另一个范围内。

unless caller is good, but a more direct parallel, as well as a more explicit check, is:

use English qw<$PROGRAM_NAME>;

if ( $PROGRAM_NAME eq __FILE__ ) { 
    ...
}

Just thought I'd put that out there.

EDIT

Keep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文