如何处理变量散列值
How to deal with variable hash value
我正在处理一个 SOAP API,它可以 return 散列或散列数组,具体取决于是否有一个或多个记录。这使得遍历 return 变得棘手。我当前的方法是检查 return 的引用,如果它是一个数组,则将其复制到一个数组,否则将其推送到一个数组上,然后对其进行迭代。有没有更简洁的习语可以使用?
my @things;
if ( ref $result->{thingGroup} eq 'ARRAY' ) {
@things = @{ $result->{thingGroup} };
} elsif ( ref $result->{thingGroup} eq 'HASH' ) {
push @things, $result->{thingGroup};
}
foreach my $thing (@things) { ... }
我会改用数组引用,这样可以避免不必要的复制:
my $things = $result->{thingGroup};
unless (ref $things eq 'ARRAY' ) {
$things = [ $things ];
}
foreach my $thing (@$things) { ... }
我删除了 elsif
,因为不清楚它添加了什么。如果你想确保 non-array 实际上是一个散列,那么你还应该有一些代码来处理它不是的情况。
类似于@cjm 的回答,但使用 ternary operator:
my $things = ref $result->{thingGroup} eq 'ARRAY'
? $result->{thingGroup}
: [ $result->{thingGroup} ];
我正在处理一个 SOAP API,它可以 return 散列或散列数组,具体取决于是否有一个或多个记录。这使得遍历 return 变得棘手。我当前的方法是检查 return 的引用,如果它是一个数组,则将其复制到一个数组,否则将其推送到一个数组上,然后对其进行迭代。有没有更简洁的习语可以使用?
my @things;
if ( ref $result->{thingGroup} eq 'ARRAY' ) {
@things = @{ $result->{thingGroup} };
} elsif ( ref $result->{thingGroup} eq 'HASH' ) {
push @things, $result->{thingGroup};
}
foreach my $thing (@things) { ... }
我会改用数组引用,这样可以避免不必要的复制:
my $things = $result->{thingGroup};
unless (ref $things eq 'ARRAY' ) {
$things = [ $things ];
}
foreach my $thing (@$things) { ... }
我删除了 elsif
,因为不清楚它添加了什么。如果你想确保 non-array 实际上是一个散列,那么你还应该有一些代码来处理它不是的情况。
类似于@cjm 的回答,但使用 ternary operator:
my $things = ref $result->{thingGroup} eq 'ARRAY'
? $result->{thingGroup}
: [ $result->{thingGroup} ];