home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / State.pm < prev    next >
Encoding:
Perl POD Document  |  2004-02-04  |  45.5 KB  |  1,414 lines

  1. #============================================================================
  2. #
  3. # AppConfig::State.pm
  4. #
  5. # Perl5 module in which configuration information for an application can
  6. # be stored and manipulated.  AppConfig::State objects maintain knowledge 
  7. # about variables; their identities, options, aliases, targets, callbacks 
  8. # and so on.  This module is used by a number of other AppConfig::* modules.
  9. #
  10. # Written by Andy Wardley <abw@wardley.org>
  11. #
  12. # Copyright (C) 1997-2003 Andy Wardley.  All Rights Reserved.
  13. # Copyright (C) 1997,1998 Canon Research Centre Europe Ltd.
  14. #
  15. # $Id: State.pm,v 1.61 2004/02/04 10:11:23 abw Exp $
  16. #
  17. #----------------------------------------------------------------------------
  18. #
  19. # TODO
  20. #
  21. # * Change varlist() to varhash() and provide another varlist() method
  22. #   which returns a list.  Multiple parameters passed implies a hash 
  23. #   slice/list grep, a single parameter should indicate a regex.
  24. #
  25. # * Perhaps allow a callback to be installed which is called *instead* of 
  26. #   the get() and set() methods (or rather, is called by them).
  27. #
  28. # * Maybe CMDARG should be in there to specify extra command-line only 
  29. #   options that get added to the AppConfig::GetOpt alias construction, 
  30. #   but not applied in config files, general usage, etc.  The GLOBAL 
  31. #   CMDARG might be specified as a format, e.g. "-%c" where %s = name, 
  32. #   %c = first character, %u - first unique sequence(?).  Will 
  33. #   GetOpt::Long handle --long to -l application automagically?
  34. #
  35. # * ..and an added thought is that CASE sensitivity may be required for the
  36. #   command line (-v vs -V, -r vs -R, for example), but not for parsing 
  37. #   config files where you may wish to treat "Name", "NAME" and "name" alike.
  38. #
  39. #============================================================================
  40.  
  41. package AppConfig::State;
  42.  
  43. require 5.004;
  44.  
  45. use strict;
  46. use vars qw( $VERSION $AUTOLOAD $DEBUG );
  47.  
  48. # need access to AppConfig::ARGCOUNT_*
  49. use AppConfig qw(:argcount);
  50.  
  51. $VERSION = sprintf("%d.%02d", q$Revision: 1.61 $ =~ /(\d+)\.(\d+)/);
  52. $DEBUG   = 0;
  53.  
  54. # internal per-variable hashes that AUTOLOAD should provide access to
  55. my %METHVARS;
  56.    @METHVARS{ qw( EXPAND ARGS ARGCOUNT ) } = ();
  57.  
  58. # internal values that AUTOLOAD should provide access to
  59. my %METHFLAGS;
  60.    @METHFLAGS{ qw( PEDANTIC ) } = ();
  61.  
  62. # variable attributes that may be specified in GLOBAL;
  63. my @GLOBAL_OK = qw( DEFAULT EXPAND VALIDATE ACTION ARGS ARGCOUNT );
  64.  
  65.  
  66. #------------------------------------------------------------------------
  67. # new(\%config, @vars)
  68. #
  69. # Module constructor.  A reference to a hash array containing 
  70. # configuration options may be passed as the first parameter.  This is 
  71. # passed off to _configure() for processing.  See _configure() for 
  72. # information about configurarion options.  The remaining parameters
  73. # may be variable definitions and are passed en masse to define() for
  74. # processing.
  75. #
  76. # Returns a reference to a newly created AppConfig::State object.
  77. #------------------------------------------------------------------------
  78.  
  79. sub new {
  80.     my $class = shift;
  81.     
  82.     my $self = {
  83.         # internal hash arrays to store variable specification information
  84.         VARIABLE   => { },     # variable values
  85.         DEFAULT    => { },     # default values
  86.         ALIAS      => { },     # known aliases  ALIAS => VARIABLE
  87.         ALIASES    => { },     # reverse alias lookup VARIABLE => ALIASES
  88.         ARGCOUNT   => { },     # arguments expected
  89.         ARGS       => { },     # specific argument pattern (AppConfig::Getopt)
  90.         EXPAND     => { },     # variable expansion (AppConfig::File)
  91.         VALIDATE   => { },     # validation regexen or functions
  92.         ACTION     => { },     # callback functions for when variable is set
  93.         GLOBAL     => { },     # default global settings for new variables
  94.         
  95.         # other internal data
  96.         CREATE     => 0,       # auto-create variables when set
  97.         CASE       => 0,       # case sensitivity flag (1 = sensitive)
  98.         PEDANTIC   => 0,       # return immediately on parse warnings
  99.         EHANDLER   => undef,   # error handler (let's hope we don't need it!)
  100.         ERROR      => '',      # error message
  101.     };
  102.  
  103.     bless $self, $class;
  104.     
  105.     # configure if first param is a config hash ref
  106.     $self->_configure(shift)
  107.         if ref($_[0]) eq 'HASH';
  108.  
  109.     # call define(@_) to handle any variables definitions
  110.     $self->define(@_)
  111.         if @_;
  112.  
  113.     return $self;
  114. }
  115.  
  116.  
  117. #------------------------------------------------------------------------
  118. # define($variable, \%cfg, [$variable, \%cfg, ...])
  119. #
  120. # Defines one or more variables.  The first parameter specifies the 
  121. # variable name.  The following parameter may reference a hash of 
  122. # configuration options for the variable.  Further variables and 
  123. # configuration hashes may follow and are processed in turn.  If the 
  124. # parameter immediately following a variable name isn't a hash reference 
  125. # then it is ignored and the variable is defined without a specific 
  126. # configuration, although any default parameters as specified in the 
  127. # GLOBAL option will apply.
  128. #
  129. # The $variable value may contain an alias/args definition in compact
  130. # format, such as "Foo|Bar=1".  
  131. #
  132. # A warning is issued (via _error()) if an invalid option is specified.
  133. #------------------------------------------------------------------------
  134.  
  135. sub define {
  136.     my $self = shift;
  137.     my ($var, $args, $count, $opt, $val, $cfg, @names);
  138.  
  139.     while (@_) {
  140.         $var = shift;
  141.         $cfg = ref($_[0]) eq 'HASH' ? shift : { };
  142.  
  143.         # variable may be specified in compact format, 'foo|bar=i@'
  144.         if ($var =~ s/(.+?)([!+=:].*)/$1/) {
  145.  
  146.             # anything coming after the name|alias list is the ARGS
  147.             $cfg->{ ARGS } = $2
  148.                 if length $2;
  149.         }
  150.  
  151.         # examine any ARGS option
  152.         if (defined ($args = $cfg->{ ARGS })) {
  153.           ARGGCOUNT: {
  154.               $count = ARGCOUNT_NONE, last if $args =~ /^!/;
  155.               $count = ARGCOUNT_LIST, last if $args =~ /@/;
  156.               $count = ARGCOUNT_HASH, last if $args =~ /%/;
  157.               $count = ARGCOUNT_ONE;
  158.           }
  159.             $cfg->{ ARGCOUNT } = $count;
  160.         }
  161.  
  162.         # split aliases out
  163.         @names = split(/\|/, $var);
  164.         $var = shift @names;
  165.         $cfg->{ ALIAS } = [ @names ] if @names;
  166.  
  167.         # variable name gets folded to lower unless CASE sensitive
  168.         $var = lc $var unless $self->{ CASE };
  169.  
  170.         # activate $variable (so it does 'exist()') 
  171.         $self->{ VARIABLE }->{ $var } = undef;
  172.  
  173.         # merge GLOBAL and variable-specific configurations
  174.         $cfg = { %{ $self->{ GLOBAL } }, %$cfg };
  175.  
  176.         # examine each variable configuration parameter
  177.         while (($opt, $val) = each %$cfg) {
  178.             $opt = uc $opt;
  179.             
  180.             # DEFAULT, VALIDATE, EXPAND, ARGS and ARGCOUNT are stored as 
  181.             # they are;
  182.             $opt =~ /^DEFAULT|VALIDATE|EXPAND|ARGS|ARGCOUNT$/ && do {
  183.                 $self->{ $opt }->{ $var } = $val;
  184.                 next;
  185.             };
  186.             
  187.             # CMDARG has been deprecated
  188.             $opt eq 'CMDARG' && do {
  189.                 $self->_error("CMDARG has been deprecated.  "
  190.                               . "Please use an ALIAS if required.");
  191.                 next;
  192.             };
  193.             
  194.             # ACTION should be a code ref
  195.             $opt eq 'ACTION' && do {
  196.                 unless (ref($val) eq 'CODE') {
  197.                     $self->_error("'$opt' value is not a code reference");
  198.                     next;
  199.                 };
  200.                 
  201.                 # store code ref, forcing keyword to upper case
  202.                 $self->{ ACTION }->{ $var } = $val;
  203.                 
  204.                 next;
  205.             };
  206.             
  207.             # ALIAS creates alias links to the variable name
  208.             $opt eq 'ALIAS' && do {
  209.                 
  210.                 # coerce $val to an array if not already so
  211.                 $val = [ split(/\|/, $val) ]
  212.                     unless ref($val) eq 'ARRAY';
  213.                 
  214.                 # fold to lower case unless CASE sensitivity set
  215.                 unless ($self->{ CASE }) {
  216.                     @$val = map { lc } @$val;
  217.                 }
  218.                 
  219.                 # store list of aliases...
  220.                 $self->{ ALIASES }->{ $var } = $val;
  221.                 
  222.                 # ...and create ALIAS => VARIABLE lookup hash entries
  223.                 foreach my $a (@$val) {
  224.                     $self->{ ALIAS }->{ $a } = $var;
  225.                 }
  226.                 
  227.                 next;
  228.             };
  229.             
  230.             # default 
  231.             $self->_error("$opt is not a valid configuration item");
  232.         }
  233.         
  234.         # set variable to default value
  235.         $self->_default($var);
  236.         
  237.         # DEBUG: dump new variable definition
  238.         if ($DEBUG) {
  239.             print STDERR "Variable defined:\n";
  240.             $self->_dump_var($var);
  241.         }
  242.     }
  243. }
  244.  
  245.  
  246. #------------------------------------------------------------------------
  247. # get($variable)
  248. #
  249. # Returns the value of the variable specified, $variable.  Returns undef
  250. # if the variable does not exists or is undefined and send a warning
  251. # message to the _error() function.
  252. #------------------------------------------------------------------------
  253.  
  254. sub get {
  255.     my $self     = shift;
  256.     my $variable = shift;
  257.     my $negate   = 0;
  258.     my $value;
  259.  
  260.     # _varname returns variable name after aliasing and case conversion
  261.     # $negate indicates if the name got converted from "no<var>" to "<var>"
  262.     $variable = $self->_varname($variable, \$negate);
  263.  
  264.     # check the variable has been defined
  265.     unless (exists($self->{ VARIABLE }->{ $variable })) {
  266.         $self->_error("$variable: no such variable");
  267.         return undef;
  268.     }
  269.  
  270.     # DEBUG
  271.     print STDERR "$self->get($variable) => ", 
  272.        defined $self->{ VARIABLE }->{ $variable }
  273.           ? $self->{ VARIABLE }->{ $variable }
  274.           : "<undef>",
  275.       "\n"
  276.           if $DEBUG;
  277.  
  278.     # return variable value, possibly negated if the name was "no<var>"
  279.     $value = $self->{ VARIABLE }->{ $variable };
  280.  
  281.     return $negate ? !$value : $value;
  282. }
  283.  
  284.  
  285. #------------------------------------------------------------------------
  286. # set($variable, $value)
  287. #
  288. # Assigns the value, $value, to the variable specified.
  289. #
  290. # Returns 1 if the variable is successfully updated or 0 if the variable 
  291. # does not exist.  If an ACTION sub-routine exists for the variable, it 
  292. # will be executed and its return value passed back.
  293. #------------------------------------------------------------------------
  294.  
  295. sub set {
  296.     my $self     = shift;
  297.     my $variable = shift;
  298.     my $value    = shift;
  299.     my $negate   = 0;
  300.     my $create;
  301.  
  302.     # _varname returns variable name after aliasing and case conversion
  303.     # $negate indicates if the name got converted from "no<var>" to "<var>"
  304.     $variable = $self->_varname($variable, \$negate);
  305.  
  306.     # check the variable exists
  307.     if (exists($self->{ VARIABLE }->{ $variable })) {
  308.         # variable found, so apply any value negation
  309.         $value = $value ? 0 : 1 if $negate;
  310.     }
  311.     else {
  312.         # auto-create variable if CREATE is 1 or a pattern matching 
  313.         # the variable name (real name, not an alias)
  314.         $create = $self->{ CREATE };
  315.         if (defined $create
  316.             && ($create eq '1' || $variable =~ /$create/)) {
  317.             $self->define($variable);
  318.             
  319.             print STDERR "Auto-created $variable\n" if $DEBUG;
  320.         }
  321.         else {
  322.             $self->_error("$variable: no such variable");
  323.             return 0;
  324.         }
  325.     }
  326.     
  327.     # call the validate($variable, $value) method to perform any validation
  328.     unless ($self->_validate($variable, $value)) {
  329.         $self->_error("$variable: invalid value: $value");
  330.         return 0;
  331.     }
  332.     
  333.     # DEBUG
  334.     print STDERR "$self->set($variable, ", 
  335.     defined $value
  336.         ? $value
  337.         : "<undef>",
  338.         ")\n"
  339.         if $DEBUG;
  340.     
  341.  
  342.     # set the variable value depending on its ARGCOUNT
  343.     my $argcount = $self->{ ARGCOUNT }->{ $variable };
  344.     $argcount = AppConfig::ARGCOUNT_ONE unless defined $argcount;
  345.  
  346.     if ($argcount eq AppConfig::ARGCOUNT_LIST) {
  347.         # push value onto the end of the list
  348.         push(@{ $self->{ VARIABLE }->{ $variable } }, $value);
  349.     }
  350.     elsif ($argcount eq AppConfig::ARGCOUNT_HASH) {
  351.         # insert "<key>=<value>" data into hash 
  352.         my ($k, $v) = split(/\s*=\s*/, $value, 2);
  353.         # strip quoting
  354.         $v =~ s/^(['"])(.*)\1$/$2/ if defined $v;
  355.         $self->{ VARIABLE }->{ $variable }->{ $k } = $v;
  356.     }
  357.     else {
  358.         # set simple variable
  359.         $self->{ VARIABLE }->{ $variable } = $value;
  360.     }
  361.  
  362.  
  363.     # call any ACTION function bound to this variable
  364.     return &{ $self->{ ACTION }->{ $variable } }($self, $variable, $value)
  365.         if (exists($self->{ ACTION }->{ $variable }));
  366.  
  367.     # ...or just return 1 (ok)
  368.     return 1;
  369. }
  370.  
  371.  
  372. #------------------------------------------------------------------------
  373. # varlist($criteria, $filter)
  374. #
  375. # Returns a hash array of all variables and values whose real names 
  376. # match the $criteria regex pattern passed as the first parameter.
  377. # If $filter is set to any true value, the keys of the hash array 
  378. # (variable names) will have the $criteria part removed.  This allows 
  379. # the caller to specify the variables from one particular [block] and
  380. # have the "block_" prefix removed, for example.  
  381. #
  382. # TODO: This should be changed to varhash().  varlist() should return a 
  383. # list.  Also need to consider specification by list rather than regex.
  384. #
  385. #------------------------------------------------------------------------
  386.  
  387. sub varlist {
  388.     my $self     = shift;
  389.     my $criteria = shift;
  390.     my $strip    = shift;
  391.  
  392.     $criteria = "" unless defined $criteria;
  393.  
  394.     # extract relevant keys and slice out corresponding values
  395.     my @keys = grep(/$criteria/, keys %{ $self->{ VARIABLE } });
  396.     my @vals = @{ $self->{ VARIABLE } }{ @keys };
  397.     my %set;
  398.  
  399.     # clean off the $criteria part if $strip is set
  400.     @keys = map { s/$criteria//; $_ } @keys if $strip;
  401.  
  402.     # slice values into the target hash 
  403.     @set{ @keys } = @vals;
  404.     return %set;
  405. }
  406.  
  407.     
  408. #------------------------------------------------------------------------
  409. # AUTOLOAD
  410. #
  411. # Autoload function called whenever an unresolved object method is 
  412. # called.  If the method name relates to a defined VARIABLE, we patch
  413. # in $self->get() and $self->set() to magically update the varaiable
  414. # (if a parameter is supplied) and return the previous value.
  415. #
  416. # Thus the function can be used in the folowing ways:
  417. #    $state->variable(123);     # set a new value
  418. #    $foo = $state->variable(); # get the current value
  419. #
  420. # Returns the current value of the variable, taken before any new value
  421. # is set.  Prints a warning if the variable isn't defined (i.e. doesn't
  422. # exist rather than exists with an undef value) and returns undef.
  423. #------------------------------------------------------------------------
  424.  
  425. sub AUTOLOAD {
  426.     my $self = shift;
  427.     my ($variable, $attrib);
  428.  
  429.  
  430.     # splat the leading package name
  431.     ($variable = $AUTOLOAD) =~ s/.*:://;
  432.  
  433.     # ignore destructor
  434.     $variable eq 'DESTROY' && return;
  435.  
  436.  
  437.     # per-variable attributes and internal flags listed as keys in 
  438.     # %METHFLAGS and %METHVARS respectively can be accessed by a 
  439.     # method matching the attribute or flag name in lower case with 
  440.     # a leading underscore_
  441.     if (($attrib = $variable) =~ s/_//g) {
  442.         $attrib = uc $attrib;
  443.     
  444.         if (exists $METHFLAGS{ $attrib }) {
  445.             return $self->{ $attrib };
  446.         }
  447.  
  448.         if (exists $METHVARS{ $attrib }) {
  449.             # next parameter should be variable name
  450.             $variable = shift;
  451.             $variable = $self->_varname($variable);
  452.             
  453.             # check we've got a valid variable
  454. #        $self->_error("$variable: no such variable or method"), 
  455. #            return undef
  456. #        unless exists($self->{ VARIABLE }->{ $variable });
  457.             
  458.             # return attribute
  459.             return $self->{ $attrib }->{ $variable };
  460.         }
  461.     }
  462.     
  463.     # set a new value if a parameter was supplied or return the old one
  464.     return defined($_[0])
  465.            ? $self->set($variable, shift)
  466.            : $self->get($variable);
  467. }
  468.  
  469.  
  470.  
  471. #========================================================================
  472. #                      -----  PRIVATE METHODS -----
  473. #========================================================================
  474.  
  475. #------------------------------------------------------------------------
  476. # _configure(\%cfg)
  477. #
  478. # Sets the various configuration options using the values passed in the
  479. # hash array referenced by $cfg.
  480. #------------------------------------------------------------------------
  481.  
  482. sub _configure {
  483.     my $self = shift;
  484.     my $cfg  = shift || return;
  485.  
  486.     # construct a regex to match values which are ok to be found in GLOBAL
  487.     my $global_ok = join('|', @GLOBAL_OK);
  488.  
  489.     foreach my $opt (keys %$cfg) {
  490.  
  491.         # GLOBAL must be a hash ref
  492.         $opt =~ /^GLOBALS?$/i && do {
  493.             unless (ref($cfg->{ $opt }) eq 'HASH') {
  494.                 $self->_error("\U$opt\E parameter is not a hash ref");
  495.                 next;
  496.             }
  497.  
  498.             # we check each option is ok to be in GLOBAL, but we don't do 
  499.             # any error checking on the values they contain (but should?).
  500.             foreach my $global ( keys %{ $cfg->{ $opt } } )  {
  501.  
  502.                 # continue if the attribute is ok to be GLOBAL 
  503.                 next if ($global =~ /(^$global_ok$)/io);
  504.                          
  505.                 $self->_error( "\U$global\E parameter cannot be GLOBAL");
  506.             }
  507.             $self->{ GLOBAL } = $cfg->{ $opt };
  508.             next;
  509.         };
  510.             
  511.     
  512.         # CASE, CREATE and PEDANTIC are stored as they are
  513.         $opt =~ /^CASE|CREATE|PEDANTIC$/i && do {
  514.             $self->{ uc $opt } = $cfg->{ $opt };
  515.             next;
  516.         };
  517.  
  518.         # ERROR triggers $self->_ehandler()
  519.         $opt =~ /^ERROR$/i && do {
  520.             $self->_ehandler($cfg->{ $opt });
  521.             next;
  522.         };
  523.  
  524.         # DEBUG triggers $self->_debug()
  525.         $opt =~ /^DEBUG$/i && do {
  526.             $self->_debug($cfg->{ $opt });
  527.             next;
  528.         };
  529.             
  530.         # warn about invalid options
  531.         $self->_error("\U$opt\E is not a valid configuration option");
  532.     }
  533. }
  534.  
  535.  
  536. #------------------------------------------------------------------------
  537. # _varname($variable, \$negated)
  538. #
  539. # Variable names are treated case-sensitively or insensitively, depending 
  540. # on the value of $self->{ CASE }.  When case-insensitive ($self->{ CASE } 
  541. # != 0), all variable names are converted to lower case.  Variable values 
  542. # are not converted.  This function simply converts the parameter 
  543. # (variable) to lower case if $self->{ CASE } isn't set.  _varname() also 
  544. # expands a variable alias to the name of the target variable.  
  545. #
  546. # Variables with an ARGCOUNT of ARGCOUNT_ZERO may be specified as 
  547. # "no<var>" in which case, the intended value should be negated.  The 
  548. # leading "no" part is stripped from the variable name.  A reference to 
  549. # a scalar value can be passed as the second parameter and if the 
  550. # _varname() method identified such a variable, it will negate the value.  
  551. # This allows the intended value or a simple negate flag to be passed by
  552. # reference and be updated to indicate any negation activity taking place.
  553. #
  554. # The (possibly modified) variable name is returned.
  555. #------------------------------------------------------------------------
  556.  
  557. sub _varname {
  558.     my $self     = shift;
  559.     my $variable = shift;
  560.     my $negated  = shift;
  561.  
  562.     # convert to lower case if case insensitive
  563.     $variable = $self->{ CASE } ? $variable : lc $variable;
  564.  
  565.     # get the actual name if this is an alias
  566.     $variable = $self->{ ALIAS }->{ $variable }
  567.     if (exists($self->{ ALIAS }->{ $variable }));
  568.  
  569.     # if the variable doesn't exist, we can try to chop off a leading 
  570.     # "no" and see if the remainder matches an ARGCOUNT_ZERO variable
  571.     unless (exists($self->{ VARIABLE }->{ $variable })) {
  572.         # see if the variable is specified as "no<var>"
  573.         if ($variable =~ /^no(.*)/) {
  574.             # see if the real variable (minus "no") exists and it
  575.             # has an ARGOUNT of ARGCOUNT_NONE (or no ARGCOUNT at all)
  576.             my $novar = $self->_varname($1);
  577.             if (exists($self->{ VARIABLE }->{ $novar })
  578.                 && ! $self->{ ARGCOUNT }->{ $novar }) {
  579.                 # set variable name and negate value 
  580.                 $variable = $novar;
  581.                 $$negated = ! $$negated if defined $negated;
  582.             }
  583.         }
  584.     }
  585.     
  586.     # return the variable name
  587.     $variable;
  588. }
  589.  
  590.  
  591. #------------------------------------------------------------------------
  592. # _default($variable)
  593. #
  594. # Sets the variable specified to the default value or undef if it doesn't
  595. # have a default.  The default value is returned.
  596. #------------------------------------------------------------------------
  597.  
  598. sub _default {
  599.     my $self     = shift;
  600.     my $variable = shift;
  601.  
  602.     # _varname returns variable name after aliasing and case conversion
  603.     $variable = $self->_varname($variable);
  604.  
  605.     # check the variable exists
  606.     if (exists($self->{ VARIABLE }->{ $variable })) {
  607.         # set variable value to the default scalar, an empty list or empty
  608.         # hash array, depending on its ARGCOUNT value
  609.         my $argcount = $self->{ ARGCOUNT }->{ $variable };
  610.         $argcount = AppConfig::ARGCOUNT_ONE unless defined $argcount;
  611.         
  612.         if ($argcount == AppConfig::ARGCOUNT_NONE) {
  613.             return $self->{ VARIABLE }->{ $variable } 
  614.             = $self->{ DEFAULT }->{ $variable } || 0;
  615.         }
  616.         elsif ($argcount == AppConfig::ARGCOUNT_LIST) {
  617.             my $deflist = $self->{ DEFAULT }->{ $variable };
  618.             return $self->{ VARIABLE }->{ $variable } = 
  619.                 [ ref $deflist eq 'ARRAY' ? @$deflist : ( ) ];
  620.             
  621.         }
  622.         elsif ($argcount == AppConfig::ARGCOUNT_HASH) {
  623.             my $defhash = $self->{ DEFAULT }->{ $variable };
  624.             return $self->{ VARIABLE }->{ $variable } = 
  625.             { ref $defhash eq 'HASH' ? %$defhash : () };
  626.         }
  627.         else {
  628.             return $self->{ VARIABLE }->{ $variable } 
  629.             = $self->{ DEFAULT }->{ $variable };
  630.         }
  631.     }
  632.     else {
  633.         $self->_error("$variable: no such variable");
  634.         return 0;
  635.     }
  636. }
  637.  
  638.  
  639. #------------------------------------------------------------------------
  640. # _exists($variable)
  641. #
  642. # Returns 1 if the variable specified exists or 0 if not.
  643. #------------------------------------------------------------------------
  644.  
  645. sub _exists {
  646.     my $self     = shift;
  647.     my $variable = shift;
  648.  
  649.  
  650.     # _varname returns variable name after aliasing and case conversion
  651.     $variable = $self->_varname($variable);
  652.  
  653.     # check the variable has been defined
  654.     return exists($self->{ VARIABLE }->{ $variable });
  655. }
  656.  
  657.  
  658. #------------------------------------------------------------------------
  659. # _validate($variable, $value)
  660. #
  661. # Uses any validation rules or code defined for the variable to test if
  662. # the specified value is acceptable.
  663. #
  664. # Returns 1 if the value passed validation checks, 0 if not.
  665. #------------------------------------------------------------------------
  666.  
  667. sub _validate {
  668.     my $self     = shift;
  669.     my $variable = shift;
  670.     my $value    = shift;
  671.     my $validator;
  672.  
  673.  
  674.     # _varname returns variable name after aliasing and case conversion
  675.     $variable = $self->_varname($variable);
  676.  
  677.     # return OK unless there is a validation function
  678.     return 1 unless defined($validator = $self->{ VALIDATE }->{ $variable });
  679.  
  680.     #
  681.     # the validation performed is based on the validator type;
  682.     #
  683.     #   CODE ref: code executed, returning 1 (ok) or 0 (failed)
  684.     #   SCALAR  : a regex which should match the value
  685.     #
  686.  
  687.     # CODE ref
  688.     ref($validator) eq 'CODE' && do {
  689.         # run the validation function and return the result
  690.            return &$validator($variable, $value);
  691.     };
  692.  
  693.     # non-ref (i.e. scalar)
  694.     ref($validator) || do {
  695.         # not a ref - assume it's a regex
  696.         return $value =~ /$validator/;
  697.     };
  698.     
  699.     # validation failed
  700.     return 0;
  701. }
  702.  
  703.  
  704. #------------------------------------------------------------------------
  705. # _error($format, @params)
  706. #
  707. # Checks for the existence of a user defined error handling routine and
  708. # if defined, passes all variable straight through to that.  The routine
  709. # is expected to handle a string format and optional parameters as per
  710. # printf(3C).  If no error handler is defined, the message is formatted
  711. # and passed to warn() which prints it to STDERR.
  712. #------------------------------------------------------------------------
  713.  
  714. sub _error {
  715.     my $self   = shift;
  716.     my $format = shift;
  717.  
  718.     # user defined error handler?
  719.     if (ref($self->{ EHANDLER }) eq 'CODE') {
  720.         &{ $self->{ EHANDLER } }($format, @_);
  721.     }
  722.     else {
  723.         warn(sprintf("$format\n", @_));
  724.     }
  725. }
  726.  
  727.  
  728. #------------------------------------------------------------------------
  729. # _ehandler($handler)
  730. #
  731. # Allows a new error handler to be installed.  The current value of 
  732. # the error handler is returned.
  733. #
  734. # This is something of a kludge to allow other AppConfig::* modules to 
  735. # install their own error handlers to format error messages appropriately.
  736. # For example, AppConfig::File appends a message of the form 
  737. # "at $file line $line" to each error message generated while parsing 
  738. # configuration files.  The previous handler is returned (and presumably
  739. # stored by the caller) to allow new error handlers to chain control back
  740. # to any user-defined handler, and also restore the original handler when 
  741. # done.
  742. #------------------------------------------------------------------------
  743.  
  744. sub _ehandler {
  745.     my $self    = shift;
  746.     my $handler = shift;
  747.  
  748.     # save previous value
  749.     my $previous = $self->{ EHANDLER };
  750.  
  751.     # update internal reference if a new handler vas provide
  752.     if (defined $handler) {
  753.         # check this is a code reference
  754.         if (ref($handler) eq 'CODE') {
  755.             $self->{ EHANDLER } = $handler;
  756.             
  757.             # DEBUG
  758.             print STDERR "installed new ERROR handler: $handler\n" if $DEBUG;
  759.         }
  760.         else {
  761.             $self->_error("ERROR handler parameter is not a code ref");
  762.         }
  763.     }
  764.    
  765.     return $previous;
  766. }
  767.  
  768.  
  769. #------------------------------------------------------------------------
  770. # _debug($debug)
  771. #
  772. # Sets the package debugging variable, $AppConfig::State::DEBUG depending 
  773. # on the value of the $debug parameter.  1 turns debugging on, 0 turns 
  774. # debugging off.
  775. #
  776. # May be called as an object method, $state->_debug(1), or as a package
  777. # function, AppConfig::State::_debug(1).  Returns the previous value of 
  778. # $DEBUG, before any new value was applied.
  779. #------------------------------------------------------------------------
  780.  
  781. sub _debug {
  782.     # object reference may not be present if called as a package function
  783.     my $self   = shift if ref($_[0]);
  784.     my $newval = shift;
  785.  
  786.     # save previous value
  787.     my $oldval = $DEBUG;
  788.  
  789.     # update $DEBUG if a new value was provided
  790.     $DEBUG = $newval if defined $newval;
  791.  
  792.     # return previous value
  793.     $oldval;
  794. }
  795.  
  796.  
  797. #------------------------------------------------------------------------
  798. # _dump_var($var)
  799. #
  800. # Displays the content of the specified variable, $var.
  801. #------------------------------------------------------------------------
  802.  
  803. sub _dump_var {
  804.     my $self   = shift;
  805.     my $var    = shift;
  806.  
  807.     return unless defined $var;
  808.  
  809.     # $var may be an alias, so we resolve the real variable name
  810.     my $real = $self->_varname($var);
  811.     if ($var eq $real) {
  812.         print STDERR "$var\n";
  813.     }
  814.     else {
  815.         print STDERR "$real  ('$var' is an alias)\n";
  816.         $var = $real;
  817.     }
  818.  
  819.     # for some bizarre reason, the variable VALUE is stored in VARIABLE
  820.     # (it made sense at some point in time)
  821.     printf STDERR "    VALUE        => %s\n", 
  822.         defined($self->{ VARIABLE }->{ $var }) 
  823.             ? $self->{ VARIABLE }->{ $var } 
  824.             : "<undef>";
  825.  
  826.     # the rest of the values can be read straight out of their hashes
  827.     foreach my $param (qw( DEFAULT ARGCOUNT VALIDATE ACTION EXPAND )) {
  828.     printf STDERR "    %-12s => %s\n", $param, 
  829.         defined($self->{ $param }->{ $var }) 
  830.             ? $self->{ $param }->{ $var } 
  831.             : "<undef>";
  832.     }
  833.  
  834.     # summarise all known aliases for this variable
  835.     print STDERR "    ALIASES      => ", 
  836.         join(", ", @{ $self->{ ALIASES }->{ $var } }), "\n"
  837.             if defined $self->{ ALIASES }->{ $var };
  838.  
  839.  
  840. #------------------------------------------------------------------------
  841. # _dump()
  842. #
  843. # Dumps the contents of the Config object and all stored variables.  
  844. #------------------------------------------------------------------------
  845.  
  846. sub _dump {
  847.     my $self = shift;
  848.     my $var;
  849.  
  850.     print STDERR "=" x 71, "\n";
  851.     print STDERR 
  852.     "Status of AppConfig::State (version $VERSION) object:\n\t$self\n";
  853.  
  854.     
  855.     print STDERR "- " x 36, "\nINTERNAL STATE:\n";
  856.     foreach (qw( CREATE CASE PEDANTIC EHANDLER ERROR )) {
  857.         printf STDERR "    %-12s => %s\n", $_, 
  858.         defined($self->{ $_ }) ? $self->{ $_ } : "<undef>";
  859.     }        
  860.  
  861.     print STDERR "- " x 36, "\nVARIABLES:\n";
  862.     foreach $var (keys %{ $self->{ VARIABLE } }) {
  863.         $self->_dump_var($var);
  864.     }
  865.  
  866.     print STDERR "- " x 36, "\n", "ALIASES:\n";
  867.     foreach $var (keys %{ $self->{ ALIAS } }) {
  868.         printf("    %-12s => %s\n", $var, $self->{ ALIAS }->{ $var });
  869.     }
  870.     print STDERR "=" x 72, "\n";
  871.  
  872.  
  873.  
  874. 1;
  875.  
  876. __END__
  877.  
  878. =head1 NAME
  879.  
  880. AppConfig::State - application configuration state
  881.  
  882. =head1 SYNOPSIS
  883.  
  884.     use AppConfig::State;
  885.  
  886.     my $state = AppConfig::State->new(\%cfg);
  887.  
  888.     $state->define("foo");            # very simple variable definition
  889.     $state->define("bar", \%varcfg);  # variable specific configuration
  890.     $state->define("foo|bar=i@");     # compact format
  891.  
  892.     $state->set("foo", 123);          # trivial set/get examples
  893.     $state->get("foo");      
  894.     
  895.     $state->foo();                    # shortcut variable access 
  896.     $state->foo(456);                 # shortcut variable update 
  897.  
  898. =head1 OVERVIEW
  899.  
  900. AppConfig::State is a Perl5 module to handle global configuration variables
  901. for perl programs.  It maintains the state of any number of variables,
  902. handling default values, aliasing, validation, update callbacks and 
  903. option arguments for use by other AppConfig::* modules.  
  904.  
  905. AppConfig::State is distributed as part of the AppConfig bundle.
  906.  
  907. =head1 DESCRIPTION
  908.  
  909. =head2 USING THE AppConfig::State MODULE
  910.  
  911. To import and use the AppConfig::State module the following line should 
  912. appear in your Perl script:
  913.  
  914.      use AppConfig::State;
  915.  
  916. The AppConfig::State module is loaded automatically by the new()
  917. constructor of the AppConfig module.
  918.       
  919. AppConfig::State is implemented using object-oriented methods.  A 
  920. new AppConfig::State object is created and initialised using the 
  921. new() method.  This returns a reference to a new AppConfig::State 
  922. object.
  923.        
  924.     my $state = AppConfig::State->new();
  925.  
  926. This will create a reference to a new AppConfig::State with all 
  927. configuration options set to their default values.  You can initialise 
  928. the object by passing a reference to a hash array containing 
  929. configuration options:
  930.  
  931.     $state = AppConfig::State->new( {
  932.     CASE      => 1,
  933.     ERROR     => \&my_error,
  934.     } );
  935.  
  936. The new() constructor of the AppConfig module automatically passes all 
  937. parameters to the AppConfig::State new() constructor.  Thus, any global 
  938. configuration values and variable definitions for AppConfig::State are 
  939. also applicable to AppConfig.
  940.  
  941. The following configuration options may be specified.  
  942.  
  943. =over 4
  944.  
  945. =item CASE
  946.  
  947. Determines if the variable names are treated case sensitively.  Any non-zero
  948. value makes case significant when naming variables.  By default, CASE is set
  949. to 0 and thus "Variable", "VARIABLE" and "VaRiAbLe" are all treated as 
  950. "variable".
  951.  
  952. =item CREATE
  953.  
  954. By default, CREATE is turned off meaning that all variables accessed via
  955. set() (which includes access via shortcut such as 
  956. C<$state-E<gt>variable($value)> which delegates to set()) must previously 
  957. have been defined via define().  When CREATE is set to 1, calling 
  958. set($variable, $value) on a variable that doesn't exist will cause it 
  959. to be created automatically.
  960.  
  961. When CREATE is set to any other non-zero value, it is assumed to be a
  962. regular expression pattern.  If the variable name matches the regex, the
  963. variable is created.  This can be used to specify configuration file 
  964. blocks in which variables should be created, for example:
  965.  
  966.     $state = AppConfig::State->new( {
  967.     CREATE => '^define_',
  968.     } );
  969.  
  970. In a config file:
  971.  
  972.     [define]
  973.     name = fred           # define_name gets created automatically
  974.  
  975.     [other]
  976.     name = john           # other_name doesn't - warning raised
  977.  
  978. Note that a regex pattern specified in CREATE is applied to the real 
  979. variable name rather than any alias by which the variables may be 
  980. accessed.  
  981.  
  982. =item PEDANTIC
  983.  
  984. The PEDANTIC option determines what action the configuration file 
  985. (AppConfig::File) or argument parser (AppConfig::Args) should take 
  986. on encountering a warning condition (typically caused when trying to set an
  987. undeclared variable).  If PEDANTIC is set to any true value, the parsing
  988. methods will immediately return a value of 0 on encountering such a
  989. condition.  If PEDANTIC is not set, the method will continue to parse the
  990. remainder of the current file(s) or arguments, returning 0 when complete.
  991.  
  992. If no warnings or errors are encountered, the method returns 1.
  993.  
  994. In the case of a system error (e.g. unable to open a file), the method
  995. returns undef immediately, regardless of the PEDANTIC option.
  996.  
  997. =item ERROR
  998.  
  999. Specifies a user-defined error handling routine.  When the handler is 
  1000. called, a format string is passed as the first parameter, followed by 
  1001. any additional values, as per printf(3C).
  1002.  
  1003. =item DEBUG
  1004.  
  1005. Turns debugging on or off when set to 1 or 0 accordingly.  Debugging may 
  1006. also be activated by calling _debug() as an object method 
  1007. (C<$state-E<gt>_debug(1)>) or as a package function 
  1008. (C<AppConfig::State::_debug(1)>), passing in a true/false value to 
  1009. set the debugging state accordingly.  The package variable 
  1010. $AppConfig::State::DEBUG can also be set directly.  
  1011.  
  1012. The _debug() method returns the current debug value.  If a new value 
  1013. is passed in, the internal value is updated, but the previous value is 
  1014. returned.
  1015.  
  1016. Note that any AppConfig::File or App::Config::Args objects that are 
  1017. instantiated with a reference to an App::State will inherit the 
  1018. DEBUG (and also PEDANTIC) values of the state at that time.  Subsequent
  1019. changes to the AppConfig::State debug value will not affect them.
  1020.  
  1021. =item GLOBAL 
  1022.  
  1023. The GLOBAL option allows default values to be set for the DEFAULT, ARGCOUNT, 
  1024. EXPAND, VALIDATE and ACTION options for any subsequently defined variables.
  1025.  
  1026.     $state = AppConfig::State->new({
  1027.     GLOBAL => {
  1028.         DEFAULT  => '<undef>',     # default value for new vars
  1029.         ARGCOUNT => 1,             # vars expect an argument
  1030.         ACTION   => \&my_set_var,  # callback when vars get set
  1031.     }
  1032.     });
  1033.  
  1034. Any attributes specified explicitly when a variable is defined will
  1035. override any GLOBAL values.
  1036.  
  1037. See L<DEFINING VARIABLES> below which describes these options in detail.
  1038.  
  1039. =back
  1040.  
  1041. =head2 DEFINING VARIABLES
  1042.  
  1043. The C<define()> function is used to pre-declare a variable and specify 
  1044. its configuration.
  1045.  
  1046.     $state->define("foo");
  1047.  
  1048. In the simple example above, a new variable called "foo" is defined.  A 
  1049. reference to a hash array may also be passed to specify configuration 
  1050. information for the variable:
  1051.  
  1052.     $state->define("foo", {
  1053.         DEFAULT   => 99,
  1054.         ALIAS     => 'metavar1',
  1055.     });
  1056.  
  1057. Any variable-wide GLOBAL values passed to the new() constructor in the 
  1058. configuration hash will also be applied.  Values explicitly specified 
  1059. in a variable's define() configuration will override the respective GLOBAL 
  1060. values.
  1061.  
  1062. The following configuration options may be specified
  1063.  
  1064. =over 4
  1065.  
  1066. =item DEFAULT
  1067.  
  1068. The DEFAULT value is used to initialise the variable.  
  1069.  
  1070.     $state->define("drink", {
  1071.         DEFAULT => 'coffee',
  1072.     });
  1073.  
  1074.     print $state->drink();        # prints "coffee"
  1075.  
  1076. =item ALIAS
  1077.  
  1078. The ALIAS option allows a number of alternative names to be specified for 
  1079. this variable.  A single alias should be specified as a string.  Multiple 
  1080. aliases can be specified as a reference to an array of alternatives or as 
  1081. a string of names separated by vertical bars, '|'.  e.g.:
  1082.  
  1083.     $state->define("name", {
  1084.         ALIAS  => 'person',
  1085.     });
  1086. or
  1087.     $state->define("name", {
  1088.         ALIAS => [ 'person', 'user', 'uid' ],
  1089.     });
  1090. or
  1091.     $state->define("name", {
  1092.         ALIAS => 'person|user|uid',
  1093.     });
  1094.  
  1095.     $state->user('abw');     # equivalent to $state->name('abw');
  1096.  
  1097. =item ARGCOUNT
  1098.  
  1099. The ARGCOUNT option specifies the number of arguments that should be 
  1100. supplied for this variable.  By default, no additional arguments are 
  1101. expected for variables (ARGCOUNT_NONE).
  1102.  
  1103. The ARGCOUNT_* constants can be imported from the AppConfig module:
  1104.  
  1105.     use AppConfig ':argcount';
  1106.  
  1107.     $state->define('foo', { ARGCOUNT => ARGCOUNT_ONE });
  1108.  
  1109. or can be accessed directly from the AppConfig package:
  1110.  
  1111.     use AppConfig;
  1112.  
  1113.     $state->define('foo', { ARGCOUNT => AppConfig::ARGCOUNT_ONE });
  1114.  
  1115. The following values for ARGCOUNT may be specified.  
  1116.  
  1117. =over 4
  1118.  
  1119. =item ARGCOUNT_NONE (0)
  1120.  
  1121. Indicates that no additional arguments are expected.  If the variable is
  1122. identified in a confirguration file or in the command line arguments, it
  1123. is set to a value of 1 regardless of whatever arguments follow it.
  1124.  
  1125. =item ARGCOUNT_ONE (1)
  1126.  
  1127. Indicates that the variable expects a single argument to be provided.
  1128. The variable value will be overwritten with a new value each time it 
  1129. is encountered.
  1130.  
  1131. =item ARGCOUNT_LIST (2)
  1132.  
  1133. Indicates that the variable expects multiple arguments.  The variable 
  1134. value will be appended to the list of previous values each time it is
  1135. encountered.  
  1136.  
  1137. =item ARGCOUNT_HASH (3)
  1138.  
  1139. Indicates that the variable expects multiple arguments and that each
  1140. argument is of the form "key=value".  The argument will be split into 
  1141. a key/value pair and inserted into the hash of values each time it 
  1142. is encountered.
  1143.  
  1144. =back
  1145.  
  1146. =item ARGS
  1147.  
  1148. The ARGS option can also be used to specify advanced command line options 
  1149. for use with AppConfig::Getopt, which itself delegates to Getopt::Long.  
  1150. See those two modules for more information on the format and meaning of
  1151. these options.
  1152.  
  1153.     $state->define("name", {
  1154.         ARGS => "=i@",
  1155.     });
  1156.  
  1157. =item EXPAND 
  1158.  
  1159. The EXPAND option specifies how the AppConfig::File processor should 
  1160. expand embedded variables in the configuration file values it reads.
  1161. By default, EXPAND is turned off (EXPAND_NONE) and no expansion is made.  
  1162.  
  1163. The EXPAND_* constants can be imported from the AppConfig module:
  1164.  
  1165.     use AppConfig ':expand';
  1166.  
  1167.     $state->define('foo', { EXPAND => EXPAND_VAR });
  1168.  
  1169. or can be accessed directly from the AppConfig package:
  1170.  
  1171.     use AppConfig;
  1172.  
  1173.     $state->define('foo', { EXPAND => AppConfig::EXPAND_VAR });
  1174.  
  1175. The following values for EXPAND may be specified.  Multiple values should
  1176. be combined with vertical bars , '|', e.g. C<EXPAND_UID | EXPAND_VAR>).
  1177.  
  1178. =over 4
  1179.  
  1180. =item EXPAND_NONE
  1181.  
  1182. Indicates that no variable expansion should be attempted.
  1183.  
  1184. =item EXPAND_VAR
  1185.  
  1186. Indicates that variables embedded as $var or $(var) should be expanded
  1187. to the values of the relevant AppConfig::State variables.
  1188.  
  1189. =item EXPAND_UID 
  1190.  
  1191. Indicates that '~' or '~uid' patterns in the string should be 
  1192. expanded to the current users ($<), or specified user's home directory.
  1193.  
  1194. =item EXPAND_ENV
  1195.  
  1196. Inidicates that variables embedded as ${var} should be expanded to the 
  1197. value of the relevant environment variable.
  1198.  
  1199. =item EXPAND_ALL
  1200.  
  1201. Equivalent to C<EXPAND_VARS | EXPAND_UIDS | EXPAND_ENVS>).
  1202.  
  1203. =item EXPAND_WARN
  1204.  
  1205. Indicates that embedded variables that are not defined should raise a
  1206. warning.  If PEDANTIC is set, this will cause the read() method to return 0
  1207. immediately.
  1208.  
  1209. =back
  1210.  
  1211. =item VALIDATE
  1212.  
  1213. Each variable may have a sub-routine or regular expression defined which 
  1214. is used to validate the intended value for a variable before it is set.
  1215.  
  1216. If VALIDATE is defined as a regular expression, it is applied to the
  1217. value and deemed valid if the pattern matches.  In this case, the
  1218. variable is then set to the new value.  A warning message is generated
  1219. if the pattern match fails.
  1220.  
  1221. VALIDATE may also be defined as a reference to a sub-routine which takes
  1222. as its arguments the name of the variable and its intended value.  The 
  1223. sub-routine should return 1 or 0 to indicate that the value is valid
  1224. or invalid, respectively.  An invalid value will cause a warning error
  1225. message to be generated.
  1226.  
  1227. If the GLOBAL VALIDATE variable is set (see GLOBAL in L<DESCRIPTION> 
  1228. above) then this value will be used as the default VALIDATE for each 
  1229. variable unless otherwise specified.
  1230.  
  1231.     $state->define("age", {
  1232.             VALIDATE => '\d+',
  1233.     });
  1234.  
  1235.     $state->define("pin", {
  1236.         VALIDATE => \&check_pin,
  1237.     });
  1238.  
  1239. =item ACTION
  1240.  
  1241. The ACTION option allows a sub-routine to be bound to a variable as a
  1242. callback that is executed whenever the variable is set.  The ACTION is
  1243. passed a reference to the AppConfig::State object, the name of the
  1244. variable and the value of the variable.
  1245.  
  1246. The ACTION routine may be used, for example, to post-process variable
  1247. data, update the value of some other dependant variable, generate a
  1248. warning message, etc.
  1249.  
  1250. Example:
  1251.  
  1252.     $state->define("foo", { ACTION => \&my_notify });
  1253.  
  1254.     sub my_notify {
  1255.     my $state = shift;
  1256.     my $var   = shift;
  1257.     my $val   = shift;
  1258.  
  1259.     print "$variable set to $value";
  1260.     }
  1261.  
  1262.     $state->foo(42);        # prints "foo set to 42"
  1263.  
  1264. Be aware that calling C<$state-E<gt>set()> to update the same variable
  1265. from within the ACTION function will cause a recursive loop as the
  1266. ACTION function is repeatedly called.  
  1267.  
  1268. =item 
  1269.  
  1270. =back
  1271.  
  1272. =head2 DEFINING VARIABLES USING THE COMPACT FORMAT
  1273.  
  1274. Variables may be defined in a compact format which allows any ALIAS and
  1275. ARGS values to be specified as part of the variable name.  This is designed
  1276. to mimic the behaviour of Johan Vromans' Getopt::Long module.
  1277.  
  1278. Aliases for a variable should be specified after the variable name, 
  1279. separated by vertical bars, '|'.  Any ARGS parameter should be appended 
  1280. after the variable name(s) and/or aliases.
  1281.  
  1282. The following examples are equivalent:
  1283.  
  1284.     $state->define("foo", { 
  1285.         ALIAS => [ 'bar', 'baz' ],
  1286.         ARGS  => '=i',
  1287.     });
  1288.  
  1289.     $state->define("foo|bar|baz=i");
  1290.  
  1291. =head2 READING AND MODIFYING VARIABLE VALUES
  1292.  
  1293. AppConfig::State defines two methods to manipulate variable values: 
  1294.  
  1295.     set($variable, $value);
  1296.     get($variable);
  1297.  
  1298. Both functions take the variable name as the first parameter and
  1299. C<set()> takes an additional parameter which is the new value for the
  1300. variable.  C<set()> returns 1 or 0 to indicate successful or
  1301. unsuccessful update of the variable value.  If there is an ACTION
  1302. routine associated with the named variable, the value returned will be
  1303. passed back from C<set()>.  The C<get()> function returns the current
  1304. value of the variable.
  1305.  
  1306. Once defined, variables may be accessed directly as object methods where
  1307. the method name is the same as the variable name.  i.e.
  1308.  
  1309.     $state->set("verbose", 1);
  1310.  
  1311. is equivalent to 
  1312.  
  1313.     $state->verbose(1); 
  1314.  
  1315. Without parameters, the current value of the variable is returned.  If
  1316. a parameter is specified, the variable is set to that value and the 
  1317. result of the set() operation is returned.
  1318.  
  1319.     $state->age(29);        # sets 'age' to 29, returns 1 (ok)
  1320.  
  1321. =head2 INTERNAL METHODS
  1322.  
  1323. The interal (private) methods of the AppConfig::State class are listed 
  1324. below.
  1325.  
  1326. They aren't intended for regular use and potential users should consider
  1327. the fact that nothing about the internal implementation is guaranteed to
  1328. remain the same.  Having said that, the AppConfig::State class is
  1329. intended to co-exist and work with a number of other modules and these
  1330. are considered "friend" classes.  These methods are provided, in part,
  1331. as services to them.  With this acknowledged co-operation in mind, it is
  1332. safe to assume some stability in this core interface.
  1333.  
  1334. The _varname() method can be used to determine the real name of a variable 
  1335. from an alias:
  1336.  
  1337.     $varname->_varname($alias);
  1338.  
  1339. Note that all methods that take a variable name, including those listed
  1340. below, can accept an alias and automatically resolve it to the correct 
  1341. variable name.  There is no need to call _varname() explicitly to do 
  1342. alias expansion.  The _varname() method will fold all variables names
  1343. to lower case unless CASE sensititvity is set.
  1344.  
  1345. The _exists() method can be used to check if a variable has been
  1346. defined:
  1347.  
  1348.     $state->_exists($varname);
  1349.  
  1350. The _default() method can be used to reset a variable to its default value:
  1351.  
  1352.     $state->_default($varname);
  1353.  
  1354. The _expand() method can be used to determine the EXPAND value for a 
  1355. variable:
  1356.  
  1357.     print "$varname EXPAND: ", $state->_expand($varname), "\n";
  1358.  
  1359. The _argcount() method returns the value of the ARGCOUNT attribute for a 
  1360. variable:
  1361.  
  1362.     print "$varname ARGCOUNT: ", $state->_argcount($varname), "\n";
  1363.  
  1364. The _validate() method can be used to determine if a new value for a variable
  1365. meets any validation criteria specified for it.  The variable name and 
  1366. intended value should be passed in.  The methods returns a true/false value
  1367. depending on whether or not the validation succeeded:
  1368.  
  1369.     print "OK\n" if $state->_validate($varname, $value);
  1370.  
  1371. The _pedantic() method can be called to determine the current value of the
  1372. PEDANTIC option.
  1373.  
  1374.     print "pedantic mode is ", $state->_pedantic() ? "on" ; "off", "\n";
  1375.  
  1376. The _debug() method can be used to turn debugging on or off (pass 1 or 0
  1377. as a parameter).  It can also be used to check the debug state,
  1378. returning the current internal value of $AppConfig::State::DEBUG.  If a
  1379. new debug value is provided, the debug state is updated and the previous
  1380. state is returned.
  1381.  
  1382.     $state->_debug(1);               # debug on, returns previous value
  1383.  
  1384. The _dump_var($varname) and _dump() methods may also be called for
  1385. debugging purposes.  
  1386.  
  1387.     $state->_dump_var($varname);    # show variable state
  1388.     $state->_dump();                # show internal state and all vars
  1389.  
  1390. =head1 AUTHOR
  1391.  
  1392. Andy Wardley, E<lt>abw@wardley.orgE<gt>
  1393.  
  1394. =head1 REVISION
  1395.  
  1396. $Revision: 1.61 $
  1397.  
  1398. =head1 COPYRIGHT
  1399.  
  1400. Copyright (C) 1997-2003 Andy Wardley.  All Rights Reserved.
  1401.  
  1402. Copyright (C) 1997,1998 Canon Research Centre Europe Ltd.
  1403.  
  1404. This module is free software; you can redistribute it and/or modify it 
  1405. under the same terms as Perl itself.
  1406.  
  1407. =head1 SEE ALSO
  1408.  
  1409. AppConfig, AppConfig::File, AppConfig::Args, AppConfig::Getopt
  1410.  
  1411. =cut
  1412.