This is not 100% correct. The array is returned from the function. But to get a hold of it, you should COPY it somewhere.

No, the array is copied before the function returns. You can observe that:

my @a= ( 'a' .. 'e' ); sub returnArray { return @a; } my @b= ( 'v' .. 'z' ); for( returnArray() ) { $_ .= '?' } for( @b ) { $_ .= '!' } print "@a\n"; print "@b\n"; __END__ a b c d e v! w! x! y! z!

And it is also not true that the function returns and then (after that) the scalar context decides to get the size of the array while the list context decides to copy the elements of the array.

The context gets passed in to the function, to the returning statement so that it can, when possible, avoid the work of creating a whole list of values just to throw that list away.

The method of returning information from a Perl function is to push zero or more scalar values onto the stack. return @array;, if called in a list context, loops over the array and pushes onto the stack, a copy of each element of the array. If you assign the return value to an array, then that assignment operator loops over the items on the stack and puts them into the array (whether each value is copied again here or the array just gets aliases to each of the original copies is an implementation detail and a matter of optimization that I have never needed to worry about).

- tye        


In reply to Re^3: Confused as to why the "casting context" is mis-behaving (return array) by tye
in thread Confused as to why the "casting context" is mis-behaving by kiz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.