在 Perl 中,如何确定我的文件是否被用作模块或作为脚本运行?
假设我有一个 Perl 文件,其中的某些部分仅在作为脚本调用时才需要运行。 我记得之前读过有关将这些部分包含在 main() 方法中并执行 a
main() unless(<some condition which tests if I'm being used as a module>);
但我忘记了条件是什么。 谷歌搜索并没有取得任何成果。 有人可以指出寻找此内容的正确位置吗?
Let's say I have a Perl file in which there are parts I need to run only when I'm called as a script. I remember reading sometime back about including those parts in a main() method and doing a
main() unless(<some condition which tests if I'm being used as a module>);
But I forgot what the condition was. Searching Google hasn't turned out anything fruitful. Can someone point out the right place to look for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果该文件作为脚本调用,则不会有 调用者,因此您可以使用:
请参阅 brian d foy 的 说明。
输出:
使用另一个脚本:
输出:
If the file is invoked as a script, there will be no caller so you can use:
See brian d foy's explanation.
Output:
Using from another script:
Output:
我最初在我的脚本作为模块文章中将这些东西称为“modulinos” Perl Journal(现在的Dobbs 博士)。 谷歌这个词,你会得到正确的资源。 Sinan 已经链接到我的一本书中的开发资源,我在其中谈到了它。 您可能还喜欢脚本如何成为模块。
I call these things "modulinos" originally in my Scripts as Modules article for The Perl Journal (now Dr. Dobbs). Google that term and you get the right resources. Sinan already linked to my development sources for one of my books where I talk about it. You might also like How a Script Becomes a Module.
最好不要这样做,而是采用结构化方法,例如 MooseX::Runnable 。
您的类将如下所示:
现在您有一个可以在程序中轻松使用的类:
在比上面的“run”方法更大的交互式脚本中:
如果您只想独立执行此操作,您可以说:
注意您编写的代码有多少,以及生成的类有多灵活。 “main if !caller”很好,但是当你可以做得更好时为什么还要麻烦呢?
(顺便说一句,MX::Runnable 有插件;因此您可以轻松增加看到的调试输出量、在代码更改时重新启动应用程序、使应用程序持久化、在分析器中运行它等)
Better to not do this, and instead take a structured approach like MooseX::Runnable.
Your class will look like:
Now you have a class that can be used inside your program easily:
Inside an interactive script that is bigger than just the "run" method above:
If you just want to do this standalone, you can say:
Notice how little code you wrote, and how flexible the resulting class is. "main if !caller" is nice, but why bother when you can do better?
(BTW, MX::Runnable has plugins; so you can easily increase the amount of debugging output you see, restart your app when the code changes, make the app persistent, run it in the profiler, etc.)