http://qs321.pair.com?node_id=11120151

LanX has asked for the wisdom of the Perl Monks concerning the following question:

As the following demo shows is caller(1) reporting the name of the calling sub + package.

In the case of a named subroutine one is able to get the code-ref of the caller by inspecting the STASH.

But this doesn't work with anonymous subs.

Caller claims they are part of the stash (here main::__ANON__ ) but accessing the associated code-ref fails. It most likely a newly autovivificated code-ref.

Any better way to get the callers code-ref?

First the output

CURRENT SUB: CODE(0x24c9198) main::upper CODE(0x24c9198) CURRENT SUB: CODE(0x24e8568) main::__ANON__ CODE(0x24c0580) # <--- OOPS

Here the demo:

use strict; use warnings; use Data::Dump qw/pp dd/; use feature "current_sub","say"; sub lower { my %caller; package DB { @caller{ qw/ package filename line subroutine hasarg +s wantarray evaltext is_require hints bitmas +k hinthash / } = caller(1); }; my $caller_name = $caller{subroutine}; my $caller_ref =\&{$caller_name};; say $caller_name," ",$caller_ref; } # --- normal sub upper { say "CURRENT SUB: ",__SUB__; lower( "UPPER" ); } upper(); # --- ano sub my $ano = sub { say "CURRENT SUB: ",__SUB__; lower("ANNO"); }; $ano->();

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re: Getting code-ref of anonymous caller
by LanX (Saint) on Jul 31, 2020 at 15:49 UTC
    Well there is at least an XS module to do the job

    see Devel::Caller

    caller_cv($level) caller_cv gives you the coderef of the subroutine being invoked at + the call frame indicated by the value of $level

    Tested and working!

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery