Let's assume you have a recent Perl and CPANPLUS installed. You want your brand new script to automatically install any modules that are not found. Well, maybe you don't. I'm sure I don't, but I couldn't resist the temptation and made Blah.pm. The module name describes exactly what it does, or... no it doesn't... but I needed a name.
My first try had a $SIG{__DIE__} handler and die "Try again :)\n", but it still didn't look nice. I did this because you cannot resurrect scripts. Kane had the idea of using exec($^X, $0, @ARGV) instead, which worked perfectly. But then, lathos suggested using a code ref in @INC. With the help of this node, I created this:
Blah.pm
use strict;
use CPANPLUS;
push @INC, sub {
my ($code, $file) = @_;
my $module = $file;
$module =~ s!/!::!g;
$module =~ s!\.pm$!!g;
install($module);
for (@INC) {
next if ref;
if (-e "$_/$file" and -r _) {
open my $fh, '<', "$_/$file" or die $!;
return $fh;
}
}
return undef;
};
Please note that real programmers don't use CPANPLUS but CPANPLUS::Backend, and use the great backend. I was lazy and used CPANPLUS with the simple install() function, but that is bad.
Example script:
use Blah;
use Acme::Time::Baby;
print babytime(), "\n";
Example output:
3;0 root@ouranos:/home/juerd/modtest# perl test.pl
Checking if your kit is complete...
Looks good
Writing Makefile for Acme::Time::Baby
PERL_DL_NONLAZY=1 /usr/bin/perl -Iblib/arch -Iblib/lib -I/usr/lib/perl
+/5.6.1 -I/
usr/share/perl/5.6.1 -e 'use Test::Harness qw(&runtests $verbose); $ve
+rbose=(eva
l(chr(36).q(|=1))-1); runtests @ARGV;' t/*.t
t/00_en..........ok
t/01_du..........ok
t/02_custom......ok
t/03_noimport....ok
t/04_chef........ok
t/05_warez.......ok
t/06_de..........ok
t/07_fr..........ok
t/08_no..........ok
t/09_it..........ok
All tests successful.
Files=10, Tests=12972, 6 wallclock secs ( 2.33 cusr + 0.17 csys = 2
+.50 CPU)
Installing of Acme::Time::Baby succesfull
The big hand is on the eight and the little hand is on the ten
3;0 root@ouranos:/home/juerd/modtest# perl test.pl
The big hand is on the nine and the little hand is on the ten
- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.