如何从哈希中删除未定义的键?
尝试使用 map 和 grep 来解决这个问题,知道出了什么问题吗?我不断收到 新哈希值时,出现“严格引用”时无法使用字符串(“10”)作为哈希引用错误
sub scrub_hash{
my($self,$hash_ref) = @_;
my $scrubbed_hash = map { defined $hash_ref->{$_} ? ($_ => $hash_ref->{$_}) : () } keys %{$hash_ref};
print STDERR "[scrub]". $_."\n" for values %{$scrubbed_hash};
}
当我尝试打印此处使用的 ...
my $params_hash = $cgi->Vars();
my $scrubbed = $self->scrub_empty_params($params_hash) if $self->is_hash($params_hash);
在这种情况下,通过帖子提交表单时未定义的参数仍然显示为 key1=&key2= 所以擦洗将它们去掉
Trying to use map and grep to figure this out, any idea whats wrong? I keep getting a
Can't use string ("10") as a HASH ref while "strict refs" error when I try to print the values of the new hash
sub scrub_hash{
my($self,$hash_ref) = @_;
my $scrubbed_hash = map { defined $hash_ref->{$_} ? ($_ => $hash_ref->{$_}) : () } keys %{$hash_ref};
print STDERR "[scrub]". $_."\n" for values %{$scrubbed_hash};
}
used here
...
my $params_hash = $cgi->Vars();
my $scrubbed = $self->scrub_empty_params($params_hash) if $self->is_hash($params_hash);
in this case the params that are undefined when a form is submitted via post still show up as key1=&key2= so scrub takes em off
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在此行中:
您正在将
map
中的列表分配到标量$scrubbed_hash
中。标量上下文中的map
将返回列表中的元素数量 (10)。不要分配给标量,而是分配给复数哈希:
如果您确实想为
$scrubbed_hash
使用标量,则需要使用{map {...} args}
将从列表中构造一个匿名散列。要过滤掉适当的元素,您可以使用
delete
函数:根据更新:
scrub_empty_params
方法应如下所示:如果这不适合您,那么您的值可能已定义,但长度为 0。
您可能希望通过创建一个不同的
->Vars()
方法来从 API 中删除一些样板文件,该方法返回过滤后的哈希值:In this line here:
You are assigning a list from
map
into the scalar$scrubbed_hash
.map
in scalar context will return the number of elements in the list (10).Rather than assigning to a scalar, assign to a plural hash:
If you really wanted to use a scalar for
$scrubbed_hash
you will need to wrap the map statement with{map {...} args}
which will construct an anonymous hash out of the list.To filter out the elements in place, you could use the
delete
function:per the update:
The
scrub_empty_params
method should look something like this:If that is not working for you, then it may be that your values are defined, but have a length of 0.
You might want to remove a bit of boiler plate from your API by creating a different
->Vars()
method that returns a filtered hash:试试这个:
Try this: