在 Perl 脚本中同时使用 ARGV 和 CGI
我正在编写一个可以从命令行和网页运行的 Perl 脚本。该脚本接收几个参数,如果从命令行启动,则通过 $ARGV 读取这些参数;如果从网页启动,则从 CGI 读取这些参数。我怎样才能做到这一点?
my $username;
my $cgi = new CGI;
#IF CGI
$username = $cgi->param('username');
#IF COMMAND LINE
$username = $ARGV[0];
I am writing a Perl script that can run both from command line and from a web page. The script receives a couple of parameters and it reads those parameters through $ARGV if it started from command line and from CGI if it started from a web page. How can I do that?
my $username;
my $cgi = new CGI;
#IF CGI
$username = $cgi->param('username');
#IF COMMAND LINE
$username = $ARGV[0];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用CGI.pm,您可以在命令行上传递参数,而无需更改代码。引用文档:
对于你的例子,这是一个做的问题:
With CGI.pm you can pass params on the command line with no need to change your code. Quoting the docs:
Wrt your example, it's a matter of doing:
Mojolicious 框架 使用经过实战验证的环境自动检测,适用于不同的服务器(不仅仅是 Apache)。
所以你可以使用下面的代码:
Mojolicious framework uses battle-proven environment autodetection that works on different servers (not Apache only).
So you can use following code:
最简洁的方法可能是将代码的核心部分放入模块中,并为每个接口(CGI 和命令行)编写一个脚本。
您可以测试 CGI 环境变量 (
$ENV{SERVER_PROTOCOL}
) 是否存在,以查看是否正在使用 CGI,但如果该脚本用作来自另一个 CGI 的命令行脚本,则会失败脚本。如果您想通过 @ARGV 传递的只是表单输入,请记住,如果脚本未被调用为 CGI(模块)将检查 @ARGV 的输入CGI 脚本。请参阅文档中标题为“调试”的部分。
The cleanest way might be to put the meat of your code in a module, and have a script for each interface (CGI and command line).
You could test for the presence of CGI environment variables (
$ENV{SERVER_PROTOCOL}
) to see if CGI is being used, but that would fail if the script is used as a command-line script from another CGI script.If all you want to pass via
@ARGV
are form inputs, keep in mind that CGI (the module) will check the@ARGV
for inputs if the script is not called as a CGI script. See the section entitled "DEBUGGING" in the documentation.当通过 CGI 调用时,您的脚本将设置额外的环境变量。您可以在 if 条件中使用它们。
例如,您可以使用 HTTP_USER_AGENT
但如果您真正需要的是独立测试 CGI 脚本,请尝试 ActiveState Komodo,调试器可以模拟 CGI 环境
When invoked through CGI your script will additional environment variables set. You can use them in your if condition.
For example, you could use HTTP_USER_AGENT
But if your real need is to test a CGI script stand alone, Try ActiveState Komodo, The debugger lets to Simulate CGI Environment