Here is the important subset of what I have:
sub logger {
my $self = shift;
my %def = (
type => $self->{options}{name},
severity => 1,
date => $self->now(),
message => ''
);
my %opt = %def;
if ( my $ref = shift ) {
%opt = (%def, %{$ref});
}
croak('message is a required option') if $opt{message} eq '';
warn($opt{type} . ': ' . $opt{message} . "\n") if ( $self->{_verbose} );
# Do some other interesting things.
}
So then I can call it like so:
$op->logger({message => 'Some message'});
So if any of my parameters are missing, they get the defaults I’ve specified in the %def hash. If a required parameter is missing, I die.
The basis of it is I overload the def hash with what the user specified with this.
if ( my $ref = shift ) {
%opt = (%def, %{$ref});
}
Problem with this is they could specify things outside my list of options, or send in a hash instead of a hash ref, or a scalar, or undef, or many other ways this could blow up.
I’m sure there is a more elegant way to handle this.
I seem to recall some code using ref() that didn’t blow up if nothing was passed in.
Method::Signatures does precisely what you’re looking for and is so very elegant :
The colons in the signature designate named parameters (passed as a hash). The exclamation mark following
$messagemakes it required.