return \@array or @array

Daniel de Oliveira Mantovani daniel.oliveira.mantovani at gmail.com
Thu Sep 12 18:05:13 BST 2013


On 12 September 2013 13:05, Jérôme Étévé <jerome.eteve at gmail.com> wrote:
> 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.


Because you are dumb like a stone,
[admin at localhost ~]$ time perl -E 'sub f {@a=1..9999999;return \@a}@b=f();'

real    0m1.802s
user    0m1.433s
sys    0m0.364s
[admin at localhost ~]$ time perl -E 'sub f {@a=1..9999999;return @a}@b=f();'

real    0m3.331s
user    0m2.695s
sys    0m0.621s


>
> 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/
>



-- 

-dom

--

Daniel de Oliveira Mantovani
Business Analytic Specialist
Perl Evangelist /Astrophysics hobbyist.
+55 11 9 8538-9897
XOXO



More information about the london.pm mailing list