perl - Best way to check for incorrect hash key input -
in perl script, have subroutine called hundreds of times many different sets of parameters, values sent in ones differ defaults. (it goes without saying number of permutations , combinations large) make more robust, checking on parameters. here shrunken version of subroutine (the actual version has dozens of parameters specific, lengthy names):
# obtain parameters differ defaults , send processing sub importantsub { %params = ( commandtype => 5, commandid => 38, channel1enable => 0, channel2enable => 0, channel3enable => 0, channel4enable => 0, channel5enable => 0, channel6enable => 0, channel7enable => 0, channel8enable => 0, channel9enable => 0, channel10enable => 0, # goes on long time @_ ); # make sure have many keys expect - verify # no additional parameters added (real version has 92) if( keys(%params) != 92 ) { croak("unexpected parameter in hash!"); } return &$privateprocessingfunction('data path configuration', \%params); }
as can see, check see if number of values same, if sent in "chan1enable" instead of "channel1enable", throw number off.
but many calls subroutine multiple other scripts written multiple other engineers, find way find value incorrect (e.g. don't there unexpected parameter, "chan1enable" invalid). furthermore, if multiple values incorrect, i'd list of them.
what efficient way this?
(i ask efficiency since function called in on 400 different ways , continue grow application expands.)
there 2 kinds of errors: supplying unrecognized parameter, or failing supply recognized parameter. you'll have worry second issue edit list of parameters , make sure new parameters used consistently throughout application.
the best , easiest solution use hash.
my @params = qw(commandtype commandid channel1enabled ...); %copy = %params; @validation_errors = (); # required parameters present? foreach $param (@params) { if (not exists $copy{$param}) { push @validation_errors, "required param '$param' missing."; } delete $copy{$param}; } # since have delete'd recognized parameters, # left unrecognized foreach $param (keys %copy) { push @validation_errors, "unrecognized param '$param' = '$copy{$param}' in input."; } if (@validation_errors) { die "errors in input:\n", join("\n", @validation_errors); }
Comments
Post a Comment