我希望使用Perl 5中的签名特性(例如5.34.0版本),这样的功能是可能的:
use feature qw{ say signatures };
&test(1, (2,3,4), 5, (6,7,8));
sub test :prototype($@$@) ($a, @b, $c, @d) {
say "c=$c";
};也许是这样的:
sub test :prototype($\@$@) ($a, \@b, $c, @d) {
}(如这里所示:https://www.perlmonks.org/?node_id=11109414)。
然而,我未能做到这一点。我的问题是:有了签名特性,是否有可能将多个数组传递给子例程?
或者:即使有签名,也是通过引用传递数组的唯一方法吗?这就是说:除了引用以外,是否有任何替代办法,例如:
sub test($a, $b, $c, @d) {
my @b = @{$b};
}非常感谢!
(P.S.:如果有数组的解决方案,那么也会有散列的解决方案,所以我没有在上面详细说明。)
发布于 2022-01-02 14:35:49
带有签名特性的
,是否可以将多个数组传递给子例程?
是的,你可以这样做:
use v5.22.0; # experimental signatures requires perl >= 5.22
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures);
sub test :prototype($\@$\@) ($a, $b, $c, $d) {
say "c=$c";
}
my @q = (2,3,4);
my @r = (6,7,8);
test(1, @q, 5, @r);输出
c=5发布于 2022-01-02 19:47:57
根据评论文章中的建议,在一个单独的答案中总结其中的一些想法:
H kon H腺体提出的解决方案
sub test :prototype($\@$\@) ($a, $b, $c, $d) {
say "c=$c";
say @$b;
}
my @q = (2,3,4);
my @r = (6,7,8);
test(1, @q, 5, @r);通常按引用传递的
请注意,这与传统的引用传递不同:
my @q = (2,3,4);
my @r = (6,7,8);
sub test1 :prototype($$$$) ($a, $b, $c, $d) {
say "c=$c";
say @$b;
}
test1(1, \@q, 5, \@r);H kon的解决方案具有验证的优点(并且意味着args作为@b而不是\@b传递)。
用declared_refs进行改进
Diab建议使用declared_refs,它提供了其他语法:
use v5.22.0;
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures declared_refs);
sub test :prototype($\@$\@) ($a, $b, $c, $d) {
say "c=$c";
say @$b;
my \@bb = $b;
say @bb;
}我(原版海报)所希望的。
我希望(主要是用于光学)这是可能的。
sub test :prototype($@$@) ($a, @b, $c, @d) {
say @b;
};https://stackoverflow.com/questions/70556414
复制相似问题