Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default argument values in subroutines

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?

like image 269
David Avatar asked Aug 22 '10 21:08

David


2 Answers

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.

like image 75
ysth Avatar answered Nov 07 '22 04:11

ysth


I usually do something like:

sub hello {
    my ($say,$to) = @_;
    $say ||= "Hello";
    $to ||= "World!";
    print "$say $to\n";
}

Note that starting from perl 5.10, you can use the "//=" operator to test if the variable is defined, and not just non-zero. (Imagine the call hello("0","friend"), which using the above would yield "Hello friend", which might not be what you wanted. Using the //= operator it would yield "0 friend").

like image 28
jsegal Avatar answered Nov 07 '22 05:11

jsegal