存在Perl原型来修改解析器的行为,这很少需要。这也不例外。
如果“beetroot
”没有任何其他参数,那么您应该使用@_
而不是数组引用。
sub aspirin {
my @items = qw'some items in here';
return @items if wantarray; # return a list in list context
return \@items;
}
sub beetroot {
print "$_\n" for @_;
}
my $L = aspirin;
beetroot @$L;
# the follow examples require the version of aspirin from this answer
my @L = aspirin;
beetroot @L;
beetroot aspirin; # aspirin called in list context
这将带来额外的好处,即如果您只想输入元素列表,则无需解析解析器。
这适用于新版本,但不适用于问题中的版本。
beetroot qw'some items in here';
beetroot aspirin; # aspirin called in list context
为了使它与问题中的问题一起工作,您必须创建一个匿名数组。有趣的是,这也适用于这个答案中的版本。
beetroot @{ [qw'some items in here'] };
# the follow examples use the version of aspirin from this answer
beetroot @{ [aspirin] };
beetroot @{ scalar aspirin };
beetroot @{ aspirin };
如果你真的想 “beetroot
” 与数组引用工作。 我会这样写。
sub beetroot{
my($lst) = @_; # similar to my $lst = shift
print "$_\n" for @$lst;
}
my $L = aspirin;
beetroot $L;
my @L = aspirin; # using the aspirin from this answer
beetroot \@L;
beetroot [qw'some items in here'];
# the follow examples use the version of aspirin from this answer
beetroot scalar aspirin; # force aspirin to return an array reference
beetroot [ aspirin ]; # copy the array
这样,如果你想使用引用减少的Perl的内存占用,或者你有其他投入“beetroot
”我只会写。
这是“为什么99%的原因不需要原型的原因列表”中的第一项。 – 2012-01-05 13:43:42