Using ARGV and CGI in a Perl script

I am writing a Perl script that can be run both from the command line and from a web page. The script receives several parameters and reads these parameters using $ ARGV if it is launched from the command line and from CGI if it is launched from a web page. How can i do this?

my $username; my $cgi = new CGI; #IF CGI $username = $cgi->param('username'); #IF COMMAND LINE $username = $ARGV[0]; 
+6
source share
4 answers

The cleanest way is to put the meat of your code in a module and have a script for each interface (CGI and command line).

You can check for CGI environment variables ( $ENV{SERVER_PROTOCOL} ) to see if CGI is used, but this will happen if the script is used as a command line script from another CGI script.

If everything you want to pass through @ARGV is form inputs, keep in mind that the CGI (module) checks the @ARGV input if the script is not called as a CGI script. See the DEBUGGING Section in the documentation .

+3
source

With CGI.pm, you can pass parameters on the command line without having to change your code. Quoting documents:

If you use the script from the command line or in the perl debugger, you can pass the script a list of keywords or Parameter = pairs of values ​​on the command line or from standard input (you do not have to worry about tricking your script into reading from environment variables)

Enter your example, this is the question:

 perl script.cgi username=John 
+9
source

The mocholytic structure uses time-tested autonomous auto-detection, which runs on different servers (not just Apache).

So you can use the following code:

 if (defined $ENV{PATH_INFO} || defined $ENV{GATEWAY_INTERFACE}) { # Go with CGI.pm } else { # Go with Getopt::Long or whatever } 
+6
source

When called through CGI, your script will add additional environment variables . You can use them in your if conditions.

For example, you can use HTTP_USER_AGENT

 if ( $ENV{HTTP_USER_AGENT} ) { #cgi stuff } else { #command line } 

But if your real need is to test the CGI script separately, try ActiveState Komodo, the debugger allows you to Simulate a CGI environment

+3
source

Source: https://habr.com/ru/post/902019/


All Articles