我正在尝试从 AJAX 请求(使用 Catalyst)动态创建值列表,如下所示:
my @listofvalues = @{$params->{parameter_with_many_values}};
然后我遍历列表以进行数据库插入(每个值一个)。因为我需要像上面那样遍历各种列表,所以我需要访问列表的索引。我目前是这样做的:
foreach my $key (0 .. $#listofvalues){
$table_model->new({
field1 => $listofvalues[$key],
field2 => $x,
field3 => $another_listofvalues[$key]
field4 => $yet_another_listofvalues[$key]
});
}
当在请求中收到两个或更多 元素时,这似乎工作正常。每当收到单个元素时,我都会收到类似
的错误[error] Caught exception in pbitdb::Controller::Subjects->add "Can't use string ("1") as an ARRAY ref while "strict refs" in use at /home/lioneluranl/svn/pbitdb/pbitdb/script/../lib/pbitdb/Controller/Subjects.pm line 119."
在这种情况下,1 是收到的值,第 119 行 是声明@listofvalues 的行。
现在我已经尝试了几种方法来解决这个问题,但还没有找到任何可以双向工作的方法(对于单个值或多个值)。有什么建议吗?
最佳答案
是的,单个元素列表在 Perl 中是可以的,数组和对此类数组的引用也是如此。
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
sub new {
print Dumper \@_;
}
my $table_model = 'main';
for my $values ( [ 'a' .. 'c' ],
[ 'd' ]
) {
my $params = { parameter_with_many_values => $values };
my @listofvalues = @{ $params->{parameter_with_many_values} };
my @another_listofvalues = map uc, @listofvalues;
for my $key (0 .. $#listofvalues) {
my $x = rand;
$table_model->new({
field1 => $listofvalues[$key],
field2 => $x,
field3 => $another_listofvalues[$key]
});
}
}
如何填充 $params->{parameter_with_many_values}
?
好像Catalyst::Request应该提到它们的“安全”参数应该按如下方式处理:
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
for my $params ( { param_with_many_values => 'a' },
{ param_with_many_values => [ 'a' .. 'e' ] },
{ something => 'else' }
) {
my $value_or_values = $params->{param_with_many_values};
my @list_of_values = ref $value_or_values ? @$value_or_values
: defined $value_or_values ? $value_or_values
: ();
print Dumper \@list_of_values;
}
https://stackoverflow.com/questions/41838669/
相关文章:
.net - 如何配置 NHibernate 以使用 MS SQL 2016 (RTM)?
python-3.x - python : How to call a variable in an
javascript - 如何在 v-for 中访问对象属性名称
javascript - 谷歌登录 : disable autologin on page load
google-maps - 如何在 angular2 中显示带有地址的谷歌地图
python - 如何在 Python 中将 unicode 字符串加载到 json 中?