是否有一个Perl等同于Python的`if __name__ =='__main __'`? [英] Is there a Perl equivalent to Python's `if __name__ == '__main__'`?

查看:83
本文介绍了是否有一个Perl等同于Python的`if __name__ =='__main __'`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以确定当前文件是否是在Perl源代码中执行的文件?在Python中,我们使用以下结构进行此操作:

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

我可以使用FindBin__FILE__一起破解某些东西,但我希望有一种规范的方法.谢谢!

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

推荐答案

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

请参见主叫方.它在主脚本中返回undef.请注意,这仅在顶级代码中无法在子例程内起作用.

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

这篇关于是否有一个Perl等同于Python的`if __name__ =='__main __'`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆