Reputation: 1
Let's say I have
use v5.026;
use feature 'signatures';
sub foo ($opt1, $opt2) {
say $opt1 if $opt2;
}
main::foo(1,2);
main::foo(1);
Now I want to call foo
with and without opt2:
foo(1); # not currently accepted
foo(1,2); # works fine
Upvotes: 3
Views: 546
Reputation: 9231
You can also allow any number of optional parameters by ending the signature with an array, which will slurp any remaining arguments and also allows no values, like normal array assignment.
sub foo ($opt1, @opts) {
Upvotes: 3
Reputation: 1
Optional parameters with subroutine signatures require a defined default which is done with = default_value_expression
. You can hard set this to undef
:
sub foo ($opt1, $opt2 = undef) {
say $opt1 if $opt2;
}
Upvotes: 6