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 references:
my @array; getInfo(\@array); sub getInfo { my ($arrayRef) = @_; push @$arrayRef, 'obama'; # ... }
instead of the more straightforward version:
my @array = getInfo(); sub getInfo { my @array; push @array, 'obama'; # ... return @array; }
The reason, of course, is that I don’t want the array to be created locally in the subroutine and then copied on return.
Is that right? Or does Perl optimize that away anyway?
What about returning an array reference in the first place?
Edit according to dehmann’s comment:
It’s also possible to use a normal array in the function and return a reference to it.