3

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
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468

2 Answers2

6

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;
}
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • Cf. [perlsub](https://perldoc.perl.org/perlsub.html#Signatures). In particular, "A positional parameter is made optional by giving a default value". (but there are various other useful information regarding signatures) – Dada Feb 04 '19 at 13:04
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) {
Grinnz
  • 9,093
  • 11
  • 18