如何使用 CGI.pm 获取选中的复选框列表?

How can I get the list of checked checkboxes using CGI.pm?

我有一个包含多个复选框的表单。用户可以 select 任意多个位置,我正在尝试将所有位置保存在一个数组中。我已经尝试了以下选项但不起作用:

<input class="form-check-input" type="checkbox" value="Location 1" name="location">  
<input class="form-check-input" type="checkbox" value="Location 2" name="location"> 
<input class="form-check-input" type="checkbox" value="Location 3" name="location"> 

my @location                   = $query->param('location');;

上面这行代码获取了所有的位置,但是没有用逗号分隔,我也试了下面的但是没有得到任何东西;

my $location       = join(",", @{ $query->param('location'); });

$query->param('location') 在标量上下文中没有 return 对数组的引用,所以你试图取消引用它是没有意义的,Perl 会告诉你,如果你一直在使用 use strict; use warnings; 你总是应该这样做。

如您所见,$query->param('location') 在列表上下文中 return 是所有值,因此您需要

join(",", $query->param('location'))

当然,您的工作代码段和这个代码段都会产生以下警告:

CGI::param called in list context from -e line 1, this can lead to vulnerabilities. See the warning in "Fetching the value or values of a single named parameter"

如文档的参考部分所述,您应该在列表上下文中使用 ->multi_param 而不是 ->param

join(",", $query->multi_param('location'))