Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl script usable as a program and as a module

Tags:

linux

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?

like image 465
Dummy00001 Avatar asked Aug 03 '10 10:08

Dummy00001


People also ask

What is the use of Perl modules?

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).

Which function in Perl allows you to include a module file or a module?

A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );

How many Perl modules are there?

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.


1 Answers

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?

like image 111
DVK Avatar answered Sep 30 '22 13:09

DVK