check_options - Check a hash for valid/required values.


 use CheckOptions;
 $n_errors = check_options(
   -values    => \%hash,
   -valid     => \@valid_keys,
   -required  => \@required_keys,


check_options() is a primitive function key => value checker, typically used to check whether a function was passed valid key/value pairs; there is currently no way to check the key values for validity.

check_options() returns the number of tests that failed (each required/valid option and reference type is a ``test''), after printing warning messages explaining each failed test. The function itself will print a stack trace and raise an exception if it is used with invalid arguments.


-values => values to check against
Hash reference, required. This is typically a reference to the hash that was passed to your subroutine.

-valid => keys in -values that are valid
Array reference, optional(*). Each element in the array is a valid key to the -values hash.

-required => keys in -values that are required
Array reference, optional(*). Each element in the array is a required key in the -values hash.

(*) Keys in -required are automatically added to -valid, which means that either -valid or -required is optional, but one of them must be used.

The last character of the elements in -valid and -required can be a type of reference required for that key:

% = HASH
& = CODE
  • * = GLOB
  • . = No Reference (e.g. A literal string or simple scalar.)

    If none of these characters are used, anything is accepted for that key.


     sub foo(%)
       my %args = @_;
       return 0 if check_options(
         -values   = \%args,
         -required = ['-bar%', '-baz@'],
         -valid    = [qw(-thud. -grunt)]

    In this example, foo is hopefully passed a hash which is passed to check_options as a reference (-values = \%args).

    That hash is checked to see if it has the required keys ``-bar'', which requires a hash reference to be passed to it, and ``-baz'', which requires an array reference to be passed to it.

    The optional argument ``-thud'' can't have a reference passed to it, and ``-grunt'' doesn't care what it gets.

    If any of these tests fail, foo will return false.


    If you try to pass a literal array/hash (not a reference) to check_options, it will fail in interseting ways. (The same goes for the subroutine you're using check_options in, probably.)


    Christian J. Robinson <>


    Copyright (C) March 01, 2002 Christian J. Robinson <>

    This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.