Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

The question is: how can a subroutine find out the name of it's caller? (I'm not looking for the solution when the caller sub puts it's name in an argument)

To clarify my question, suppose there we have theses subs:

sub LOG; sub do_this { ....; ....; LOG "a message"; } sub do_that { ....; ....; LOG "another message..."; }
How should the LOG sub look like when I want to see this output:
LOG: sub "do_this" says: "a message" LOG: sub "do_that" says: "another message..."
Thanks for your trouble.

Replies are listed 'Best First'.
Re: how can a subroutine find out the name of it's caller?
by Mutant (Priest) on Feb 18, 2005 at 12:32 UTC
    Have a look at the caller function:

    perldoc -f caller

    Also, for logging purposes, the core Carp module has some useful functions to print out call stacks, etc.
Re: how can a subroutine find out the name of it's caller?
by jbrugger (Parson) on Feb 18, 2005 at 13:03 UTC
    To clarifie, the caller gets the contect of the CURRENT subroutine call, hence
    #!/usr/bin/perl -w use strict; sub jojo { my ($package, $filename, $line, $subroutine, $hasargs, $wantar +ray, $evaltext, $is_require) = caller(1); print "2: " . $subroutine . "\n"; } sub jo { my ($package, $filename, $line, $subroutine, $hasargs, $wantar +ray, $evaltext, $is_require) = caller(1); print "1: " . $subroutine . "\n"; jojo; } jo;
    would print:
    Use of uninitialized value in concatenation (.) or string at ./test.pl line 11.
    1:
    2: main::jo
    As you see, the first call doesn't show a caller, since there is no sub that clalled it, only the package would be known, and you should give the depth of info, thus the following should work
    #!/usr/bin/perl -w use strict; sub jojo { my ($package, $filename, $line, $subroutine, $hasargs, $wantar +ray, $evaltext, $is_require) = caller(1); print "2: $package - $subroutine \n"; } sub jo { my ($package, $filename, $line, $subroutine, $hasargs, $wantar +ray, $evaltext, $is_require) = caller(); print "1: $package - $subroutine \n"; jojo; } jo;

    That prints:
    1: main -
    2: main - main::jo
Re: how can a subroutine find out the name of it's caller?
by friedo (Prior) on Feb 18, 2005 at 13:04 UTC
    The caller function returns all sorts of useful stuff, and you can use it to trace all the way back up the function stack. To go back one stack frame, you can use:

    sub LOG { my $msg = shift; my @cl = caller(1); print "sub ", $cl[3], " says: ", $msg; }
Re: how can a subroutine find out the name of it's caller?
by perlsen (Chaplain) on Feb 18, 2005 at 13:33 UTC

    Hi, did u seen the Carp::Trace module

    Carp::Trace - provides simple traceback of call stacks.

    Carp::Trace provides an easy way to see the route your script took to get to a certain place.
    It uses simple caller calls to determine this.

    Thanks