Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Returning two arrays..

by count0 (Friar)
on Jan 04, 2002 at 20:57 UTC ( #136303=note: print w/replies, xml ) Need Help??

in reply to Returning two arrays..

While impossiblerobot and tstock provided excellent solutions, it may help to understand why these solutions are needed.

When you return() an array, it is sent back (so to speak) as a list. The variable @array provides a nice little grouping for all its elements. If we had @array = ('a', 'b'); and return()'ed it, the portion catching this value will get ('a', 'b') and that variable container, @array, is no more.

What does this lead to? Well, given the following:
sub foo { my @a = qw(a b); my @b = qw(c d); return (@a, @b); }<br> @return_val = foo();
You might expect @return_val to contain ('a', 'b')... But because the return value is put into a list, ('a', 'b', 'c', 'd') is returned from foo(). There aren't any @a or @b anymore to "draw the line" and distinguish one array from the other... it's just one big list.

So anyhow, by returning scalars (strings, hash refs, array refs, etc), you always ensure that the elements of each of the return values (or the elements pointed to by them) stay in their container variables. =)

Replies are listed 'Best First'.
Re^2: Returning two arrays..
by Takophiliac (Novice) on Feb 16, 2005 at 20:14 UTC
    Your wisdom has enlightened me. However... Given the simplicity,IMHO, why are young monks not taught to play with arrays such:
    #**function to concatenate another value onto the end of each string. #!!Value to be added specified as last scalar sub addvalue($$$); my ($ref1,$ref2); @$ref1=("meet","my"); @$ref2=("say","hello","to","my"); ($ref1,$ref2)=addvalue($ref1,$ref2,"dog"); print "@$ref1\n"; print "@$ref2\n"; sub addvalue($$$) {my ($a,$b,$c); @$a=@{$_[0]}; @$b=@{$_[1]}; $c=$_[2]; push(@$a,$c); push(@$b,$c); return ($a,$b);}
    I am Takophiliac. The evil souls remind me and in the darkness find me.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://136303]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2018-06-24 17:40 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.