Can you force either a scalar or array ref to be an array in Perl? Can you force either a scalar or array ref to be an array in Perl? arrays arrays

Can you force either a scalar or array ref to be an array in Perl?


im not sure there's any other way than:

$result = [ $result ]   if ref($result) ne 'ARRAY';  foreach .....


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:

sub call_to_service{    my $returnValue = service::call();    if (ref($returnValue) eq "ARRAY")    {        return($returnValue);    }    else    {       return( [$returnValue] );    }}

Then you can always know that you will get back a reference to an array, even if it was only one item.

foreach my $item (@{call_to_service()}){  ...}


Well if you can't do...

for my $result ( ref $results eq 'ARRAY' ? @$results : $results ) {    # Process result}

or this...

for my $result ( ! ref $results ? $results : @$results ) {    # Process result}

then you might have to try something hairy scary like this!....

for my $result ( eval { @$results }, eval $results ) {    # Process result}

and to avoid that dangerous string eval it becomes really ugly fugly!!....

for my $result ( eval { $results->[0] } || $results, eval { @$results[1 .. $#{ $results }] } ) {    # Process result}

PS. My preference would be to abstract it away in sub ala call_to_service() example given by reatmon.