处理作为数组发送的 POST 数据

Handle POST data sent as array

我有一个 html 表单,它发送一个隐藏字段和一个同名的单选按钮。

这允许人们提交表单而无需从列表中选择(但记录零答案)。

当用户执行 select 单选按钮时,表单会同时发布隐藏值和selected 值。

我想编写一个 perl 函数来将 POST 数据转换为散列。以下适用于标准文本框等

#!/usr/bin/perl
use CGI qw(:standard);
sub GetForm{
    %form;
    foreach my $p (param()) {
         $form{$p} = param($p); 
    }
    return %form;
}   

然而,当面对两个同名的表单输入时,它只是 returns 第一个(即隐藏的)

我可以看到输入作为数组包含在 POST header 中,但我不知道如何处理它们。

我正在使用遗留代码,所以很遗憾我无法更改表单!

有办法吗?

I have an html form which sends a hidden field and a radio button with the same name.

This allows people to submit the form without picking from the list (but records a zero answer).

这是一种奇怪的方法。将隐藏的输入排除在外并将缺少数据视为零答案会更容易。


但是,如果您想坚持自己的方法,请阅读 the CGI module 的文档。

具体来说,documentation for param:

When calling param() If the parameter is multivalued (e.g. from multiple selections in a scrolling list), you can ask to receive an array. Otherwise the method will return the first value.

因此:

$form{$p} = [ param($p) ]; 

但是,您似乎确实在重新发明轮子。有一个built-in method to get a hash of all paramaters:

$form = $CGI->new->Vars

也就是说,文档还说:

CGI.pm is no longer considered good practice for developing web applications, including quick prototyping and small web scripts. There are far better, cleaner, quicker, easier, safer, more scalable, more extensible, more modern alternatives available at this point in time. These will be documented with CGI::Alternatives.

所以无论如何你都应该远离这个。

替换

$form{$p} = param($p);                             # Value of first field named $p

$form{$p} = ( multi_param($p) )[-1];               # Value of last field named $p

$form{$p} = ( grep length, multi_param($p) )[-1];  # Value of last field named $p
                                                   # that has a non-blank value