Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Perl script *run itself* with flags

Tags:

flags

perl

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?

like image 628
mike622867 Avatar asked Jul 02 '15 17:07

mike622867


People also ask

How do I run in Perl?

The normal way to run a Perl program is by making it directly executable, or else by passing the name of the source file as an argument on the command line. (An interactive Perl environment is also possible--see perldebug for details on how to do that.)

What is #!/ Usr bin Perl?

The first line in many Perl programs is something like: #!/usr/bin/perl. For Unix systems, this #! (hash-bang or shebang) line tells the shell to look for the /usr/bin/perl program and pass the rest of the file to that /usr/bin/perl for execution.

What does E mean in Perl?

The perldoc unary operator -e checks if a file exists. Perldoc unary file test operators list: -r File is readable by effective uid/gid. - w File is writable by effective uid/gid. - x File is executable by effective uid/gid. - o File is owned by effective uid. -


1 Answers

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" ...

like image 65
mob Avatar answered Nov 15 '22 17:11

mob