1AppConfig::State(3)   User Contributed Perl Documentation  AppConfig::State(3)
2
3
4

NAME

6       AppConfig::State - application configuration state
7

SYNOPSIS

9           use AppConfig::State;
10
11           my $state = AppConfig::State->new(\%cfg);
12
13           $state->define("foo");            # very simple variable definition
14           $state->define("bar", \%varcfg);  # variable specific configuration
15           $state->define("foo|bar=i@");     # compact format
16
17           $state->set("foo", 123);          # trivial set/get examples
18           $state->get("foo");
19
20           $state->foo();                    # shortcut variable access
21           $state->foo(456);                 # shortcut variable update
22

OVERVIEW

24       AppConfig::State is a Perl5 module to handle global configuration
25       variables for perl programs.  It maintains the state of any number of
26       variables, handling default values, aliasing, validation, update
27       callbacks and option arguments for use by other AppConfig::* modules.
28
29       AppConfig::State is distributed as part of the AppConfig bundle.
30

DESCRIPTION

32   USING THE AppConfig::State MODULE
33       To import and use the AppConfig::State module the following line should
34       appear in your Perl script:
35
36            use AppConfig::State;
37
38       The AppConfig::State module is loaded automatically by the new()
39       constructor of the AppConfig module.
40
41       AppConfig::State is implemented using object-oriented methods.  A new
42       AppConfig::State object is created and initialised using the new()
43       method.  This returns a reference to a new AppConfig::State object.
44
45           my $state = AppConfig::State->new();
46
47       This will create a reference to a new AppConfig::State with all
48       configuration options set to their default values.  You can initialise
49       the object by passing a reference to a hash array containing
50       configuration options:
51
52           $state = AppConfig::State->new( {
53               CASE      => 1,
54               ERROR     => \&my_error,
55           } );
56
57       The new() constructor of the AppConfig module automatically passes all
58       parameters to the AppConfig::State new() constructor.  Thus, any global
59       configuration values and variable definitions for AppConfig::State are
60       also applicable to AppConfig.
61
62       The following configuration options may be specified.
63
64       CASE
65           Determines if the variable names are treated case sensitively.  Any
66           non-zero value makes case significant when naming variables.  By
67           default, CASE is set to 0 and thus "Variable", "VARIABLE" and
68           "VaRiAbLe" are all treated as "variable".
69
70       CREATE
71           By default, CREATE is turned off meaning that all variables
72           accessed via set() (which includes access via shortcut such as
73           "$state->variable($value)" which delegates to set()) must
74           previously have been defined via define().  When CREATE is set to
75           1, calling set($variable, $value) on a variable that doesn't exist
76           will cause it to be created automatically.
77
78           When CREATE is set to any other non-zero value, it is assumed to be
79           a regular expression pattern.  If the variable name matches the
80           regex, the variable is created.  This can be used to specify
81           configuration file blocks in which variables should be created, for
82           example:
83
84               $state = AppConfig::State->new( {
85                   CREATE => '^define_',
86               } );
87
88           In a config file:
89
90               [define]
91               name = fred           # define_name gets created automatically
92
93               [other]
94               name = john           # other_name doesn't - warning raised
95
96           Note that a regex pattern specified in CREATE is applied to the
97           real variable name rather than any alias by which the variables may
98           be accessed.
99
100       PEDANTIC
101           The PEDANTIC option determines what action the configuration file
102           (AppConfig::File) or argument parser (AppConfig::Args) should take
103           on encountering a warning condition (typically caused when trying
104           to set an undeclared variable).  If PEDANTIC is set to any true
105           value, the parsing methods will immediately return a value of 0 on
106           encountering such a condition.  If PEDANTIC is not set, the method
107           will continue to parse the remainder of the current file(s) or
108           arguments, returning 0 when complete.
109
110           If no warnings or errors are encountered, the method returns 1.
111
112           In the case of a system error (e.g. unable to open a file), the
113           method returns undef immediately, regardless of the PEDANTIC
114           option.
115
116       ERROR
117           Specifies a user-defined error handling routine.  When the handler
118           is called, a format string is passed as the first parameter,
119           followed by any additional values, as per printf(3C).
120
121       DEBUG
122           Turns debugging on or off when set to 1 or 0 accordingly.
123           Debugging may also be activated by calling _debug() as an object
124           method ("$state->_debug(1)") or as a package function
125           (AppConfig::State::_debug(1)), passing in a true/false value to set
126           the debugging state accordingly.  The package variable
127           $AppConfig::State::DEBUG can also be set directly.
128
129           The _debug() method returns the current debug value.  If a new
130           value is passed in, the internal value is updated, but the previous
131           value is returned.
132
133           Note that any AppConfig::File or App::Config::Args objects that are
134           instantiated with a reference to an App::State will inherit the
135           DEBUG (and also PEDANTIC) values of the state at that time.
136           Subsequent changes to the AppConfig::State debug value will not
137           affect them.
138
139       GLOBAL
140           The GLOBAL option allows default values to be set for the DEFAULT,
141           ARGCOUNT, EXPAND, VALIDATE and ACTION options for any subsequently
142           defined variables.
143
144               $state = AppConfig::State->new({
145                   GLOBAL => {
146                       DEFAULT  => '<undef>',     # default value for new vars
147                       ARGCOUNT => 1,             # vars expect an argument
148                       ACTION   => \&my_set_var,  # callback when vars get set
149                   }
150               });
151
152           Any attributes specified explicitly when a variable is defined will
153           override any GLOBAL values.
154
155           See "DEFINING VARIABLES" below which describes these options in
156           detail.
157
158   DEFINING VARIABLES
159       The "define()" function is used to pre-declare a variable and specify
160       its configuration.
161
162           $state->define("foo");
163
164       In the simple example above, a new variable called "foo" is defined.  A
165       reference to a hash array may also be passed to specify configuration
166       information for the variable:
167
168           $state->define("foo", {
169                   DEFAULT   => 99,
170                   ALIAS     => 'metavar1',
171               });
172
173       Any variable-wide GLOBAL values passed to the new() constructor in the
174       configuration hash will also be applied.  Values explicitly specified
175       in a variable's define() configuration will override the respective
176       GLOBAL values.
177
178       The following configuration options may be specified
179
180       DEFAULT
181           The DEFAULT value is used to initialise the variable.
182
183               $state->define("drink", {
184                       DEFAULT => 'coffee',
185                   });
186
187               print $state->drink();        # prints "coffee"
188
189       ALIAS
190           The ALIAS option allows a number of alternative names to be
191           specified for this variable.  A single alias should be specified as
192           a string.  Multiple aliases can be specified as a reference to an
193           array of alternatives or as a string of names separated by vertical
194           bars, '|'.  e.g.:
195
196               # either
197               $state->define("name", {
198                       ALIAS  => 'person',
199                   });
200
201               # or
202               $state->define("name", {
203                       ALIAS => [ 'person', 'user', 'uid' ],
204                   });
205
206               # or
207               $state->define("name", {
208                       ALIAS => 'person|user|uid',
209                   });
210
211               $state->user('abw');     # equivalent to $state->name('abw');
212
213       ARGCOUNT
214           The ARGCOUNT option specifies the number of arguments that should
215           be supplied for this variable.  By default, no additional arguments
216           are expected for variables (ARGCOUNT_NONE).
217
218           The ARGCOUNT_* constants can be imported from the AppConfig module:
219
220               use AppConfig ':argcount';
221
222               $state->define('foo', { ARGCOUNT => ARGCOUNT_ONE });
223
224           or can be accessed directly from the AppConfig package:
225
226               use AppConfig;
227
228               $state->define('foo', { ARGCOUNT => AppConfig::ARGCOUNT_ONE });
229
230           The following values for ARGCOUNT may be specified.
231
232           ARGCOUNT_NONE (0)
233               Indicates that no additional arguments are expected.  If the
234               variable is identified in a confirguration file or in the
235               command line arguments, it is set to a value of 1 regardless of
236               whatever arguments follow it.
237
238           ARGCOUNT_ONE (1)
239               Indicates that the variable expects a single argument to be
240               provided.  The variable value will be overwritten with a new
241               value each time it is encountered.
242
243           ARGCOUNT_LIST (2)
244               Indicates that the variable expects multiple arguments.  The
245               variable value will be appended to the list of previous values
246               each time it is encountered.
247
248           ARGCOUNT_HASH (3)
249               Indicates that the variable expects multiple arguments and that
250               each argument is of the form "key=value".  The argument will be
251               split into a key/value pair and inserted into the hash of
252               values each time it is encountered.
253
254       ARGS
255           The ARGS option can also be used to specify advanced command line
256           options for use with AppConfig::Getopt, which itself delegates to
257           Getopt::Long.  See those two modules for more information on the
258           format and meaning of these options.
259
260               $state->define("name", {
261                       ARGS => "=i@",
262                   });
263
264       EXPAND
265           The EXPAND option specifies how the AppConfig::File processor
266           should expand embedded variables in the configuration file values
267           it reads.  By default, EXPAND is turned off (EXPAND_NONE) and no
268           expansion is made.
269
270           The EXPAND_* constants can be imported from the AppConfig module:
271
272               use AppConfig ':expand';
273
274               $state->define('foo', { EXPAND => EXPAND_VAR });
275
276           or can be accessed directly from the AppConfig package:
277
278               use AppConfig;
279
280               $state->define('foo', { EXPAND => AppConfig::EXPAND_VAR });
281
282           The following values for EXPAND may be specified.  Multiple values
283           should be combined with vertical bars , '|', e.g. "EXPAND_UID |
284           EXPAND_VAR").
285
286           EXPAND_NONE
287               Indicates that no variable expansion should be attempted.
288
289           EXPAND_VAR
290               Indicates that variables embedded as $var or $(var) should be
291               expanded to the values of the relevant AppConfig::State
292               variables.
293
294           EXPAND_UID
295               Indicates that '~' or '~uid' patterns in the string should be
296               expanded to the current users ($<), or specified user's home
297               directory.  In the first case, "~" is expanded to the value of
298               the "HOME" environment variable.  In the second case, the
299               "getpwnam()" method is used if it is available on your system
300               (which it isn't on Win32).
301
302           EXPAND_ENV
303               Inidicates that variables embedded as ${var} should be expanded
304               to the value of the relevant environment variable.
305
306           EXPAND_ALL
307               Equivalent to "EXPAND_VARS | EXPAND_UIDS | EXPAND_ENVS").
308
309           EXPAND_WARN
310               Indicates that embedded variables that are not defined should
311               raise a warning.  If PEDANTIC is set, this will cause the
312               read() method to return 0 immediately.
313
314       VALIDATE
315           Each variable may have a sub-routine or regular expression defined
316           which is used to validate the intended value for a variable before
317           it is set.
318
319           If VALIDATE is defined as a regular expression, it is applied to
320           the value and deemed valid if the pattern matches.  In this case,
321           the variable is then set to the new value.  A warning message is
322           generated if the pattern match fails.
323
324           VALIDATE may also be defined as a reference to a sub-routine which
325           takes as its arguments the name of the variable and its intended
326           value.  The sub-routine should return 1 or 0 to indicate that the
327           value is valid or invalid, respectively.  An invalid value will
328           cause a warning error message to be generated.
329
330           If the GLOBAL VALIDATE variable is set (see GLOBAL in DESCRIPTION
331           above) then this value will be used as the default VALIDATE for
332           each variable unless otherwise specified.
333
334               $state->define("age", {
335                       VALIDATE => '\d+',
336                   });
337
338               $state->define("pin", {
339                       VALIDATE => \&check_pin,
340                   });
341
342       ACTION
343           The ACTION option allows a sub-routine to be bound to a variable as
344           a callback that is executed whenever the variable is set.  The
345           ACTION is passed a reference to the AppConfig::State object, the
346           name of the variable and the value of the variable.
347
348           The ACTION routine may be used, for example, to post-process
349           variable data, update the value of some other dependant variable,
350           generate a warning message, etc.
351
352           Example:
353
354               $state->define("foo", { ACTION => \&my_notify });
355
356               sub my_notify {
357                   my $state = shift;
358                   my $var   = shift;
359                   my $val   = shift;
360
361                   print "$variable set to $value";
362               }
363
364               $state->foo(42);        # prints "foo set to 42"
365
366           Be aware that calling "$state->set()" to update the same variable
367           from within the ACTION function will cause a recursive loop as the
368           ACTION function is repeatedly called.
369
370   DEFINING VARIABLES USING THE COMPACT FORMAT
371       Variables may be defined in a compact format which allows any ALIAS and
372       ARGS values to be specified as part of the variable name.  This is
373       designed to mimic the behaviour of Johan Vromans' Getopt::Long module.
374
375       Aliases for a variable should be specified after the variable name,
376       separated by vertical bars, '|'.  Any ARGS parameter should be appended
377       after the variable name(s) and/or aliases.
378
379       The following examples are equivalent:
380
381           $state->define("foo", {
382                   ALIAS => [ 'bar', 'baz' ],
383                   ARGS  => '=i',
384               });
385
386           $state->define("foo|bar|baz=i");
387
388   READING AND MODIFYING VARIABLE VALUES
389       AppConfig::State defines two methods to manipulate variable values:
390
391           set($variable, $value);
392           get($variable);
393
394       Both functions take the variable name as the first parameter and
395       "set()" takes an additional parameter which is the new value for the
396       variable.  "set()" returns 1 or 0 to indicate successful or
397       unsuccessful update of the variable value.  If there is an ACTION
398       routine associated with the named variable, the value returned will be
399       passed back from "set()".  The "get()" function returns the current
400       value of the variable.
401
402       Once defined, variables may be accessed directly as object methods
403       where the method name is the same as the variable name.  i.e.
404
405           $state->set("verbose", 1);
406
407       is equivalent to
408
409           $state->verbose(1);
410
411       Without parameters, the current value of the variable is returned.  If
412       a parameter is specified, the variable is set to that value and the
413       result of the set() operation is returned.
414
415           $state->age(29);        # sets 'age' to 29, returns 1 (ok)
416
417   VARLIST
418       The varlist() method can be used to extract a number of variables into
419       a hash array.  The first parameter should be a regular expression used
420       for matching against the variable names.
421
422           my %vars = $state->varlist("^file");   # all "file*" variables
423
424       A second parameter may be specified (any true value) to indicate that
425       the part of the variable name matching the regex should be removed when
426       copied to the target hash.
427
428           $state->file_name("/tmp/file");
429           $state->file_path("/foo:/bar:/baz");
430
431           my %vars = $state->varlist("^file_", 1);
432
433           # %vars:
434           #    name => /tmp/file
435           #    path => "/foo:/bar:/baz"
436
437   INTERNAL METHODS
438       The interal (private) methods of the AppConfig::State class are listed
439       below.
440
441       They aren't intended for regular use and potential users should
442       consider the fact that nothing about the internal implementation is
443       guaranteed to remain the same.  Having said that, the AppConfig::State
444       class is intended to co-exist and work with a number of other modules
445       and these are considered "friend" classes.  These methods are provided,
446       in part, as services to them.  With this acknowledged co-operation in
447       mind, it is safe to assume some stability in this core interface.
448
449       The _varname() method can be used to determine the real name of a
450       variable from an alias:
451
452           $varname->_varname($alias);
453
454       Note that all methods that take a variable name, including those listed
455       below, can accept an alias and automatically resolve it to the correct
456       variable name.  There is no need to call _varname() explicitly to do
457       alias expansion.  The _varname() method will fold all variables names
458       to lower case unless CASE sensititvity is set.
459
460       The _exists() method can be used to check if a variable has been
461       defined:
462
463           $state->_exists($varname);
464
465       The _default() method can be used to reset a variable to its default
466       value:
467
468           $state->_default($varname);
469
470       The _expand() method can be used to determine the EXPAND value for a
471       variable:
472
473           print "$varname EXPAND: ", $state->_expand($varname), "\n";
474
475       The _argcount() method returns the value of the ARGCOUNT attribute for
476       a variable:
477
478           print "$varname ARGCOUNT: ", $state->_argcount($varname), "\n";
479
480       The _validate() method can be used to determine if a new value for a
481       variable meets any validation criteria specified for it.  The variable
482       name and intended value should be passed in.  The methods returns a
483       true/false value depending on whether or not the validation succeeded:
484
485           print "OK\n" if $state->_validate($varname, $value);
486
487       The _pedantic() method can be called to determine the current value of
488       the PEDANTIC option.
489
490           print "pedantic mode is ", $state->_pedantic() ? "on" ; "off", "\n";
491
492       The _debug() method can be used to turn debugging on or off (pass 1 or
493       0 as a parameter).  It can also be used to check the debug state,
494       returning the current internal value of $AppConfig::State::DEBUG.  If a
495       new debug value is provided, the debug state is updated and the
496       previous state is returned.
497
498           $state->_debug(1);               # debug on, returns previous value
499
500       The _dump_var($varname) and _dump() methods may also be called for
501       debugging purposes.
502
503           $state->_dump_var($varname);    # show variable state
504           $state->_dump();                # show internal state and all vars
505

AUTHOR

507       Andy Wardley, <abw@wardley.org>
508
510       Copyright (C) 1997-2007 Andy Wardley.  All Rights Reserved.
511
512       Copyright (C) 1997,1998 Canon Research Centre Europe Ltd.
513
514       This module is free software; you can redistribute it and/or modify it
515       under the same terms as Perl itself.
516

SEE ALSO

518       AppConfig, AppConfig::File, AppConfig::Args, AppConfig::Getopt
519
520
521
522perl v5.32.1                      2021-01-26               AppConfig::State(3)
Impressum