How can I run my Perl script only if it wasn't loaded with require?

浪子不回头ぞ 提交于 2019-12-11 01:19:50

问题


I have a Perl script. If it was called direct from the command line, I want to run sub main.

If it was called using require, I want to do nothing and wait for the caller script to call sub job at it's leisure.


回答1:


There's a recommended Perl solution for code which needs to be runnable from a script as well as a perl module.

It's usually called "modulino", which can be used as Google or SO search term to find how-tos.

Here's one how-to with reference links:

Perl script usable as a program and as a module




回答2:


It sounds as if you should be splitting your script into a module and a front-end program. Then programs which want to use the functionality can load the module using use (or require, if you insist) and the stub program can do that and the call the job subroutine as well.




回答3:


You could so something like this:

#!/usr/bin/env perl
package Some::Module;

sub job { ... }

sub main { ... } 

if (!caller) {
     main(@ARGV);
}

1;
__END__

=head1 NAME

Some::Module - program, podpage, and module

....

That can now simultaneously be all of:

  1. an executable script to be called from the command line as a program (which will call its main() function)

  2. a module to use from elsewhere in which case it just loads function definitions

  3. a podpage you can run pod2text on

Is that what you were looking for?



来源:https://stackoverflow.com/questions/4004466/how-can-i-run-my-perl-script-only-if-it-wasnt-loaded-with-require

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!