terdon terdon -4 years ago 111
Perl Question

How can a Perl subroutine report the line that called it?

I am writing a Perl pipeline, a script that calls various other programs and manages passing data from one to the other. The script (call it

) and the various sub-scripts it manages all share a list of common subroutines defined in
and included via a
require subroutines.ph

One of these is a function whose job is to exit printing an error message (the actual subroutine also does some other jobs, but they're not relevant here; no, I am not reinventing

## subroutines.ph
sub errorDie
my ($errMsg) = @_;
## various other cleanup tasks here

And, in

require 'subroutines.ph';


Running the script above results in:

foo at subroutines.ph line 5.

Is it possible to have it instead report something like:

foo at pipelines.pl line 4.

So, instead of reporting the line the
was found on, it should report the line of the original script where the
subroutine was called from. I know I can do this by including the line in the
variable, but that is fragile and cumbersome. Can this be done automatically? Can a subroutine defined in an external file detect where it was called from?

Answer Source

There is caller , to do this: https://perldoc.perl.org/functions/caller.html

my ($package, $filename, $line) = caller;

gives you the information you need.

However, as you are talking about debugging generally, you can get a complete backtrace from carp, as mentioned already.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download