我希望使用 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};
}
非常感謝!
(PS:如果有針對陣列的解決方案,那么也會有針對哈希的解決方案,所以我沒有在上面詳細說明。)
uj5u.com熱心網友回復:
使用簽名功能,是否可以將多個陣列傳遞給一個子程式?
是的,你可以這樣做:
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
uj5u.com熱心網友回復:
根據評論執行緒中的建議,總結一些想法:
H?kon H?gland 提出的解決方案
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);
請注意,這與傳統的 pass by ref 不同:
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);
我希望(主要是光學)這是可能的
sub test :prototype($@$@) ($a, @b, $c, @d) {};
然而,H?kon 的解決方案具有驗證的好處(并且意味著 args 被傳遞為@b而不是\@b)。
使用clarified_refs 進行改進
Diab Jerius 建議了clared_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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401301.html
