Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Getting code-ref of anonymous caller

by LanX (Cardinal)
on Jul 31, 2020 at 15:13 UTC ( #11120151=perlquestion: print w/replies, xml ) Need Help??

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 (Cardinal) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11120151]
Approved by marto
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2020-10-30 23:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (286 votes). Check out past polls.

    Notices?