Perl: check if your file was loaded as a module or run directly

How to write a test in Perl to check if my file was run directly or imported from another source? I would like to do this to make it easier to combine everything into one file, but still write unit tests against 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 source file and call it as unit tests.

I remember how it was done before, but I don’t remember how to do it. I would like to avoid checking $ 0 for some known value, because this means that the user cannot rename the script.

+3
source share
3 answers

, Perl def.:)

, :

__PACKAGE__->main unless caller;

caller , , use require.

"" , Google.

+11

, brian d foy "modulino" recipe, script, .

" " Perl, " script " Perlmonks.

+4

See my question about testing Perl scripts. You may also be interested in starting REPL with this module:

package REPL;

use Modern::Perl;
use Moose;

sub foo {
    return "foo";
}

sub run {
    use Devel::REPL;
    my $repl = new Devel::REPL;
    $repl->load_plugin($_) for qw/History LexEnv Refresh/;
    $repl->run;
}

run if not caller;

1;

And then on the command line:

$ perl REPL.pm
$ REPL->new->foo;
bar
^D
$ perl -MREPL -E "say REPL->new->foo"
bar
+1
source

Source: https://habr.com/ru/post/1735111/


All Articles