我想在Perl脚本中获取当前文件名和行号.我该怎么做呢?
例如,在文件调用中test.pl:
my $foo = 'bar';
print 'Hello World';
print functionForFilename() . ':' . functionForLineNo();
Run Code Online (Sandbox Code Playgroud)
它会输出:
Hello World
test.pl:3
Run Code Online (Sandbox Code Playgroud)
Eth*_*her 13
这些可用于__LINE__和__FILE__令牌,如perldoc perldata在"Special Literals "中所述:
特殊文字__FILE __,_ _ _ _ _ _ _和_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 它们只能用作单独的代币; 它们不会插入字符串中.如果没有当前包(由于包空;指令),__PACKAGE__是未定义的值.
该caller功能将满足您的需求:
sub print_info {
my ($package, $filename, $line) = caller;
...
}
print_info(); # prints info about this line
Run Code Online (Sandbox Code Playgroud)
这将从调用sub的位置获取信息,这可能就是您要查找的内容.在__FILE__和__LINE__指令只适用于它们被写入其中,所以你不能封装他们的子程序的效果.(除非你想要一个只打印有关它定义位置信息的子)