Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a whole array from a Perl subroutine inefficient?

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?

like image 916
Frank Avatar asked Feb 13 '09 14:02

Frank


People also ask

How do I return an array from a subroutine in Perl?

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();

Can you return multiple values in Perl?

It is really easy to return multiple values from a subroutine in Perl. One just needs to pass the values to the return statement.

What is return in Perl?

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.


2 Answers

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;
}      
like image 54
user55400 Avatar answered Sep 21 '22 03:09

user55400


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.

like image 28
Leon Timmermans Avatar answered Sep 18 '22 03:09

Leon Timmermans