Assuming a relatively recent version of perl (5.7.1+ IIRC) you can execute
INIT at your discretion. However the trick is in avoiding executing them twice. Here's a very bare bones example of executing
INIT blocks from both
use and
require
package testpkg;
BEGIN { warn "in BEGIN\n" }
{
no warnings;
INIT {
return if $INIT_DONE++;
warn "in INIT\n";
}
}
{
use B;
$_->object_2svref->() for grep {
$_->GV->STASH->NAME eq __PACKAGE__
} B::init_av->ARRAY;
}
1;
And some usage code
$ perl -we 'use testpkg;'
in BEGIN
in INIT
$ perl -we 'require testpkg;'
in BEGIN
in INIT
Unfortunately it uses a rather horrific bodge of a package variable and post-increment behaviour, but nonetheless, it works :) Hopefully there's some very straight-forward solution for determining what state perl is in when a piece of code is executing, but currently I'm out of ideas.