Perl - How to Find Out Who You Are and Who Your Caller Is

How to find out the name of the current method, and the name of your parent.

Note: It should be noted that this is not a UW-Madison Help Desk or DoIT Middleware supported procedure, and, naturally, we can't take responsibility for any damage you do while following or attempting to follow these procedures. Be sure you understand what you are doing.

The caller function provides access to the call stack in Perl. In a list context, it returns your package information:

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

Which is not very useful. Luckily, if you give it a parameter (the stack frame number in question), it returns:

(   $package,   $filename, $line,       $subroutine, $hasargs,
    $wantarray, $evaltext, $is_require, $hints,      $bitmask
    = caller($i);

So, you can use it to find out who you are, or who your parent is (I'll leave finding your grandparent as an exercise to the reader):

# Me

$me = ( caller(0) )[3];

# Parent

$parent = ( caller(1) )[3];

Rather than using caller() directly, you probably want to create functions:

sub whoami  { ( caller(1) )[3] }
sub whowasi { ( caller(2) )[3] }

A full example program:

# ignore warnings about undefs.  DON'T DO THIS IN REAL CODE
no warnings;

sub whoami  { ( caller(1) )[3] }
sub whowasi { ( caller(2) )[3] }

sub me {
    print "me: hello\n";

    # Note that whowasi() returns undef here
    printf "I Am: %s.  I was: %s\n", whoami(), whowasi();

    print "me: goodbye\n";

sub them {
    print "them: hello\n";

    printf "I Am: %s.  I was: %s\n", whoami(), whowasi();


    print "them: goodbye\n";

print "main: hello\n";

# Note that whoami() and whowasi() return undef here
printf "I Am: %s.  I was: %s\n", whoami(), whowasi();


print "main: goodbye\n";

Which Produces:

$ perl ./
main: hello
I Am: .  I was: 
them: hello
I Am: main::them.  I was: 
me: hello
I Am: main::me.  I was: main::them
me: goodbye
them: goodbye
main: goodbye

Keywords:perl who am function name caller   Doc ID:4309
Owner:Naomi S.Group:Identity and Access Management
Created:2006-01-03 19:00 CDTUpdated:2020-04-09 08:57 CDT
Sites:Identity and Access Management, Middleware
Feedback:  68   18