如何将从函数(如split)返回的数组转换为数组引用?

时间:2022-02-14 01:45:10

Consider this code:

考虑这段代码:

@tmp = split(/\s+/, "apple banana cherry");
$aref = \@tmp;

Besides being inelegant, the above code is fragile. Say I follow it with this line:

除了不优雅之外,上面的代码也很脆弱。假设我遵循这条线:

@tmp = split(/\s+/, "dumpling eclair fudge");

Now $$aref[1] is "eclair" instead of "banana".

现在$aref[1]是“eclair”而不是“banana”。

How can I avoid the use of the temp variable?

如何避免使用temp变量?

Conceptually, I'm thinking of something like

从概念上讲,我想的是

$aref = \@{split(/\s+/, "apple banana cherry")};

3 个解决方案

#1


19  

You could do this if you want an array-ref:

如果你想要array-ref,你可以这样做:

my $aref = [ split(/\s+/, "apple banana cherry") ];

#2


3  

I figured it out:

我想通了:

$aref = [split(/\s+/, "apple banana cherry")];

#3


2  

While I like mu's answer (and would use that approach first here), keep in mind that variables can be rather easily scoped, even without the use of functions, imagine:

虽然我喜欢mu的答案(这里将首先使用这种方法),但请记住,即使不使用函数,变量也可以很容易地确定作用域,想象一下:

my $aref = do {
  my @temp = split(/\s+/, "apple banana cherry");
  \@temp;
};
print join("-", @$aref), "\n";
# with warnings: Name "main::temp" used only once: possible typo at ...
# with strict: Global symbol "@temp" requires explicit package name at ...
print join("-", @temp), "\n";

Happy coding.

快乐的编码。

#1


19  

You could do this if you want an array-ref:

如果你想要array-ref,你可以这样做:

my $aref = [ split(/\s+/, "apple banana cherry") ];

#2


3  

I figured it out:

我想通了:

$aref = [split(/\s+/, "apple banana cherry")];

#3


2  

While I like mu's answer (and would use that approach first here), keep in mind that variables can be rather easily scoped, even without the use of functions, imagine:

虽然我喜欢mu的答案(这里将首先使用这种方法),但请记住,即使不使用函数,变量也可以很容易地确定作用域,想象一下:

my $aref = do {
  my @temp = split(/\s+/, "apple banana cherry");
  \@temp;
};
print join("-", @$aref), "\n";
# with warnings: Name "main::temp" used only once: possible typo at ...
# with strict: Global symbol "@temp" requires explicit package name at ...
print join("-", @temp), "\n";

Happy coding.

快乐的编码。