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?
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";
}
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.