10.4. Determining Current Function Name10.4.1. ProblemYou want to determine the name of the currently running function. This is useful for creating error messages that don't need to be changed if you copy and paste the subroutine code. 10.4.3. DiscussionCode can always determine the current source line number via the special symbol _ _LINE_ _, the current file via _ _FILE_ _, and the current package via _ _PACKAGE_ _. But no such symbol for the current subroutine name exists, let alone the name for the subroutine that called this one. The built-in function caller handles all of these. In scalar context it returns the calling function's package name, but in list context it returns much more. You can also pass it a number indicating how many frames (nested subroutine calls) back you'd like information about: 0 is your own function, 1 is your caller, and so on. Here's the full syntax, where $i is how far back you're interested in: ($package, $filename, $line, $subr, $has_args, $wantarray # 0 1 2 3 4 5 $evaltext, $is_require, $hints, $bitmask # 6 7 8 9 )= caller($i); Here's what each of those return values means:
Rather than using caller directly as in the Solution, you might want to write functions instead: $me = whoami( ); $him = whowasi( ); sub whoami { (caller(1))[3] } sub whowasi { (caller(2))[3] } These use arguments of 1 and 2 for parent and grandparent functions because the call to whoami or whowasi would itself be frame number 0. 10.4.4. See AlsoThe wantarray and caller functions in Chapter 29 of Programming Perl and in perlfunc(1); Recipe 10.6 Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|