mike622867
mike622867

Reputation: 377

Making Perl script *run itself* with flags

I'm very new to Perl, and have recently encountered the following problem. My Perl code must all reside within a single file (it's being called by another program I have no control of). I now wish to make the script run with a flag (e.g., perl myscript.pl -T for taint mode), although it is initially called without the flag. How can I do that, i.e., how do I "set the flag" from within the Perl file?

One idea that I've had is to make the file launch itself again (after being called without flags), this time with the -T flag (by issuing a shell command such as system($^X, "myscript.pl -T", @ARGS);). Would that work? Any better ideas?

Upvotes: 8

Views: 1008

Answers (1)

mob
mob

Reputation: 118605

I think you're on the right track. You can make use of the $^{TAINT} variable, and exec instead of system:

exec($^X, $0, '-T', @ARGV) if $^{TAINT} < 1;

This won't work in all cases. For one thing, you'll lose some other command line switches that your script might initially be called with:

perl -I/path/to/some/more/libs -w -MNecessary::Module myscript.pl ...

There are some workarounds to some of these (use warnings or add -w switch to your exec statement above, analyze @INC and %INC to determine what -I and -M switches were added) but the more you can learn about exactly how your script is called, the more you can figure out what workarounds you need to worry about.


Depending on the ... group dynamics in play here, another approach is to exercise some indirect control of the calling program. Go ahead and put -T on the shebang line as @Hunter McMillen and @ThisSuitIsBlackNot suggest, wait for a bug report, and then diagnose the problem as "program not invoked with -T switch" ...

Upvotes: 5

Related Questions