Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Check to see if your file was loaded as a module or run directly

Tags:

module

perl

How do I write a test in Perl to see if my file was run directly or imported from some other source? I'd like to do this to make it easy to bundle everything in one file but still write unit tests against the functions. My idea is to have something like this:

if (running_directly()) {
  main();
}

def main {
  this();
  that();
}

def this {
  # ...
}

def that {
  # ...
}

Then in a separate perl script I can load the original file and call this & that as unit tests.

I remember seeing this done before, but I can't remember how to do it. I'd like to avoid testing $0 against some known value, because that means the user can't rename the script.

like image 551
Paul A Jungwirth Avatar asked Dec 05 '22 03:12

Paul A Jungwirth


2 Answers

First of all, Perl doesn't have a def keyword. :)

But you can check if a module is being executed directly or included elsewhere by doing this:

__PACKAGE__->main unless caller;

Since caller won't return anything if you're at the top of the call stack, but will if you're inside a use or require.

Some people have assigned the dreadful neologism "modulino" to this pattern, so use that as Google fuel.

like image 176
friedo Avatar answered Dec 28 '22 05:12

friedo


You might be thinking of brian d foy's "modulino" recipe, which allows a file to be loaded either as a standalone script or as a module.

It is also described in greater depth in his "Scripts as Modules" article for The Perl Journal as well as "How a Script Becomes a Module" on Perlmonks.

like image 37
Ether Avatar answered Dec 28 '22 06:12

Ether