return \@array or @array

Jérôme Étévé jerome.eteve at gmail.com
Thu Sep 12 17:05:35 BST 2013


Great :)

so now:

use Devel::Peek;

sub foo{
    my @foo = 0..2;
    # Dump A
    print Dump(\@foo);
    return @foo;
}

my @foo = foo();

# Dump B
print Dump(\@foo);

Prints quite interesting resutls. It shows both references are the
same, with only the intermediate PVAV changing.

I'm still not quite sure about the real benefit of return \@array though.

Cheers,

J.



On 12 September 2013 16:32, Yitzchak Scott-Thoennes <sthoenna at gmail.com> wrote:
> On Thu, Sep 12, 2013 at 7:33 AM, Jérôme Étévé <jerome.eteve at gmail.com> wrote:
>> use Devel::Peek;
>>
>> my $foo_ref;
>>
>> sub foo{
>>     my @foo = 0..2;
>>     $foo_ref = \@foo;
>>     return @foo;
>> }
>>
>> print Dump([ foo() ]);
>> print Dump($foo_ref);
>>
>> Shows that apparently @foo is deeply copied when it's returned. Is that correct?
>
> No.  But perl notices when you leave foo() that @foo has an external
> reference, so it allocates a new one in preparation for the next call
> to foo().
>
>> I'm not an expert in perl guts, but it seems there's no such thing as
>> a 'list' native structure. They're both PVAV.
>
> The return of a sub isn't a native structure, it's just a range of
> elements on a stack.  (So basically a shallow copy, but without an
> array container.)  There is no mechanism for returning a PVAV, just a
> reference to one.
>



-- 
Jerome Eteve
+44(0)7738864546
http://www.eteve.net/



More information about the london.pm mailing list