Perl脚本可用作程序和模块 [英] Perl script usable as a program and as a module
问题描述
我有一个Perl脚本(独立程序),其中包含一些我想在其他脚本中重用的子程序.由于执行环境的限制,我无法将功能移动到常见的 .pm
文件中.
是否可以区分脚本是作为独立程序运行还是由其他脚本进行 require
required/ do
?
我唯一能找到的就是在顶层使用 caller
:当 require
ed caller 时,独立程序没有任何调用者代码>显示谁加载了模块.有更好的解决方案吗?
是的,您的主叫方
方法是正确的-这是精通Perl"一书中的程序即模块"一章布莱恩·弗伊
I have a Perl script (standalone program) which contains some subs I'd like to reuse in other scripts. Due to limitations of the execution environment, I can't move the functions to a common .pm
file.
Is it possible to differentiate whether the script was run as a standalone program or it was require
ed/do
ed by another script?
The only thing I could find was to use caller
at the top level: standalone program doesn't have any caller while when require
ed caller
shows who did load the module. Is there any better solution?
Yes, your caller
approach was correct - this is a technique named "modulinos" by brian d foy. I am guessing that brian invented it unless someone enlightens me to the contrary.
The main working part of modulino looks like this (from SO answer linked below):
__PACKAGE__->run( @ARGV ) unless caller;
sub run {
my( $class, @args ) = @_;
}
1;
Here are a couple of references:
"Modules as Programs" chapter from "Mastering Perl" book by brian d foy
"Scripts as Modules" article in Dr. Dobbs
"How a script becomes a module" article on perlmonks
What should I put in my starter template for my Perl programs?
这篇关于Perl脚本可用作程序和模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!