Perl脚本可用作程序和模块 [英] Perl script usable as a program and as a module

查看:55
本文介绍了Perl脚本可用作程序和模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl脚本(独立程序),其中包含一些我想在其他脚本中重用的子程序.由于执行环境的限制,我无法将功能移动到常见的 .pm 文件中.

是否可以区分脚本是作为独立程序运行还是由其他脚本进行 require required/ do ?

我唯一能找到的就是在顶层使用 caller :当 require ed caller 时,独立程序没有任何调用者代码>显示谁加载了模块.有更好的解决方案吗?

解决方案

是的,您的主叫方方法是正确的-这是精通Perl"一书中的程序即模块"一章布莱恩·弗伊

Dobbs博士中的脚本作为模块"

关于Perlmonks的文章脚本如何成为模块"

什么我应该为我的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 requireed/doed 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 requireed 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屋!

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