1. Perl
  2. builtin functions
  3. here

caller function - get caller information

You can use the caller function to get the caller information.

To get the calling package name, call the caller function in scalar context.

To get the calling package name, filename, and line number, call the caller function in list context.

# package name
my $package_name = caller;

# Package name, file name, line number, subroutine name
my ($package_name, $file_name, $line) = caller;

How to get the information of the higher hierarchy?

To get the information of the higher hierarchy, give the caller function an argument indicating how many times to go up the hierarchy.

    # 0 1 2 3 4
 my ($package, $filename, $line, $subroutine, $hasargs,

    # 5 6 7 8 9 10
    $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
  = caller($i);

You can also get additional subroutine names and so on.

See official documentation for details.

Example

This is an example caller function.

use strict;
use warnings;

# Get the name of the function you are executing
# caller

print "1: Get the name of the function you are executing.\n";
func_name ();

sub func_name {
  my $this_func_name = (caller 0) [3];
  # If you specify 0 as the argument of the caller function
  # You can get information about its own function.
  # The function name is in the 4th (index is 3).
  print $this_func_name, "\n";
  print "\n";
}

print "2: Get the function name without the package name.\n";
func_name_none_package ();

sub func_name_none_package {
  my $this_func_name = (caller 0) [3];
  $this_func_name =~ s /. *:://;
  print $this_func_name, "\n\n";
}

print "3: Make function name acquisition into a subroutine.\n";
test1 ();

sub test1 {
  print get_func_name () . "\n";
}

sub get_func_name {
  # If 1 is specified as the argument of the caller function
  # You can get the information of the calling function.
  my $this_func_name = (caller 1) [3];
  $this_func_name =~ s /. *:://;
  return $this_func_name;
}

Output

1: Get the name of the function you are executing.
main::func_name

2: Get the function name without the package name.
func_name_none_package

3: Make the function name acquisition a subroutine.
test1

Related Informatrion