Perl 是否有相当于 Python 的“if __name__ == '__main__'”?
有没有一种方法可以确定当前文件是否是 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅调用者。 它在主脚本中返回
undef
。 请注意,这在子例程内部不起作用,仅在顶级代码中起作用。See caller. It returns
undef
in the main script. Note that that doesn't work inside a subroutine, only in top-level code.请参阅 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.
unless caller
很好,但更直接的并行以及更显式检查是:只是想我会把它放在那里。
编辑
请记住,
$PROGRAM_NAME
(或“$0
”)是可写的,因此这不是绝对的。 但是,在大多数实践中(除了意外或模块失控之外),这可能不会改变,或者至多改变本地在另一个范围内。unless caller
is good, but a more direct parallel, as well as a more explicit check, is: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.