Hi all,
Agile programming question...
I frequently find myself in need of (or thinking I'm in need of) a new
support package/class while developing a script/module. Often, a
block-scoped package declaration will do the trick, but what if the
architecture you're building toward needs to have some backend-require
semantics? (Familiar examples: LWP::Protocol + [LWP::Protocol::http,
L::P::*], or URI::file::* -- runtime selection and require().)
So, the basic need is to set $INC{$filename} so that use() and require()
will work (given BEGIN{}s and proper ordering) without loading from a
file. The reason to not load from a file is essentially temporary, the
point being that I might change my mind about the naming (and/or actual
need for it) and would rather not interrupt my train of thought to
ponder a name, create a file, and add it to version control. If you're
not an organic coder, or just could care less about naming, maybe this
doesn't bother you -- but I'm me (and I'm guessing that some others may
or would use this technique.)
I've noticed that a subref passed to a use statement essentially plays
the same role as a BEGIN block, so I've come up with:
use Package::Unicorn sub {
package BlahBlahBlah;
sub thing {foo->stuff()};
__PACKAGE__;
};
So, everything inside the subref is in package BlahBlahBlah and the
return value (which is true) is the name of that package. The import()
of Package::Unicorn then does 'my $p = $sub->();' and twiddles %INC
accordingly following some s/ on $p. If BlahBlahBlah does indeed need
to be its own .pm file, all the parts are already in place as soon as
you're ready to commit to the name.
I've tried to come up with something that doesn't need the trailing
__PACKAGE__ or require typing BlahBlahBlah twice, but can't think of
anything that doesn't involve DB or B::*. If anyone has a suggestion,
it would easily be the hack of the week, and may require a second
edition of chromatic's book. (Provided it doesn't involve caller() and
open() :-D)
While I could certainly just use BEGIN {...; $INC{"BlahBlahBlah.pm" =
__FILE__;}, I find that to be a bit less elegant, and less than
self-documenting. The neat side-effect of using a module for this is
that it could also be self-reporting (even if only in a dependency scan
reminding you that you intended to finalize that bit before a release.)
Yes, this is a hack and yes that package is a closure. I'm not going to
encourage (ab)using this in production code, just as a development aid.
Such things do tend to get shipped under duress, but that's why I'm
trying to avoid B/DB related hackery.
Thoughts? Usefullness? Better name than Package::Unicorn or
Acme::RealSoonNow?
Thanks,
Eric
--
perl -e 'srand; print join(" ",sort({rand() < 0.5}
qw(sometimes it is important to be consistent)));'
---------------------------------------------------
http://scratchcomputing.com
---------------------------------------------------