Saturday, March 14, 2009

Returning multiple arrays from a perl function

I wrote a perl function where I was trying to return 2 arrays from a perl function with statement,
return (@array1, @array2);
Return values were being collected as
my (@a1, @a2) = array_function ();
Even though there were no errors, my script was not working as expected. Only when I digged deeper I realized that returned arrays were not getting collected properly in @a1 & @2. Perl, was returning both of those arrays in concatenated manner and all the contents were getting assigned to single array @a1.

The fix:
To fix this issue, I changed the function to return references to array instead of arrays themselves. References are scalars and hence can be returned from functions just like any other scalar variables. Now my code inside a function changed to

return (\@array1, \@array2);

and calling statement changed to

my ($ref_a1, $ref_a2)= array_function ();
The way these references are used to retrieve the contents of array is to use a formation,
@{ref_a1} and @{ref_a2}

This one was a good learning!

1 comment:

Unknown said...

minor edit, the line at the end should say
@{$ref_a1} and @{$ref_a2}
or just
@$ref_a1 and @$ref_a2

but not
@{ref_a1} and @{ref_a2}

at least that's what worked for me