3

假设我有

use v5.026;
use feature 'signatures';

sub foo ($opt1, $opt2) {
  say $opt1 if $opt2;
}

main::foo(1,2);
main::foo(1);

现在我想在foo有和没有 opt2 的情况下打电话:

foo(1);    # not currently accepted
foo(1,2);  # works fine
4

2 回答 2

6

带有子例程签名的可选参数需要定义的默认值,该默认值由= default_value_expression. 您可以将其硬设置为undef

sub foo ($opt1, $opt2 = undef) {
  say $opt1 if $opt2;
}
于 2019-02-03T21:12:29.877 回答
3

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) {
于 2019-02-03T21:33:19.843 回答