3
votes

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?

3

3 Answers

8
votes

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
votes

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.

1
votes

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.