如何处理变量哈希值



我处理的是一个SOAP API,它可以返回哈希或哈希数组,具体取决于是否有一个或多个记录。这使得迭代返回变得棘手。我目前的方法是检查return的ref,如果它是一个数组,要么将其复制到一个数组中,要么将它推送到一个数组上,然后对其进行迭代。有更干净的习惯用法吗?

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) { ... }

类似于@cjm的答案,但使用三元运算符:

my $things = ref $result->{thingGroup} eq 'ARRAY'
    ? $result->{thingGroup}
    : [ $result->{thingGroup} ];

我会使用数组引用,这样可以避免不必要的复制:

my $things = $result->{thingGroup};
unless (ref $things eq 'ARRAY' ) {
    $things = [ $things ];
} 
foreach my $thing (@$things) { ... }

我删除了elsif,因为不清楚它是否添加了任何内容。如果你想确保非数组实际上是一个散列,那么你也应该有一些代码来处理它不是的情况。

最新更新