Michael G Schwern wrote:
Now, nobody says this means your program has to be split up into a whole
bunch of files and become a full fledged module. You can write something
like this.
#!/usr/bin/perl -w
use Getopt::Long;
my %Opts;
GetOptions(\%Opts, "test");
sub main {
return if $Opts{test};
...the program using the functions below...
}
main();
sub some_function { ... }
sub some_other_function { ... }
And then when you want to test the internal functions you can do this:
local @ARGV = qw(--test);
require "bin/myprogram";
is( some_function(), 'happy' );
And when you want to test the external functionality you can do this:
is( `bin/myprogram some args`, 'wibble' );
Great stuff.
Or if you want to be super portable you can do this:
use Test::Output;
local @ARGV = qw(some args);
stdout_is( sub { do "bin/myprogram" }, 'wibble' );
Which has the nice side benefit of making sure your code initialzes itself
properly between each run rather than just assuming its in a fresh process
each time.
I always assume I'm in a fresh process when writing scripts. :)
BTW-Never knew about that use of the 'do' command (just read perldoc -f
do after seeing that). I remember several times I could have used that
in the past.
[1] And often reusability is not so much planned but discovered. And its
much easier to discover reusability when things are already well encapsulated
than to attempt to see it in a large wad of code.
I will try incorporate this into my future projects!
-ofer