问题
I am supposed to write a Perl script which can be run both on the command line and as a CGI script. I haven't been able to determine how I should distinguish between the two modes.
So could you please let me know how to implement the logic?
回答1:
You can check for the presence of any number of CGI environment variables, e.g.:
if ($ENV{GATEWAY_INTERFACE})
{
print "Content-type: text/plain\n\nLooks like I'm a CGI\n";
}
else
{
print "I'm just a plain command line program\n";
}
回答2:
At a guess, $ENV{'GATEWAY_INTERFACE'}
will be NULL when run from the command line, and contain something (e.g. 1.1) when run as a CGI.
You'll need to try it out.
回答3:
Since it's a common question, I want to point out that there are more than two cases people might be interested in. For a more all-purpose solution:
use IO::Interactive qw( is_interactive );
if (exists $ENV{'GATEWAY_INTERFACE'}) {
# running as CGI
}
elsif (is_interactive()) {
# running from terminal, with a real live user
}
else {
# running from cron, system call, etc
}
If you're prompting the user for input, it's the second case that you want to check. And before you start writing your own implementation of is_interactive()
you should probably look at this post by the author of the IO::Interactive module.
来源:https://stackoverflow.com/questions/3086655/how-to-distinguish-between-cli-cgi-modes-in-perl