note
BrowserUk
<p>I think that including a test script into the same file as a module (and its pod) is a good idea (I said as much in [id://231256]), and now do this regularly in my own modules. If that test code happened to be useful standalone, then it is serving two possible uses which seems like a good thing to me.
<p>A short example of doing this is a module I originally wrote to see if I could profile regexes [id://231487]. It now looks like this.
<p><code>
E:\Perl\site\lib\My>type Filter.pm
#! perl -slw
package My::Filter;
use Filter::Simple;
use Benchmark::Timer;
our $t = Benchmark::Timer->new();
FILTER_ONLY
regex => sub {
$_ = "(?{{ \$My::Filter::t->start('$_$/') }})"
. "(?:$_)"
. "(?{{ \$My::Filter::t->stop('$_$/') }})";
},
;
sub report{ return $t->report() }
return 1 if caller();
use strict;
use My::Filter;
my $stuff = 'abcdefghijklmnopqrstuvwxyz';
for (1..1000) {
if ( $stuff =~ m[pqr] ) {
$stuff =~ s/(\G(?:.{3})+?)(?<=...)(.)(.)/$1$3$2/g;
}
$_ = $stuff;
my $OK = 1 if m[pqr];
}
print $stuff;
print '=' x 20, 'Timing of regexs in ', $0, '=' x 20;
print My::Filter::report();
</code>
<p>It can be run standalone like this<code>
E:\Perl\site\lib\My>perl Filter.pm
Subroutine report redefined at E:/Perl/site/lib/My/Filter.pm line 16.
abcdefghijklmnopqrstuvwxyz
====================Timing of regexs in Filter.pm====================
2000 trials of pqr
(260.000ms total), 130us/trial
5000 trials of (\G(?:.{3})+?)(?<=...)(.)(.)
(640.000ms total), 128us/trial
</code>
<p>Or used from a script like this.<code>
C:\test>perl -MMy::Filter -e"$s='abc'; print 'ok' if $s =~ m[b]; print My::Filter::report();"
ok1 trial of b
(0s total)
C:\test>
</code>
<p>The only downside is having to switch to the directory where the module lives or specify the full path to in order to invoke it standalone, but there are several ways around that.
<hr>
<font size=1>
<div>Examine what is said, not who speaks.</div>
<div align="right">
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. <br />
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible<br />
3) Any sufficiently advanced technology is indistinguishable from magic.<br />
Arthur C. Clarke.
</div></font>
244162
244162