On Sep 8, 2014, at 3:13 PM, lee wrote:

> Shawn H Corey <shawnhco...@gmail.com> writes:
> 
>> On Mon, 18 Aug 2014 16:17:53 +0800
>> Ken Peng <o...@dnsbed.com> wrote:
>> 
>>> sub myfunc {
>>>  my @x=(1,2,3);
>>>  return \@x;
>>> }
>>> 
>>> # or,
>>> 
>>> sub myfunc {
>>>  my @x=(1,2,3);
>>>  return [@x];
>>> }
>> 
>> # or
>> 
>> sub myfunc {
>>  return [ 1, 2, 3 ];
>> }
> 
> Is there a difference to
> 
> sub myfunc {
>  return ( 1, 2, 3 );
> }

The first example returns [ 1, 2, 3 ], which is a reference to a list with 3 
elements. References are scalars.

The second example returns ( 1, 2, 3 ), which is a list with 3 elements.

So, yes, there is a difference.

> ?  And my understanding was/is that in
> 
> sub myfunc {
>  my @x=(1,2,3);
>  return \@x;
> }
> 
> a reference would be returned to an array that ceases to exist when the
> function returning it has finished.  At the point the function returns
> to, there isn't anything left the reference could refer to.
> 
> Or is there?

Perl will not garbage-collect an element if there is a reference to it. So 
while the array name @x no longer is in scope once the subroutine has returned, 
the list that was the value of @x still exists in memory, and the reference 
returned by the subroutine will be valid.

If the reference is not saved or copied, then the list will eventually get 
garbage collected.


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to