Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the file and line number where a Perl subroutine reference was created?

Tags:

perl

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.

like image 237
Ovid Avatar asked Feb 02 '09 16:02

Ovid


People also ask

How to define subroutine in Perl?

One can avoid using the return statement. Defining Subroutines: The general form of defining the subroutine in Perl is as follows- sub subroutine_name { # body of method or subroutine } Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as follows-

How to Pass parameter in Perl subroutine?

You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

How do you perform a forward declaration of a subroutine performed in Perl?

To declare a subroutine, use one of these forms: sub NAME ; # A "forward" declaration. sub NAME ( PROTO ); # Ditto, but with prototype.

How to insert a line in a file in Perl?

To insert a line after one already in the file, use the -n switch. It's just like -p except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add. To delete lines, only print the ones that you want.


1 Answers

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.

like image 61
dsm Avatar answered Dec 11 '22 07:12

dsm