How can I run my Perl script only if it wasn't

2019-07-21 09:24发布

问题:

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?



标签: perl require