paperlined.org
dev > perl
document updated 2 months ago, on Aug 26, 2024

How to locate where a subroutine/variable is defined?

First, generate a list of all Perl code files that get 'use'd while your script runs. Add this code anywhere in your Perl script:

END {
    # record a list of all Perl code files that were used while this script was running
    use Cwd 'abs_path';
    my $logfile = abs_path($0);
    $logfile =~ s#/#_#g;
    $logfile = "/tmp/Perl_files$logfile." . getpwuid( $< ) . ".txt";
    if (open my $f, '>', $logfile) {
        print $f join("\n", sort values %INC, abs_path($0)), "\n";
        print "Perl file list output to file $logfile\n"   if (-t STDOUT);
    }
}

Then run your script, and afterwards there should be a file generated named something like /tmp/Perl_files...$USER.txt.

The second step is to search within those files:

$ grep 'regex' $(cat /tmp/Perl_files_blahblah.root.txt)

This works for CGI scripts too, though in that case, you'll have to try to guess the name of the file that was written: ls -lrt /tmp/Perl_files_*

TODO: It's known that this Perl code breaks when running under Perl's taint mode (such as when the script has been sudo'd). Fix this at some point.