如何在Perl中将列表作为数组引用返回?

0x8*_*x89 2 perl reference

嘿.在Python中我可以这样做:

def fnuh():
    a = "foo"
    b = "bar"
    return a,b
Run Code Online (Sandbox Code Playgroud)

我可以在perl中以类似优雅的方式返回一个列表,特别是当子例程的返回类型应该是对数组的引用时?

我知道我能做到

sub fnuh {
    my $a = "foo";
    my $b = "bar";
    my $return = [];
    push (@{$return}, $a);
    push (@{$return}, $b);
    return $return;
}
Run Code Online (Sandbox Code Playgroud)

但我敢打赌,在Perl中有更好的方法.你知道吗?

Eth*_*her 8

当然,只需\在列表前面敲击一个以返回引用.

或者用一个新的arrayref [ list elements ].

在你的例子中,

sub f1 {
    my $a = "foo";
    my $b = "bar";
    return [ $a, $b ];
}

sub f2 {
    my $a = "foo";
    my $b = "bar";
    push @return, $a, $b;
    return \@return;
}
Run Code Online (Sandbox Code Playgroud)

有关参考文献的更多信息,请参阅perldoc perlreftutperldoc perlref.perldoc perldsc还有一个数据结构食谱.

您可能还想在perlfaq中阅读这个问题(感谢brian):"列表和数组之间有什么区别?"

  • 第二种方式你肯定想用`my`声明`@ return`,否则它变得全局不太好. (6认同)
  • "#自动返回最后一个表达式;不需要明确" - 对此,我更喜欢python.从"蟒蛇的禅",第二个陈述:明确比隐含更好.所以我更喜欢:返回[$ a,$ b]; (2认同)
  • 我更喜欢总是做出明确的回报.添加一点清晰度没有错.特别是在Perl.:) (2认同)

Eri*_*rom 6

Python自动打包和解包模拟列表的赋值周围的元组.在Perl中,您可以以相同的方式编写它,返回一个列表.

sub fnuh {
    my $a = 'foo';
    my $b = 'bar';
    $a, $b
}
Run Code Online (Sandbox Code Playgroud)

然后使用结果:

my ($x, $y) = fnuh;
Run Code Online (Sandbox Code Playgroud)

或者如果您需要参考:

my $ref = [ fnuh ];
Run Code Online (Sandbox Code Playgroud)