tags:

views:

321

answers:

2

Given a subroutine reference, is there a way to find out the file and line number where the subroutine was declared? warn and friends seems to get this right, but I need this externally. Here's my test program:

#!/usr/bin/perl -l

use strict;
use warnings;
use B;

# line 99 'bin/some_code.pl'
{
    no strict 'refs';
    print B::svref_2object(\*{'Foo::some_sub'})->LINE;
    print B::svref_2object(\&Foo::some_sub)->GV->LINE;
}
Foo::some_sub();

package Foo;
# line 23 'bin/some_file.pl'
sub some_sub {
    warn "Got to here";
}

That outputs:

102
102
Got to here at 'bin/some_file.pl' line 24.

The line information is not what I'm expecting, so I assume I'm doing something wrong (B::GV has a corresponding FILE method, but until I get LINE working, it's not much use to me).

Is there some other way to get this information and am I doing something wrong in the above code?

Update: As it turns out, the 'FILE' and 'LINE' methods seem to work OK if I'm not using line directives. Looks like it may be a bug in the B::GV module.

+4  A: 

You could try looking at caller. This is what the debugger uses to build stack traces, so maybe it is what you want.

I don't think __LINE__, __FILE__ and __PACKAGE__ help you here as they only provide the location of the current point of execution, meaning that given a code reference or sub as in your code you will get the same results.

dsm
+1  A: 

You're already doing some of this, but also see the Perlmonks thread "Track the filename/line number of an anonymous coderef".

brian d foy