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.
First of all, Perl doesn’t have a
defkeyword. 🙂But you can check if a module is being executed directly or included elsewhere by doing this:
Since
callerwon’t return anything if you’re at the top of the call stack, but will if you’re inside auseorrequire.Some people have assigned the dreadful neologism “modulino” to this pattern, so use that as Google fuel.