raz3r
raz3r

Reputation: 3131

Using both ARGV and CGI in a Perl script

I am writing a Perl script that can run both from command line and from a web page. The script receives a couple of parameters and it reads those parameters through $ARGV if it started from command line and from CGI if it started from a web page. How can I do that?

my $username;
my $cgi = new CGI;
#IF CGI
$username = $cgi->param('username');
#IF COMMAND LINE
$username = $ARGV[0];

Upvotes: 7

Views: 3438

Answers (4)

yko
yko

Reputation: 2710

Mojolicious framework uses battle-proven environment autodetection that works on different servers (not Apache only).

So you can use following code:

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

Upvotes: 6

ikegami
ikegami

Reputation: 385657

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

You could test for the presence of CGI environment variables ($ENV{SERVER_PROTOCOL}) to see if CGI is being used, but that would fail if the script is used as a command-line script from another CGI script.

If all you want to pass via @ARGV are form inputs, keep in mind that CGI (the module) will check the @ARGV for inputs if the script is not called as a CGI script. See the section entitled "DEBUGGING" in the documentation.

Upvotes: 4

larsen
larsen

Reputation: 1431

With CGI.pm you can pass params on the command line with no need to change your code. Quoting the docs:

If you are running the script from the command line or in the perl debugger, you can pass the script a list of keywords or parameter=value pairs on the command line or from standard input (you don't have to worry about tricking your script into reading from environment variables)

Wrt your example, it's a matter of doing:

perl script.cgi username=John

Upvotes: 9

parapura rajkumar
parapura rajkumar

Reputation: 24403

When invoked through CGI your script will additional environment variables set. You can use them in your if condition.

For example, you could use HTTP_USER_AGENT

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

But if your real need is to test a CGI script stand alone, Try ActiveState Komodo, The debugger lets to Simulate CGI Environment

Upvotes: 3

Related Questions