I have a perl variable $results
that gets returned from a service. The value is supposed to be an array, and $results
should be an array reference. However, when the array has only one item in it, $results
will be set to that value, and not a referenced array that contains that one item.
I want to do a foreach
loop on the expected array. Without checking ref($results) eq 'ARRAY'
, is there any way to have something equivalent to the following:
foreach my $result (@$results) {
# Process $result
}
That particular code sample will work for the reference, but will complain for the simple scalar.
EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.
im not sure there's any other way than:
Another solution would be to wrap the call to the server and have it always return an array to simplify the rest of your life:
Then you can always know that you will get back a reference to an array, even if it was only one item.
Well if you can't do...
or this...
then you might have to try something hairy scary like this!....
and to avoid that dangerous string eval it becomes really ugly fugly!!....
PS. My preference would be to abstract it away in sub ala call_to_service() example given by reatmon.
I would re-factor the code inside the loop and then do
Of course I would only do that if the code in the loop was non-trivial.
I've just tested this with:
And it seems to work ok, so I'm thinking it has something to do with the result getting returned from the service? If you have no control over the returning service this might be hard one to crack
You can do it like this: