develooper Front page | perl.beginners | Postings from February 2002

Re: Return multiple arrays

Thread Previous | Thread Next
From:
Adam Turoff
Date:
February 5, 2002 08:06
Subject:
Re: Return multiple arrays
Message ID:
20020205160525.GC7235@panix.com
On Tue, Feb 05, 2002 at 08:52:44AM -0700, Mike Garner wrote:
> I have a subroutine that calls another 
> subroutine, passing one array to the second for processing.  I need the 
> second sub to return 3 arrays to the first sub.  I can't seem to get this 
> to work....well I can return the data from all three subs, but it returns 
> into one array.  Is there an option to do this or do I need to rewrite the 
> second subroutine into 3 smaller subs? or maybe I'm not using my 
> correctly...running without use strict; and not using my on the arrays 
> makes them global and avaiable for processing by the first sub...but I want 
> to use strict;

When you're returning values, you can either return a single (atomic) value,
or a list of values (a series of atomic values).  The behavior you're have
demonstrates that when you're returning a series of three arrays, the values
in those arrays get flattened into a single list:

	sub mysub1 { 
		return 1..5, 10..15, 20..25; 
	}


	my (@a, @b, @c) = mysub1();
	print "@a\n";

	## prints 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25\n

If you want to return three arrays, the way to accomplish that is to 
return three discrete elements, each of which is a *reference* to an array.
What you're returning then is a list of three arrayrefs, which you can then
de-reference to get at the individual array elements:

	sub mysub2 { return [1..5], [10..15], [20..25]; }

	my ($a, $b, $c) = mysub2();
	print "@$a\n";
	print "@$b\n";
	print "@$c\n";

	## prints 1 2 3 4 5\n10 11 12 13 14 15\n20 21 22 23 24 25\n

Now, each array has been wrapped with an array reference (a scalar value),
and you can now address each array individually (with a dereference).

In your code, the return statement would look something like this:

	return [@array1], [@array2], [@array3];

		- or -

	return \@array1, \@array2, \@array3;   ## same effect

HTH,

Z.


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About