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?
Yes, your
callerapproach 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):
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?