How do I get the filename and line number in Perl?
I would like to get the current filename and line number within a Perl script. How do I do this?
For example, in a file call test.pl
:
my $foo = 'bar';
print 'Hello, World!';
print functi开发者_StackOverflow社区onForFilename() . ':' . functionForLineNo();
It would output:
Hello, World!
test.pl:3
These are available with the __LINE__
and __FILE__
tokens, as documented in perldoc perldata under "Special Literals":
The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value.
The caller
function will do what you are looking for:
sub print_info {
my ($package, $filename, $line) = caller;
...
}
print_info(); # prints info about this line
This will get the information from where the sub is called, which is probably what you are looking for. The __FILE__
and __LINE__
directives only apply to where they are written, so you can not encapsulate their effect in a subroutine. (unless you wanted a sub that only prints info about where it is defined)
You can use:
print __FILE__. " " . __LINE__;
精彩评论