本文介绍了从 Perl 子例程返回整个数组效率低下吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在 Perl 中有一个子程序,用一些信息填充数组.由于我也习惯用 C++ 进行 hack,我发现自己经常在 Perl 中这样做,使用引用:

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";
   # ...
}

而不是更直接的版本:

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.

是吗?或者 Perl 会优化它吗?

Is that right? Or does Perl optimize that away anyway?

推荐答案

首先返回数组引用怎么样?

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

根据德曼的评论进行

也可以在函数中使用普通数组并返回对它的引用.

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;
}

这篇关于从 Perl 子例程返回整个数组效率低下吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:32