如何区分 CLI 和 CLI Perl 中的 CGI 模式

发布于 2024-09-06 03:44:08 字数 93 浏览 2 评论 0原文

我应该编写一个 Perl 脚本,它既可以在命令行上运行,也可以作为 CGI 脚本运行。我无法确定应该如何区分这两种模式。

那么你能告诉我如何实现这个逻辑吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

携余温的黄昏 2024-09-13 03:44:08

您可以检查是否存在任意数量的 CGI 环境变量,例如:

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

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";
}
吃素的狼 2024-09-13 03:44:08

据猜测,从命令行运行时 $ENV{'GATEWAY_INTERFACE'} 将为 NULL,并在作为 CGI 运行时包含某些内容(例如 1.1)。

你需要尝试一下。

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.

旧伤慢歌 2024-09-13 03:44:08

由于这是一个常见问题,我想指出人们可能会对两种以上的情况感兴趣。对于更通用的解决方案:

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
}

如果您提示用户输入,那么您想要的是第二种情况查看。在开始编写自己的 is_interactive() 实现之前,您可能应该查看 这篇文章作者为IO::Interactive 模块。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文