Subroutines & signatures
where constraints
FullNarrow a parameter with a predicate — a value must be the right type and satisfy the test.
A where clause attaches a predicate to a parameter, so a value must both be of the right type and satisfy the test. An argument that fails the predicate is rejected, so the routine never runs with a bad value.
A constrained parameter #
sub f(Int $n where * > 0) {
$n * 2;
}
say f(5);
Output
10The predicate can be any expression — where *.chars > 3, where * %% 2, or a literal value.
sub g($s where *.chars > 3) {
"ok: $s";
}
say g("hello");
Output
ok: helloA failing argument is rejected #
An argument that fails the predicate causes the call to fail — no candidate matches — so try catches it and the fallback runs.
sub pos(Int $n where * > 0) { $n }
say (try pos(-1)) // "rejected";
Output
rejectedpos(-1) fails the * > 0 check, so the value never reaches the body.