tags:

views:

83

answers:

1

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?

+8  A: 

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

http://stackoverflow.com/questions/1839825/what-should-i-put-in-my-starter-template-for-my-perl-programs/1841356#1841356

DVK
+1 A related question: http://stackoverflow.com/questions/1215657.
FM
Tom Christiansen (I think) coined the term progmod for this many years before "modulino"
ysth
I didn't invent the technique. Tom C. was the first person I saw doing it. I just popularized it.
brian d foy