Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Track the filename/line number of an anonymous coderef

by merlyn (Sage)
on Dec 10, 2004 at 00:21 UTC ( #413725=snippet: print w/ replies, xml ) Need Help??

Description: Use the imported "Sub" instead of "sub", and you can create an anonymous coderef that acts normally except when dereferenced as a string, where it returns the filename and line number of where it was defined. See the example for usage.

This code came from the discussion in the thread that includes •Re^5: How to de-reference a coderef?.

BEGIN {
  package MagicalCoderef;

  use overload '""' => sub {
    require B;

    my $ref = shift;
    my $gv = B::svref_2object($ref)->GV;
    sprintf "%s:%d", $gv->FILE, $gv->LINE;
  };

  sub main::Sub (&) {
    return bless shift, __PACKAGE__;
  }
}

my $s = Sub { print +shift };
$s->("hello world\n");
print "$s\n";
Comment on Track the filename/line number of an anonymous coderef
Download Code
Re: Track the filename/line number of an anonymous coderef
by brian_d_foy (Abbot) on Dec 11, 2004 at 06:23 UTC

    I changed this around to do it for arbitrary coderefs, since I get to deal with some that come from other sources. Instead of catching them at definition time, I "enchant" them later.

    This looks like it could be a useful decorator if I work on the concept a little more. So Randal, who wants to upload it to CPAN first?

    #!/usr/bin/perl my $a = sub { print "I am A\n" }; my $b = sub { print "I am B\n" }; $a->(); $b->(); $c = MagicalCodeRef->enchant( $a ); $a->(); print STDERR "That was $a I just called\n"; BEGIN { package MagicalCodeRef; use overload '""' => sub { require B; my $ref = shift; my $gv = B::svref_2object($ref)->GV; sprintf "%s:%d", $gv->FILE, $gv->LINE; }; sub enchant { bless $_[1], $_[0] } }
    --
    brian d foy <bdfoy@cpan.org>

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://413725]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2015-07-02 06:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (29 votes), past polls