How to get file name and line number in Perl?

I would like to get the current file name and line number in a Perl script. How to do it?

For example, in a file call test.pl:

my $foo = 'bar';
print 'Hello World';
print functionForFilename() . ':' . functionForLineNo();

It outputs:

Hello World
test.pl:3
+3
source share
3 answers

They are available with tokens __LINE__and __FILE__, as described in perldoc perldata in the "Special Literals" section:

The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current file name, line number, and package name at this point in your program. They can only be used 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 value undefined.

+13

caller , :

sub print_info {
   my ($package, $filename, $line) = caller;
   ...
}

print_info(); # prints info about this line

, sub, , , , . __FILE__ __LINE__ , , . ( , , , )

+7

You can use:

print __FILE__. " " . __LINE__;
+6
source

Source: https://habr.com/ru/post/1772520/


All Articles