How to distinguish between CLI & CGI modes in Perl

隐身守侯 提交于 2019-11-29 08:13:25

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!