<?xml version="1.0" encoding="windows-1252"?>
<node id="992211" title="Re: Let a module call a sub of the caller" created="2012-09-06 19:57:06" updated="2012-09-06 19:57:06">
<type id="11">
note</type>
<author id="381608">
ikegami</author>
<data>
<field name="doctext">
&lt;p&gt;The same mechanisms pragmas use to clean themselves up can be used here. Here's an example:

&lt;p&gt;&lt;c&gt;call_when_scope_is_compiled.pm&lt;/c&gt;:

&lt;c&gt;
package call_when_scope_is_compiled;

use Sub::ScopeFinalizer qw( scope_finalizer );

sub import {
   my ($class, $sub) = @_;
   $^H{__PACKAGE__ . '::'} =
      scope_finalizer { $sub-&gt;() };
}

1;
&lt;/c&gt;

&lt;c&gt;
$ perl -E'
   say "post";
   use call_when_scope_is_compiled \&amp;foo;
   sub foo { say "foo!" }
   BEGIN { say "pre"; }
'
pre
foo!
post
&lt;/c&gt;

&lt;p&gt;It also works for narrower scopes.

&lt;c&gt;
$ perl -E'
   {
      use call_when_scope_is_compiled \&amp;foo;
      sub foo { say "foo!" }
      BEGIN { say "pre"; }
   }
   BEGIN { say "post"; }
'
pre
foo!
post
&lt;/c&gt;

</field>
<field name="root_node">
992164</field>
<field name="parent_node">
992164</field>
</data>
</node>
