Capture 的定義:
class Capture does Positional does Associative { }
Capture 是一個(gè)用于給 code 對(duì)象傳遞參數(shù)的容器。Captures 是簽名的另一面 — Captures 在調(diào)用方定義實(shí)參, 而簽名(Signatures) 在被調(diào)用方定義形式參數(shù)。
當(dāng)你調(diào)用 print $a, $b
時(shí), $a, $b
這部分就是一個(gè) Capture碉纺。$a, $b
在這兒是實(shí)參。
Captures 包含一個(gè) list-like 部分的位置參數(shù)和一個(gè) hash-like 部分的具名參數(shù)。對(duì)于具名參數(shù), Captures 使用一種略微不同的語(yǔ)法而不是普通的 List介粘。有兩種簡(jiǎn)單的方法生成一個(gè)具名參數(shù):
- 使用一個(gè)未引起的鍵命名一個(gè)形參, 后面跟著
=>
, 然后跟著參數(shù) - 使用以形參命名的冒號(hào)對(duì)兒字面量
say unique 1, -2, 2, 3, as => { abs $_ }; # 1, -2, 3
# ... is the same thing as:
say unique 1, -2, 2, 3, :as({ abs $_ }); # 1, -2, 3
# Be careful not to quote the name of a named parameter:
say unique 1, -2, 2, 3, 'as' => { abs $_ }; # 1, -2, 2, 3, "as" => { ... }
單個(gè)獨(dú)立的 Capture 也能被生成, 存儲(chǔ), 然后供之后使用姻采。 在項(xiàng)(term)那兒前置一個(gè)反斜線 \
能生成一個(gè)字面的 Capture刑棵。通常, 這個(gè) term 會(huì)是一個(gè) terms 的列表, 在這個(gè)列表里面, 任何 Pair 字面值會(huì)被放在 Capture 的具名部分, 而其它 terms 會(huì)被放在Capture 的位置(positional) 部分碍舍。
my $c = \(42); # 帶有一個(gè) positional 部分的 Capture
$c = \(1, 2, a => 'b'); # 帶有兩個(gè) positional 部分和一個(gè)具名部分的 Capture
要使用這樣的 Capture, 在函數(shù)調(diào)用里你可以在這個(gè) Capture 前面使用 |
, 那么它看起來(lái)會(huì)像這個(gè) Capture 中的所有值都被作為實(shí)參直接傳遞這個(gè)函數(shù)了 — 具名參數(shù)作為具名參數(shù)傳遞, 而位置參數(shù)會(huì)作為位置參數(shù)傳遞。 只要你愿意, 你可以重用這個(gè) Capture 任意次, 甚至使用不同的函數(shù)呐伞。
my $c = \(4,2,3);
reverse(|$c).say; # 3 2 4
sort(5,|$c).say; # 2 3 4 5
在簽名( Signature) 里面, 可以在不含符號(hào)的形參那兒前置一個(gè)豎線 |
來(lái)創(chuàng)建一個(gè) Capture伶氢。這會(huì)把余下的參數(shù)列表打包到那個(gè)形參中:
sub f($a, |c) {
say c;
}
f(1, 2, 3, a => 4, b => 5); # c is \(2, 3, a => 4, b => 5)
請(qǐng)注意,Capture 仍然是列表瘪吏,因?yàn)樗鼈兛赡馨萜餮⒎溃恢皇侵?
my $b = 1;
my $c = \(4,2,$b,3);
sort(|$c).say; # 1 2 3 4
$b = 6;
sort(|$c).say; # 2 3 4 6