5

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?

Dummy00001
  • 16,630
  • 5
  • 41
  • 63
  • I posted the answer below, but if you could elaborate on the "limitations of the execution environment", may be there are ways around those limitations that would allow you to use proper modules? Thx – DVK Aug 03 '10 at 11:02
  • @DVK: I'm really happy with your answer. (Neither my syntax of caller() check is as nice as in your response.) Regarding the limitation. Really quite silly: I can not add another non-executable module to the directory since it is scanned for the files and all file names have special meaning. Adding .pm there breaks other scripts which I'm not allowed to modify. – Dummy00001 Aug 03 '10 at 11:29
  • 1
    As per @FM, my question is essentially a dup of http://stackoverflow.com/questions/1131304/ – Dummy00001 Aug 03 '10 at 14:05

1 Answers1

10

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?

Community
  • 1
  • 1
DVK
  • 126,886
  • 32
  • 213
  • 327