in reply to Re^2: Confused as to why the "casting context" is mis-behaving ("list vs array", again)
in thread Confused as to why the "casting context" is mis-behaving
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Confused as to why the "casting context" is mis-behaving (return array)
by andal (Hermit) on Oct 25, 2010 at 08:39 UTC | |
by tye (Sage) on Oct 25, 2010 at 13:27 UTC | |
by andal (Hermit) on Oct 26, 2010 at 09:34 UTC | |
by tye (Sage) on Oct 27, 2010 at 05:31 UTC | |
by andal (Hermit) on Oct 27, 2010 at 09:03 UTC | |
|