Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

returning two arrays

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
Hello all,

I am trying to return two arrays from a function. My code is as follows:

(@array1, @array2) = function();

sub function(){
@temp1();
@temp2();

some code here..

return (@temp1, @temp2);
}

However this dosent seem to work - @array2 dosent seem to be populated - i am doing something wrong?

thanks for your help
jim
 
Hi Jim,

Perl return() values don't quite work like that.

these two statement, in a sub

return(@array1, $scalar1, @array2);
return(@array3);

They will both compile and run just fine - but you'll run into problems in the calling script with the first one unless you know *exactly* how many elements @array1 has.

Basically - you just get a list of values returned.

What you have to do is return what's call a "reference" to an array, like this.

return(\@array1, $scalar1, \@array2);

Then, in your calling script, you can write code that understands that these references actually point to arrays.

Have a look at:

perldoc perlreftut
perldoc perlref
Mike
______________________________________________________________________
"Experience is the comb that Nature gives us after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Mike is correct. When you pass arrays to a subroutine, or return arrays from subroutines, they are actually "flattened" into a single long LIST of values. Which means that all values passed or returned will be treated as a single "array". Array references like Mike mentioned are definitely the best way to handle passing and returning arrays, and they're not that difficult to learn. If you're going to do any kind of sophisticated perl programming you're going to have to learn how to use them eventually.

Another perl man page I'd recommend is perldsc (Data Structures Cookbook). It shows how to do arrays of arrays, arrays of hashes, etc. Pretty deep reading, but lots of good stuff about references. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top