現在のサブルーチン呼び出しのコンテキストを取得するcaller関数を使うと、パッケージ名や関数名などを取得できる。
以下、簡単なコードピース
#!/usr/bin/perl use strict; use warnings; { package Sample; sub whoami { # my ($package, $filename, $line) = caller; my ($package, $filename, $line, $subroutine, $hasargs, $wantarray, $evaltext, $is_require, $hints, $bitmask) = caller(0); print "package = [${package}]\n" if defined($package); print "filename = [${filename}]\n" if defined($filename); print "line = [${line}]\n" if defined($line); print "subroutine = [${subroutine}]\n" if defined($subroutine); print "hasargs = [${hasargs}]\n" if defined($hasargs); print "wantarray = [${wantarray}]\n" if defined($wantarray); print "evaltext = [${evaltext}]\n" if defined($evaltext); print "is_require = [${is_require}]\n" if defined($is_require); print "hints = [${hints}]\n" if defined($hints); print "bitmask = [${bitmask}]\n" if defined($bitmask); print '__FILE__ = [', __FILE__, "]\n"; print '__PACKAGE__ = [', __PACKAGE__, "]\n"; } } Sample::whoami; print "\n--------------------------\n"; my ($package, $filename, $line) = caller; print "package = [${package}]\n" if defined($package); print "filename = [${filename}]\n" if defined($filename); print "line = [${line}]\n" if defined($line); print '__FILE__ = [', __FILE__, "]\n"; print '__PACKAGE__ = [', __PACKAGE__, "]\n";
実行例
C:\in_vitro\perl\basic>perl caller01.pl package = [main] filename = [caller01.pl] line = [29] subroutine = [Sample::whoami] hasargs = [1] hints = [2] bitmask = [UUUUUUUUUUUU] __FILE__ = [caller01.pl] __PACKAGE__ = [Sample] -------------------------- __FILE__ = [caller01.pl] __PACKAGE__ = [main]
コメント