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