我在Perl中有这段代码:
sub f {
return [1,2,3]
}
print f;
函数f
返回对数组的引用,如何在没有附加变量的情况下将返回值转换为数组,就像这里一样?
sub f {
return [1,2,3]
}
$a = f;
print @$a;
答案 0 :(得分:10)
你只是想这样做吗?
print @{ f() };
您可以取消引用任何返回引用的内容。它不一定是变量。它甚至可以是很多代码:
print @{ @a = grep { $_ % 2 } 0 .. 10; \@a };
Perl v5.20 adds an experimental post dereference:
print f()->@*
答案 1 :(得分:2)
sub f {
my @return = 1..3;
return @return if wantarray;
return \@return;
# if you want to return a copy of an array:
# return [@return];
}
say f; # list context => wantarray == 1
say scalar f; # scalar context => wantarray == 0
f(); # void context => wantarray == undef
123 ARRAY(0x9238880)
my $a_s = f; # scalar
my($a_l) = f; # list
my @b_l = f; # list
my @b_s = scalar f; # scalar
my %c_l = f; # list
my %c_s = scalar f; # scalar
$a_s == [ 1..3 ];
$a_l == 1;
@b_l == ( 1..3 );
@b_s == ( [ 1..3 ] );
%c_l == ( 1 => 2, 3 => undef );
%c_s == ( ARRAY(0x9238880) => undef );
注意:这是Perl6子程序处理标量/列表上下文的方式