存在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