http://www.perlmonks.org?node_id=992211


in reply to Let a module call a sub of the caller

The same mechanisms pragmas use to clean themselves up can be used here. Here's an example:

call_when_scope_is_compiled.pm:

package call_when_scope_is_compiled; use Sub::ScopeFinalizer qw( scope_finalizer ); sub import { my ($class, $sub) = @_; $^H{__PACKAGE__ . '::'} = scope_finalizer { $sub->() }; } 1;
$ perl -E' say "post"; use call_when_scope_is_compiled \&foo; sub foo { say "foo!" } BEGIN { say "pre"; } ' pre foo! post

It also works for narrower scopes.

$ perl -E' { use call_when_scope_is_compiled \&foo; sub foo { say "foo!" } BEGIN { say "pre"; } } BEGIN { say "post"; } ' pre foo! post