Dem
Dem

Reputation: 53

Linux - Perl: Printing the content of the script I am executing

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

Answers (1)

mob
mob

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.

  1. 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;
    
  2. 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>;
    
  3. 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

Related Questions