http://www.perlmonks.org?node_id=1022254


in reply to perl vs she-bang perl

Discussion:

Lots of good answers here. Thank you all.

After consideration of the responses, I can say that my first point would better be stated as

What command was used to start my script?

It's going to be either perl [perlargs] script ... or script ...

In the latter case, any Perl arguments are in the shebang line, but in the end, I don't care; if I restart the script the same way it was started, the Perl arguments will be applied the same way, and transparently if on the shebang line. Looking them up and applying them myself with an explict perl command would be inconsistent with the original start.

Solutions:

In *nix land, my best bet is to scrape a ps command. It gives me everything I need in one shot.

In Win* land, the wmic solution solution is perfect for my needs; it appears to be present in Windows all the way back to XP.

Followup:

So, if I wanted to bundle this all up in a module for CPAN, what do y'all think is a good name for the module and it's only function?

Replies are listed 'Best First'.
Re^2: perl vs she-bang perl
by mpersico (Monk) on Mar 07, 2013 at 17:08 UTC

    After I sent my reply above, I went off and did a rather involved exploration of /proc and ps that I was going to post here. But, as a result of that work, and a discussion of it with a colleague, I came to the conclusion that using any external means of determining a process' own start up command is potentially inaccurate and a potential security breach.

    How?

    Well, you can lie to exec about what $0 is in the first place (see http://perldoc.perl.org/functions/exec.html and search for lie). And the lie will be propagated in /proc and ps, so using those are no better than using $0. Additionally, I would imagine that mucking around with your environment (especially $ENV{PATH}) before calling exec on a naked perl command could be the potential security hazard.

    I am convinced that the safest way for a Perl program to re-invoke yourself is to build the command as follows:

    • Use $^X in place of the perl command you might determine externally.
    • Use Devel::PL_origargv for arguments/options to Perl itself.
    • Use $0 for the script name (although this can be fraught with peril, as noted above).
    • Use a copy of @ARGV before any getopt processing.
    • Put all of these in an array and use the exec(@array) form, not the exec("@array") string form.

    Still sounds like an operation worth of a module. Potential names anyone? Reinvoke? Groundhog ? :-)