OptionHash - Checking of option hashes
version 0.2.2
use OptionHash; my $cat_def = ohash_define( keys => [qw< tail nose claws teeth >]); sub cat{ my %options = @_; ohash_check( $cat_def, \%options); # ... } cat( teeth => 'sharp' ); cat( trunk => 'long'); # Boom, will fail. Cats dont expect to have a trunk.
I like to pass options around in hash form because it's clear and flexible. However it can lead to sloppy mistakes when you typo the keys. OptionHash quickly checks your hashes against a definition and croaks if you've passed in bad keys.
Currently.. That's it! Simple but effective.
Define an optionhash specification, sort-of a type:
my $cat_def = ohash_define( keys => [ qw< teeth claws > ]);
Check a hash against a definition:
ohash_check( $cat_def, \%options);
If everything is okay things will proceed, otherwise ohash_check will croak (see Carp).
Generally the way to use this is to create the definition "types" at compile time in the package definition & then check against them later :
package foo; use OptionHash; my $DOG_DEF = ohash_define( keys => [ qw< nose > ]); sub build_a_dog{ my( %opts ) = @_; ohash_check($DOG_DEF, \%opts); } 1;
Params::ValidationCompiler can also validate a hash of options, and a lot more besides, so it's well worth a look. There's a lot more going on than in OptionHash which (I'd say) is a bit more focused (thus far anyway) so it's a balance between features and complexity. Had I found Params::ValidationCompiler before I wrote this I probably wouldn't have bothered to re-invent the wheel, but as I already have I'm glad I did!
Joe Higton <draxil@gmail.com>
This software is copyright (c) 2022 by Joe Higton <draxil@gmail.com>.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
To install OptionHash, copy and paste the appropriate command in to your terminal.
cpanm
cpanm OptionHash
CPAN shell
perl -MCPAN -e shell install OptionHash
For more information on module installation, please visit the detailed CPAN module installation guide.