note
ikegami
<p>The same mechanisms pragmas use to clean themselves up can be used here. Here's an example:
<p><c>call_when_scope_is_compiled.pm</c>:
<c>
package call_when_scope_is_compiled;
use Sub::ScopeFinalizer qw( scope_finalizer );
sub import {
my ($class, $sub) = @_;
$^H{__PACKAGE__ . '::'} =
scope_finalizer { $sub->() };
}
1;
</c>
<c>
$ perl -E'
say "post";
use call_when_scope_is_compiled \&foo;
sub foo { say "foo!" }
BEGIN { say "pre"; }
'
pre
foo!
post
</c>
<p>It also works for narrower scopes.
<c>
$ perl -E'
{
use call_when_scope_is_compiled \&foo;
sub foo { say "foo!" }
BEGIN { say "pre"; }
}
BEGIN { say "post"; }
'
pre
foo!
post
</c>
992164
992164