Reputation: 42421
I'm looking for a general-purpose module to take the drudgery out of validating subroutine and method arguments. I've scanned through various possibilities on CPAN: Params::Validate
, Params::Smart
, Getargs::Mixed
, Getargs::Long
, and a few others.
Any information regarding pros and cons of these or other modules would be appreciated. Thanks.
Upvotes: 10
Views: 1369
Reputation: 22570
Have a look at MooseX::Method::Signatures which provides a bit more than just validating the arguments.
Example from POD:
package Foo;
use Moose;
use MooseX::Method::Signatures;
method morning (Str $name) {
$self->say("Good morning ${name}!");
}
method hello (Str :$who, Int :$age where { $_ > 0 }) {
$self->say("Hello ${who}, I am ${age} years old!");
}
method greet (Str $name, Bool :$excited = 0) {
if ($excited) {
$self->say("GREETINGS ${name}!");
}
else {
$self->say("Hi ${name}!");
}
}
MooseX::Method::Signatures also comes as standard with MooseX::Declare which brings even more sexy syntax to the Perl plate. The above could be written like so (just showing first method for brevity):
use MooseX::Declare;
class Foo {
method morning (Str $name) {
$self->say("Good morning ${name}!");
}
}
There is also a corollary signatures CPAN module for plain subroutines but unfortunately it isn't as feature rich as above.
Upvotes: 5
Reputation: 9303
I am currently researching the same question as the O.P.
I noticed that Dave Rolsky - hyper-productive programmer of Moose fame - has recently (2009) taken over maintenance of Params::Validate, so I think this a good sign. The module has not been upgraded since 2003. So I guess, it still can be used again for checking subroutine params.
Upvotes: 2
Reputation: 1
If you start to use Moose
, you'll find MooseX::Types
to your liking. Types automatically have an is_$type(), and to_$type(). These are for making sure you input passes type constraints, or making your input has a valid coercion to the type. I like them better even for these types of things because you can ensure the state of your object has the said types at no additional cost.
use Moose;
has 'foo' => ( isa => MyType, is => ro );
sub _check_my_type {
my ( $self, $type ) = @_;
is_MyType( $type );
};
It might be lacking some support for deep/recursive types, but if your using this stuff in modern perl you're probably "doing it wrong." Instead use an object that has its own consistency checks (like mine above with MyType), and just pass the object.
Upvotes: 6