I'm dealing with a SOAP API that can either return a hash or array of hashes depending if there is one or more records. This makes iterating over the return tricky. My current method is check the ref of return and either copy it to an array if it is an array, else push it on an array and then iterate over it. Is there a cleaner idiom to use?
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) { ... }
Similar to @cjm's answer, but using the ternary operator:
my $things = ref $result->{thingGroup} eq 'ARRAY'
? $result->{thingGroup}
: [ $result->{thingGroup} ];