I often have a subroutine in Perl that fills an array with some information. Since I\'m also used to hacking in C++, I find myself often do it like this in Perl, using refer
If I look at your example and think about what you want to do I'm used to write it in this manner:
sub getInfo {
my @array;
push @array, 'obama';
# ...
return \@array;
}
It seems to me as straightforward version when I need return large amount of data. There is not need to allocate array outside sub
as you written in your first code snippet because my
do it for you. Anyway you should not do premature optimization as Leon Timmermans suggest.
To answer the final rumination, no, Perl does not optimize this away. It can't, really, because returning an array and returning a scalar are fundamentally different.
If you're dealing with large amounts of data or if performance is a major concern, then your C habits will serve you well - pass and return references to data structures rather than the structures themselves so that they won't need to be copied. But, as Leon Timmermans pointed out, the vast majority of the time, you're dealing with smaller amounts of data and performance isn't that big a deal, so do it in whatever way seems most readable.