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?
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.
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"
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With