How can I determine if a script was called from the command line or as a cgi script?

落花浮王杯 提交于 2019-11-28 00:02:19
VoidPointer

According to the CGI specification in RFC3875 (section 4.1.4.), the GATEWAY_INTERFACE environment variable would be the authoritative thing to check whether you are running in a CGI context:

4.1.4. GATEWAY_INTERFACE

The GATEWAY_INTERFACE variable MUST be set to the dialect of CGI being used by the server to communicate with the script.

There's really no way good way to tell if your script was started by a web server or from the command line. Any of the environment variables can be set in both situations. I often run CGI programs straight from the command line to test them, for instance.

Knowing that, if you want to pick one environment variable to use, it just has to be one that you won't set in the other situation, or one that you set in both but give different values to. In that case, choose any environment variable that you like.

If you want to get more sophisicated, you can use something like IO::Interactive to determine if you're connected to a terminal. If you aren't, the filehanandle that is_interactive returns is a null filehandle and the output goes nowhere:

 print { is_interactive() } $http_header;

If you don't like how IO::Interactive decides, you can reimplement is_interactive. It's a very short piece of code and the higher-level interface is very nice.

Peter

I usually do a little trick at the beginning of my module:

exit run(@ARGV) unless caller();   # run directly if called from command line

sub run
{
    process_options(@_);
    ...
}

sub process_options {
    @ARGV = @_;
    my  %opts;
    GetOptions(\%opts,
    ...
}

The module does not have to be named "run".

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