Reputation: 53
Is it possible to print the whole content of the script I am executing?
Since there are many things that will go on inside the script like the calling perl modules I will call in runtime (require "/dir/file";), the print lines I am executing inside an array (foreach(@array) {print "$_\n";}).
Why do I need this? To study the script generation I am making, especially when errors are occurring. Error occurred on line 2000 (even I have only 1 thousand lines of script).
Upvotes: 2
Views: 307
Reputation: 118605
There are probably better ways to debug a script (the perl debugger, using Carp::Always
to get stack traces with any errors and warnings), but nonetheless there are at least two three mechanisms for obtaining the source code of the running script.
Since $0
contains the name of the file that perl is executing, you can read from it.
open my $fh, '<', $0;
my @this_script = <$fh>;
close $fh;
If a script has the __DATA__
or __END__
token in its source, then Perl also sets up the DATA
file handle. Initially, the DATA
file handle points to the text after
the __DATA__
or __END__
token, but it is actually opened to the whole source file, so you can seek
to the beginning of that file handle and access the entire script.
seek DATA, 0, 0;
my @this_script = <DATA>;
HT Grinnz: the token __FILE__
in any Perl source file refers to the name of the file that contains that token
open my $fh, '<', __FILE__;
my @this_file = <$fh>;
close $fh;
Upvotes: 4