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


in reply to Package level scope callbacks.

If what you want is to have a sub called when a sub of a package is called maybe this code can be useful for you:
############ # SPY_SUBS # ############ sub spy_subs { my ( $pack , $callback ) = @_ ; $pack =~ s/::$// ; my $stash = *{"$pack\::"}{HASH} ; foreach my $Key ( keys %$stash ) { my $sub = "$pack\::$Key" ; if ( defined &$sub ) { my $org_sub = \&$sub ; *{$sub} = sub { &$callback(@_) ; &$org_sub(@_) ;} ; } } } ############### # PACKAGE FOO # ############### package foo ; sub call { print "call>> @_\n" ; } sub foo { print "foo>> @_\n" ; } main::spy_subs('foo',\&call) ; foo(123);
Output:
call>> 123 foo>> 123
But note that this will interfere with caller(), since you have an extra sub for each call. With some extra code this can be fixed, but for now is just that.

Graciliano M. P.
"Creativity is the expression of the liberty".

Replies are listed 'Best First'.
Re^2: Package level scope callbacks.
by tilly (Archbishop) on Aug 02, 2004 at 03:48 UTC
    You can fix the caller issue by calling the original subroutine with goto &$org_sub;