Subject: | Policy suggestion: Require croak/die when getting wrong number of args |
I don't know how to write Perl::Critic policies, so I'm submitting this
suggestion here.
Many methods and subroutines take key/value pairs as arguments. It feels
natural, then, to write something like this:
sub new {
my ($package, %args) = @_;
# check if some mandatory args are missing, etc
return bless \%args, $package;
}
However, if the user of this code supplies an odd number of arguments to
new(), it will only generate a warning at run-time. A better practice
would be to croak() or die() when receiving an odd number of arguments,
like so:
sub new {
my ($package) = shift;
croak "$package requires an even number of arguments" if @_ & 1;
my %args = @_;
# check if some mandatory args are missing, etc
return bless \%args, $package;
}
I would propose checking if there is a hash on the left-hand side when
assigning from @_ in a subroutine where the number of elements in @_ has
not been checked beforehand.