http://www.perlmonks.org?node_id=852776


in reply to SOLVED: How to load the subs without running the script

perl -c manages because the Perl interpreter itself is getting control before execution starts at all and then just exiting.

You can use the debugger hooks to do this if you don't want any of the code in monster.pl to execute at all.

If you create a sub called DB::DB, Perl will enter it just as soon as the code has compiled but before the first statement executes. You can then do what you like with the subs back in main:: (the namespace of the monster.pl script, assuming it doesn't have internal packages).

Try something like this: in a new file, Devel::Stop:

package Devel::Stop; use strict; use warnings; sub DB::DB { # Execute the code you want to run here my $result = main::foo(); print STDERR "1..2\n"; print STDERR ((defined $result ? "ok 1" : "not ok 1")," - got a valu +e\n"); print STDERR (($result eq "I am foo" ? "ok 2" : "not ok 2"), " - rig +ht value\n"); exit(0); } 1;
and you'll get
joe-desk-> perl -d:Stop xxx 1..2 ok 1 - got a value ok 2 - right value
DB::DB gets called as soon as the code is loaded and compiled (including use statements in the main program). Since it calls exit before it returns, control never returns to the program being "debugged".

Run this like this:

perl -d:Stop monster.pl
Exercise for the reader to make the mechanism more flexible so you don't have to write a new package for every test, though a new package for every test is better than no tests at all...

Note that Test::Simple won't work here: it runs stuff in BEGIN and END blocks, and confuses this ultra-simple debugger. I'd recommend either writing your own little library to handle the ok, like, etc. functions, or beefing up the logic in DB::DB to allow the Test:: code to run but not anything in main::.

This is meant to demonstrate a direction you can go rather than be a complete solution; there's a lot of potential here, accompanying a lot of potential "why did THAT happen?" situations.