In Perl, if I want to use named parameters in an object constructor, my code seems a bit clumsy if I wish to have some validation.
sub new {
my $class = shift;
my $self = {};
my %args = @_;
foreach my $argname (keys %args) {
if ($argname eq 'FOO') { $self->{$argname} = $args{$argname}; }
elsif ($argname eq 'BAR') { $self->{$argname} = $args{$argname}; }
elsif ($argname eq 'BAZ') { $self->{$argname} = $args{$argname}; }
…
else { die "illegal argument $argname\n"; }
}
bless $self;
return $self;
}
Firstly it seems a bit clumsy to have a temporary hash (%args
). Secondly the whole if
chain seems verbose and tedious.
The latter can be simplified to
if ('-FOO-BAR-BAZ-'=~m/-$argname-/) { $self->{$argname} = $args{$argname} }
else { die "..."; }
but I imagine this can be improved.
If I need to check values, the if … elsif
chain is still necessary?
I've searched a little but cannot find a better idiom. Is there one (other than using a Perl OO framework of some sort)