我想迭代一个大散列的值,如果该散列的任何值是键,我想将它转换为逗号分隔列表,可以在' query_form'中解析。
现在从下面的数据中我得到了:
name = Bob& surname = Whitbread& customerErrors = HASH(Xa456)(例如)
这是我到目前为止所拥有的:
sub convertArgsToQueryString {
my $class = shift;
my $args = shift;
return unless ($args && ref($args) eq 'HASH');
foreach my $key (values %$args) {
if (ref($key) eq 'HASH') {
# change to a comma separated list
}
}
my $dummyURL = URI->new('', 'http');
$dummyURL->query_form(%$args);
return $dummyURL->query;
}
数据:
my $data = {
'name' => 'Bob',
'surname' => 'Whitbread',
'customerErrors' => {
'error1' => 'paymentError',
'error2' => 'addressError'
},
};
查询表格:
名=鲍勃&安培;姓=惠特&安培; customerErrors = paymentError,addressError
答案 0 :(得分:1)
这将做你想要的事情
print join ",", values %{$data->{customerErrors}},"\n";
虽然我建议,而不是error1
作为哈希键,你最好使用数组:
my $data = {
'name' => 'Bob',
'surname' => 'Whitbread',
'customerErrors' => [ 'paymentError', 'addressError' ],
};
将其缩小为通用,您会发现ref
函数有用:
foreach my $key ( keys %$data ) {
print "$key is a ", ref $data->{$key},"\n";
if ( ref $data->{$key} eq 'HASH' ) {
print join ",", values %{$data->{$key}};
}
else {
print $data -> {$key},"\n";
}
}
或简洁地说:
print join "\&", map { #join iterated on &
join "=", $_, #join paired values on =
ref $data->{$_} eq 'HASH' #ternary to check reference type
? values %{ $data->{$_} } #extract values if HASH
: $data->{$_} #extract just value if not.
} keys %$data; #iterate keys of data
作为输出:
name=Bob&customerErrors=addressError=paymentError&surname=Whitbread