So you have a program that contains routines which should really be in a library. You want to run those routines separately to test them. You don't want to run the program, of course. Or, worse, you want to run those routines for actual production use (you should be shot) without running the program.
I found out how to do this in the middle of the night a couple of weeks ago, from a presentation somebody linked to from here. Jotted down some notes, and now I'm putting it here so I can find it later.
require($program);
import qw(routine routine routine);
Or, for testing:
require_ok($program);
import qw(routine routine routine)
ok(routine(1, 2));
This just gets at what the use keyword does, internally.
Update: Okay, this is apparently wrong.
Which means somebody's slides were way off.
self-import-ant? (Score:2)
Except that it does not work... (Score:1)
Let's say you have this prog.pl:
and this test.pl:
Now, running test.pl produces:
because the require will execute the program. So, if the program dies because @ARGV is wrong, or somesuch, your test dies as well...
What you should do is change the program (Score:2)
Thus, do this at the top level: It'll work now.
Re: (Score:2)
Thank you. Sounds like this advice was either present in the slides I read, and I missed it (it was middle of the night, up late hacking for work :) ), or else the presenter missed it or only mentioned it orally without including it in the slides.
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers
It's a Method! (Score:1)
Besides your update,
import()is a method. When you call methods as functions in Perl, you don't always get what you want.I think you'll have more luck checking
caller()to see if someone has invoked your program directly.Perhaps you heard about modulinos (Score:2)
int main(void)). Now a program is just a set of subroutines and you can use it like every other library of subroutines (including testing it).I write about it in Chapter 18 of Mastering Perl [pair.com]
Here's how I did it (Score:1)
Hopefully it wasn't my slides [redhotpenguin.com] that were way off ;-) Here's how I poked at the internals of a program, including global variables. I got the idea from another post here on use Perl, and I hacked out this working program and test.
Re: (Score:1)
Oops, I forgot the output