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?
A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN).
A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );
Perl modules are a set of related functions in a library file. They are specifically designed to be reusable by other modules or programs. There are 108,000 modules ready for you to use on the Comprehensive Perl Archive Network.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With