要使用 Perl 进行 CGI,只需使用该CGI
模块(预安装在 Perl 中)。它将正确、安全地解析表单字段,并同时处理 theget
和post
HTTP 方法。这比编码或复制和粘贴解决方案要容易得多。只需编写一个小 CGI 脚本来包装您的原始脚本或重写您的脚本以在 CGI 和命令行模式之间切换。
HTML:
<form method="post" action="myScript.pl">
<input type="text" name="name" />
<input type="submit" value="Submit /">
</form>
珀尔:
#!/usr/bin/perl
use strict; use warnings;
use CGI::Carp; # send errors to the browser, not to the logfile
use CGI;
my $cgi = CGI->new(); # create new CGI object
my $name = $cgi->param('name');
print $cgi->header('text/html');
print "Hello, $name";
您使用该param
方法获取数据字段。有关更多变体,请参阅文档。然后,您可以调用脚本并返回输出。您可能会使用qx{…}
或open
调用您的脚本并阅读输出。如果您想返回纯输出,您可以尝试exec
. 请注意它不会返回(Content-type
应该是text/plain
)。
my $arg0 = $cgi->param('ARG[0]');
...;
my $output = qx{perl script.pl -ARG[0] "$arg0" -ARG[1] "$arg1"};
print $output;
或者
my $arg0 = $cgi->param('ARG[0]');
...;
# prints directly back to the browser
exec 'perl', 'script.pl', '-ARG[0]', $arg0, '-ARG[1]', $arg1;
The first form allows you prettify your ourput, our decorate it with HTML. The second form is more efficient, and the arguments can be passed safely. However, the raw output is returned.
You can use system
instead of exec
if the original script shall print directly to the browser, but you have to regain the control flow, e.g. to close a <div>
or whatever.