Default argument values in subroutines

Viewed 17491

I don't know how to set default arguments for subroutines. Here is what I considered:

sub hello {
  print @_ || "Hello world";
}

That works fine for if all you needed was one argument. How would you set default values for multiple arguments?

I was going to do this:

sub hello {
  my $say = $_[0] || "Hello";
  my $to  = $_[1] || "World!";
  print "$say $to";
}

But that's a lot of work... There must be an easier way; possibly a best practice?

9 Answers

I like this way the most: Since Perl 5.10 you can use // to check if a variable is defined or not and provide an alternative value in case it is not. So, an easy example is:

my $DEFAULT_VALUE = 42;

sub f {
    my ($p1, $p2) = @_;
    $p1 //= 'DEFAULT';
    $p2 // = $DEFAULT_VALUE;
}

Another option is using the shift instruction to get the params from @_:

sub f {
    my $p1 = shift // 'DEFAULT';
}

Source: https://perlmaven.com/how-to-set-default-values-in-perl

Related