Default argument values in subroutines

David picture David · Aug 22, 2010 · Viewed 14.9k times · Source

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?

Answer

ysth picture ysth · Aug 23, 2010

I do it with named arguments like so:

sub hello {
    my (%arg) = (
        'foo' => 'default_foo',
        'bar' => 'default_bar',
        @_
    );

}

I believe Params::Validate supports default values, but that's more trouble than I like to take.