$aref = \@array;
$aref = [ @array ];
1. $aref becomes a pointer to the @array
2. then $aref is reassigned as pointer to a "deep copy" of the @array in a new hunk of memory.
"@array" is not "abandoned", that memory and the original @array can be accessed by the name @array.
Perl uses reference counting when deciding to "free" memory. If you want to "free" @array, then @array=(); would do it provided that there aren't any other things like $aref2 = \@array hanging around out there. Maybe this point is too detailed here, but Perl never gives memory back to the OS. If you watch a long lived Perl process run, it will grow in size and approach a max size. It will never get smaller. So to be more specific, when Perl "frees" memory that means that memory can be recycled and reused by Perl itself, not the OS.
This construct with square brackets $ref=[ 1, 2, 3] always allocates memory with "no name", an anonymous array.
So,return[@something] returns a reference to a hunk of memory. If all you do with the return value is use the $ref (and don't make copies of that ref), then the second time you run the sub{}, then at the end of the day, that original anon memory will get "recycled", ie, this is not a memory leak.
When I said "why bother?", that meant that putting this sort into a sub{} won't save any memory, nor will it increase efficiency. Just use the "one liner". I showed how to pass a ref to the a sub that sorts. If you want a sub that sorts, and intent is to modify the original array, this is the way to do it (no return value from the sub). I hope its clear that NO return value is faster than having a return value! This doesn't save any time either, actually slightly slower as the de-referencing takes some time. These Perl functions like sort{}, foreach(keys %hash) are very optimized. Try to use the idiomatic language constructs and some of them like the REGEX engine have become significantly faster between releases. |