return \@array or @array

Jérôme Étévé jerome.eteve at gmail.com
Thu Sep 12 15:33:49 BST 2013


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?

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.

J.


On 12 September 2013 15:08, Joel Bernstein <joel at fysh.org> wrote:
> You're wrong. Where you're going wrong is assuming that "return @foo" is
> going to "return an array". It returns a list of values, the same list that
> the array held in the subroutine scope.
>
> That is:
>
> sub foo {
>   my @foo = 1..100;
>   return @foo;
> }
>
> sub bar {
>   my @bar = 1..100;
>   return \@bar;
> }
>
> foo() will return a list of 99 elements.
> bar() will return a list of 1 element, which is a reference to an array
> containing 99 elements.
>
> Does that make more sense?
>
> /joel
>
>
> On 12 September 2013 16:02, Jérôme Étévé <jerome.eteve at gmail.com> wrote:
>>
>> Hi all,
>>
>> I reckon there's a popular belief going around that A is "faster" than B
>>
>> sub fA{ ... ; return \@array; }
>> sub fB{ ... ; return @array; }
>>
>> foreach my $thing ( @{fa()} ){ ... }
>> foreach my $thing ( fB() ){ ... }
>>
>> My almost blind faith in the Perl internals gives me the gut feeling
>> that as arrays are a very native Type in Perl, and the underlying AV
>> holds a reference anyway (at the end of the day, it's C..), it
>> shouldn't make much difference.
>>
>> And that building a Perl reference of something that's already a C
>> space reference isn't going to help much.
>>
>> Any insight?
>>
>> Cheers,
>>
>> Jerome.
>>
>> --
>> Jerome Eteve
>> +44(0)7738864546
>> http://www.eteve.net/
>>
>



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



More information about the london.pm mailing list