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?
Show activity on this post. sub findLines { ... return @list; # Returns array @list } my @results = findLines(); # or sub findLines { ... return \@list; # returns a reference to array @list } my $resultsRef = findLines();
It is really easy to return multiple values from a subroutine in Perl. One just needs to pass the values to the return statement.
Perl provides a return statement which can be used to exit a function, and provide a value when a function call is evaluated. In the absence of a return statement, the value of a function call will be the last expression which was evaluated in the body of the function.
What about returning an array reference in the first place?
sub getInfo {
my $array_ref = [];
push @$array_ref, 'foo';
# ...
return $array_ref;
}
my $a_ref = getInfo();
# or if you want the array expanded
my @array = @{getInfo()};
Edit according to dehmann's comment:
It's also possible to use a normal array in the function and return a reference to it.
sub getInfo {
my @array;
push @array, 'foo';
# ...
return \@array;
}
Passing references is more efficient, but the difference is not as big as in C++. The argument values themselves (that means: the values in the array) are always passed by reference anyway (returned values are copied though).
Question is: does it matter? Most of the time, it doesn't. If you're returning 5 elements, don't bother about it. If you're returning/passing 100'000 elements, use references. Only optimize it if it's a bottleneck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With