Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 960
Rudd Zwolinski Avatar asked Aug 06 '08 05:08

Rudd Zwolinski


People also ask

How do I convert a scalar variable to an array in Perl?

var = "abc|xyz|123"; I want to have the above values in to array. $var = "abc|xyz|123"; $var =~ tr/|/\n/; # transforming "|" to new line "\n" @a = $var; print $a[0]; The complete transformed output is sent to only variable instead of individual variables.

How do I reference an array in Perl?

Creating a reference to a Perl array If we have an array called @names, we can create a reference to the array using a back-slash \ in-front of the variable: my $names_ref = \@names;. We use the _ref extension so it will stand out for us that we expect to have a reference in that scalar.

What is scalar array in Perl?

An array is an ordered and mutable list of scalars. In Perl, scalars are defined as a single unit of data such as an integer, a floating-point, a character, a string, and so on. They are preceded by a $ when defined.


2 Answers

im not sure there's any other way than:

$result = [ $result ]   if ref($result) ne 'ARRAY';   foreach ..... 
like image 156
svrist Avatar answered Sep 30 '22 04:09

svrist


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()}) {   ... } 
like image 44
user1917 Avatar answered Sep 30 '22 05:09

user1917