简体   繁体   English

Perl:CGI模块-将param()作为参数传递给子例程

[英]Perl: CGI module - passing param() as parameters to subroutines

Question about using the Perl CGI module: 有关使用Perl CGI模块的问题:

Let's say I have a sub called foo that accepts two parameters defined as follows: 假设我有一个名为foo的子程序,它接受两个定义如下的参数:

sub foo {
   local($a, $b) = @_;
   print "a= [$a]";
}

In my main routine, I take some form parameters and pass them to foo like this: 在我的主例程中,我采用了一些形式参数并将它们传递给foo,如下所示:

use CGI;
$cgi = CGI->new;
foo($cgi->param('field1'), $cgi->param('field2'));

If the form did not pass in a value for field1, (in my case, a SELECT field called field1 with no values to choose from was used), the sub foo sets $a to the value that was passed in $cgi->param('field2'), which was a non-empty value. 如果表单未传递field1的值(在我的示例中,使用了一个名为field1的SELECT字段,没有可供选择的值),则子foo会将$ a设置为$ cgi-> param中传递的值('field2'),这是一个非空值。

Can someone help me understand why this happens and why $a isn't simply a blank ('') value and $b = the value sent in from $cgi->param('field2')? 有人可以帮助我理解为什么会发生这种情况,以及为什么$ a不仅仅是一个空白('')值,而$ b =从$ cgi-> param('field2')发送来的值吗?

I'm sure there's a logical reason, but I'm not a Perl pro so I'm sure it's something I've yet to learn or understand about Perl. 我确定这是有道理的,但是我不是Perl专业人士,所以我确定这是我尚未了解或了解的有关Perl的知识。

Thanks in advance! 提前致谢!

CGI 's param() function behaves differently if called in list or scalar context. 如果在列表或标量上下文中调用, CGIparam()函数的行为将有所不同。 In scalar context, the first (and most the only) parameter value is returned. 在标量上下文中,将返回第一个(也是唯一的)参数值。 In list context, all parameter values are returned (remember that CGI allows to have multiple values per key). 在列表上下文中,将返回所有参数值(请记住,CGI允许每个键具有多个值)。

If you call your function like this, then list context is used. 如果这样调用函数,则使用列表上下文。 This means that $cgi->param('field1') evaluates to the empty list, and the first value of $cgi->param('field2') is assigned to $a in the subroutine. 这意味着$cgi->param('field1')为空列表,并且$cgi->param('field2')的第一个值在子例程中分配给$a To avoid this, you have to explicitly force scalar context. 为了避免这种情况,您必须显式强制标量上下文。 This can be done by using scalar : 这可以通过使用scalar来完成:

foo(scalar($cgi->param('field1')), scalar($cgi->param('field2')));

Another possibility is to use intermediate variables: 另一种可能性是使用中间变量:

my $field1 = $cgi->param('field1'); # scalar context here
my $field2 = $cgi->param('field2');
foo($field1, $field2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM