in reply to returning large arrays from functions

E.g., does perl avoid copying of data in the following cases?

No. The array is copied in both those cases.

There are two ways of avoiding that:

  1. Return an arrayref as in your second example and use it as an array ref in the calling code:
    sub large_array_ref { my $large_array_ref = []; ...populate @$large_array_ref... return $large_array_ref; } my $c = large_array_ref(); $c->[ ... ];
  2. Pass an array ref into your sub:
    sub large_array_ref { my $large_array_ref = shift; ...populate @$large_array_ref... return; } large_array_ref( \my @c ); $c[ ... ];

    With a suitably chosen name for the sub, the latter looks less awkward:

    populateThingArray( \my @c ); $c[ ... ];

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP an inspiration; A true Folk's Guy

Replies are listed 'Best First'.
Re^2: returning large arrays from functions
by LanX (Saint) on Nov 19, 2010 at 16:45 UTC
    > With a suitably chosen name for the sub, the latter looks less awkward:

    populateThingArray( \my @c ); $c[ ... ];

    as a side note, one can use the fat comma for syntactic sugar:

    calcArrays( $par1, $par2 => \ my (@a,@b) );

    Cheers Rolf

    Update: extended code to return multiple Arrays.