1General(3) User Contributed Perl Documentation General(3)
2
3
4
6 Config::General - Generic Config Module
7
9 #
10 # the OOP way
11 use Config::General;
12 $conf = Config::General->new("rcfile");
13 my %config = $conf->getall;
14
15 #
16 # the procedural way
17 use Config::General qw(ParseConfig SaveConfig SaveConfigString);
18 my %config = ParseConfig("rcfile");
19
21 This module opens a config file and parses its contents for you. The
22 new method requires one parameter which needs to be a filename. The
23 method getall returns a hash which contains all options and its
24 associated values of your config file.
25
26 The format of config files supported by Config::General is inspired by
27 the well known Apache config format, in fact, this module is 100%
28 compatible to Apache configs, but you can also just use simple
29 name/value pairs in your config files.
30
31 In addition to the capabilities of an Apache config file it supports
32 some enhancements such as here-documents, C-style comments or multiline
33 options.
34
36 new()
37 Possible ways to call new():
38
39 $conf = Config::General->new("rcfile");
40
41 $conf = Config::General->new(\%somehash);
42
43 $conf = Config::General->new( %options ); # see below for description of possible options
44
45 This method returns a Config::General object (a hash blessed into
46 "Config::General" namespace. All further methods must be used from
47 that returned object. see below.
48
49 You can use the new style with hash parameters or the old style
50 which is of course still supported. Possible parameters to new()
51 are:
52
53 * a filename of a configfile, which will be opened and parsed by
54 the parser
55
56 or
57
58 * a hash reference, which will be used as the config.
59
60 An alternative way to call new() is supplying an option- hash with
61 one or more of the following keys set:
62
63 -ConfigFile
64 A filename or a filehandle, i.e.:
65
66 -ConfigFile => "rcfile" or -ConfigFile => \$FileHandle
67
68 -ConfigHash
69 A hash reference, which will be used as the config, i.e.:
70
71 -ConfigHash => \%somehash
72
73 -String
74 A string which contains a whole config, or an arrayref
75 containing the whole config line by line. The parser will
76 parse the contents of the string instead of a file. i.e:
77
78 -String => $complete_config
79
80 it is also possible to feed an array reference to -String:
81
82 -String => \@config_lines
83
84 -AllowMultiOptions
85 If the value is "no", then multiple identical options are
86 disallowed. The default is "yes". i.e.:
87
88 -AllowMultiOptions => "yes"
89
90 see IDENTICAL OPTIONS for details.
91
92 -LowerCaseNames
93 If set to a true value, then all options found in the config
94 will be converted to lowercase. This allows you to provide
95 case-in-sensitive configs. The values of the options will not
96 lowercased.
97
98 -UseApacheInclude
99 If set to a true value, the parser will consider "include ..."
100 as valid include statement (just like the well known Apache
101 include statement).
102
103 It also supports apache's "IncludeOptional" statement with the
104 same behavior, that is, if the include file doesn't exist no
105 error will be thrown.
106
107 -IncludeRelative
108 If set to a true value, included files with a relative path
109 (i.e. "cfg/blah.conf") will be opened from within the location
110 of the configfile instead from within the location of the
111 script($0). This works only if the configfile has a absolute
112 pathname (i.e. "/etc/main.conf").
113
114 If the variable -ConfigPath has been set and if the file to be
115 included could not be found in the location relative to the
116 current config file, the module will search within -ConfigPath
117 for the file. See the description of -ConfigPath for more
118 details.
119
120 -IncludeDirectories
121 If set to a true value, you may specify include a directory, in
122 which case all files inside the directory will be loaded in
123 ASCII order. Directory includes will not recurse into
124 subdirectories. This is comparable to including a directory in
125 Apache-style config files.
126
127 -IncludeGlob
128 If set to a true value, you may specify a glob pattern for an
129 include to include all matching files (e.g. <<include
130 conf.d/*.conf>>). Also note that as with standard file
131 patterns, * will not match dot-files, so <<include dir/*>> is
132 often more desirable than including a directory with
133 -IncludeDirectories.
134
135 An include option will not cause a parser error if the glob
136 didn't return anything.
137
138 -IncludeAgain
139 If set to a true value, you will be able to include a sub-
140 configfile multiple times. With the default, false, you will
141 get a warning about duplicate includes and only the first
142 include will succeed.
143
144 Reincluding a configfile can be useful if it contains data that
145 you want to be present in multiple places in the data tree.
146 See the example under "INCLUDES".
147
148 Note, however, that there is currently no check for include
149 recursion.
150
151 -ConfigPath
152 As mentioned above, you can use this variable to specify a
153 search path for relative config files which have to be
154 included. Config::General will search within this path for the
155 file if it cannot find the file at the location relative to the
156 current config file.
157
158 To provide multiple search paths you can specify an array
159 reference for the path. For example:
160
161 @path = qw(/usr/lib/perl /nfs/apps/lib /home/lib);
162 ..
163 -ConfigPath => \@path
164
165 -MergeDuplicateBlocks
166 If set to a true value, then duplicate blocks, that means
167 blocks and named blocks, will be merged into a single one (see
168 below for more details on this). The default behavior of
169 Config::General is to create an array if some junk in a config
170 appears more than once.
171
172 -MergeDuplicateOptions
173 If set to a true value, then duplicate options will be merged.
174 That means, if the same option occurs more than once, the last
175 one will be used in the resulting config hash.
176
177 Setting this option implies -AllowMultiOptions == false unless
178 you set -AllowMultiOptions explicit to 'true'. In this case
179 duplicate blocks are allowed and put into an array but
180 duplicate options will be merged.
181
182 -AutoLaunder
183 If set to a true value, then all values in your config file
184 will be laundered to allow them to be used under a -T taint
185 flag. This could be regarded as circumventing the purpose of
186 the -T flag, however, if the bad guys can mess with your config
187 file, you have problems that -T will not be able to stop.
188 AutoLaunder will only handle a config file being read from
189 -ConfigFile.
190
191 -AutoTrue
192 If set to a true value, then options in your config file, whose
193 values are set to true or false values, will be normalised to 1
194 or 0 respectively.
195
196 The following values will be considered as true:
197
198 yes, on, 1, true
199
200 The following values will be considered as false:
201
202 no, off, 0, false
203
204 This effect is case-insensitive, i.e. both "Yes" or "No" will
205 result in 1.
206
207 -FlagBits
208 This option takes one required parameter, which must be a hash
209 reference.
210
211 The supplied hash reference needs to define variables for which
212 you want to preset values. Each variable you have defined in
213 this hash-ref and which occurs in your config file, will cause
214 this variable being set to the preset values to which the value
215 in the config file refers to.
216
217 Multiple flags can be used, separated by the pipe character |.
218
219 Well, an example will clarify things:
220
221 my $conf = Config::General->new(
222 -ConfigFile => "rcfile",
223 -FlagBits => {
224 Mode => {
225 CLEAR => 1,
226 STRONG => 1,
227 UNSECURE => "32bit" }
228 }
229 );
230
231 In this example we are defining a variable named "Mode" which
232 may contain one or more of "CLEAR", "STRONG" and "UNSECURE" as
233 value.
234
235 The appropriate config entry may look like this:
236
237 # rcfile
238 Mode = CLEAR | UNSECURE
239
240 The parser will create a hash which will be the value of the
241 key "Mode". This hash will contain all flags which you have
242 pre-defined, but only those which were set in the config will
243 contain the pre-defined value, the other ones will be
244 undefined.
245
246 The resulting config structure would look like this after
247 parsing:
248
249 %config = (
250 Mode => {
251 CLEAR => 1,
252 UNSECURE => "32bit",
253 STRONG => undef,
254 }
255 );
256
257 This method allows the user (or, the "maintainer" of the
258 configfile for your application) to set multiple pre-defined
259 values for one option.
260
261 Please beware, that all occurrences of those variables will be
262 handled this way, there is no way to distinguish between
263 variables in different scopes. That means, if "Mode" would
264 also occur inside a named block, it would also parsed this way.
265
266 Values which are not defined in the hash-ref supplied to the
267 parameter -FlagBits and used in the corresponding variable in
268 the config will be ignored.
269
270 Example:
271
272 # rcfile
273 Mode = BLAH | CLEAR
274
275 would result in this hash structure:
276
277 %config = (
278 Mode => {
279 CLEAR => 1,
280 UNSECURE => undef,
281 STRONG => undef,
282 }
283 );
284
285 "BLAH" will be ignored silently.
286
287 -DefaultConfig
288 This can be a hash reference or a simple scalar (string) of a
289 config. This causes the module to preset the resulting config
290 hash with the given values, which allows you to set default
291 values for particular config options directly.
292
293 Note that you probably want to use this with
294 -MergeDuplicateOptions, otherwise a default value already in
295 the configuration file will produce an array of two values.
296
297 -Tie
298 -Tie takes the name of a Tie class as argument that each new
299 hash should be based off of.
300
301 This hash will be used as the 'backing hash' instead of a
302 standard Perl hash, which allows you to affect the way,
303 variable storing will be done. You could, for example supply a
304 tied hash, say Tie::DxHash, which preserves ordering of the
305 keys in the config (which a standard Perl hash won't do). Or,
306 you could supply a hash tied to a DBM file to save the parsed
307 variables to disk.
308
309 There are many more things to do in tie-land, see tie to get
310 some interesting ideas.
311
312 If you want to use the -Tie feature together with
313 -DefaultConfig make sure that the hash supplied to
314 -DefaultConfig must be tied to the same Tie class.
315
316 Make sure that the hash which receives the generated hash
317 structure (e.g. which you are using in the assignment: %hash =
318 $config->getall()) must be tied to the same Tie class.
319
320 Example:
321
322 use Config::General qw(ParseConfig);
323 use Tie::IxHash;
324 tie my %hash, "Tie::IxHash";
325 %hash = ParseConfig(
326 -ConfigFile => shift(),
327 -Tie => "Tie::IxHash"
328 );
329
330 -InterPolateVars
331 If set to a true value, variable interpolation will be done on
332 your config input. See Config::General::Interpolated for more
333 information.
334
335 -InterPolateEnv
336 If set to a true value, environment variables can be used in
337 configs.
338
339 This implies -InterPolateVars.
340
341 -AllowSingleQuoteInterpolation
342 By default variables inside single quotes will not be
343 interpolated. If you turn on this option, they will be
344 interpolated as well.
345
346 -ExtendedAccess
347 If set to a true value, you can use object oriented (extended)
348 methods to access the parsed config. See
349 Config::General::Extended for more information.
350
351 -StrictObjects
352 By default this is turned on, which causes Config::General to
353 croak with an error if you try to access a non-existent key
354 using the OOP-way (-ExtendedAcess enabled). If you turn
355 -StrictObjects off (by setting to 0 or "no") it will just
356 return an empty object/hash/scalar. This is valid for OOP-
357 access 8via AUTOLOAD and for the methods obj(), hash() and
358 value().
359
360 -StrictVars
361 By default this is turned on, which causes Config::General to
362 croak with an error if an undefined variable with
363 InterPolateVars turned on occurs in a config. Set to false
364 (i.e. 0) to avoid such error messages.
365
366 -SplitPolicy
367 You can influence the way how Config::General decides which
368 part of a line in a config file is the key and which one is the
369 value. By default it tries its best to guess. That means you
370 can mix equalsign assignments and whitespace assignments.
371
372 However, sometime you may wish to make it more strictly for
373 some reason. In this case you can set -SplitPolicy. The
374 possible values are: 'guess' which is the default, 'whitespace'
375 which causes the module to split by whitespace, 'equalsign'
376 which causes it to split strictly by equal sign, or 'custom'.
377 In the latter case you must also set -SplitDelimiter to some
378 regular expression of your choice. For example:
379
380 -SplitDelimiter => '\s*:\s*'
381
382 will cause the module to split by colon while whitespace which
383 surrounds the delimiter will be removed.
384
385 Please note that the delimiter used when saving a config
386 (save_file() or save_string()) will be chosen according to the
387 current -SplitPolicy. If -SplitPolicy is set to 'guess' or
388 'whitespace', 3 spaces will be used to delimit saved options.
389 If 'custom' is set, then you need to set -StoreDelimiter.
390
391 -SplitDelimiter
392 Set this to any arbitrary regular expression which will be used
393 for option/value splitting. -SplitPolicy must be set to
394 'custom' to make this work.
395
396 -StoreDelimiter
397 You can use this parameter to specify a custom delimiter to use
398 when saving configs to a file or string. You only need to set
399 it if you want to store the config back to disk and if you have
400 -SplitPolicy set to 'custom'.
401
402 However, this parameter takes precedence over whatever is set
403 for -SplitPolicy.
404
405 Be very careful with this parameter.
406
407 -CComments
408 Config::General is able to notice c-style comments (see section
409 COMMENTS). But for some reason you might no need this. In this
410 case you can turn this feature off by setting -CComments to a
411 false value('no', 0, 'off').
412
413 By default -CComments is turned on.
414
415 -BackslashEscape
416 Deprecated Option.
417
418 -SlashIsDirectory
419 If you turn on this parameter, a single slash as the last
420 character of a named block will be considered as a directory
421 name.
422
423 By default this flag is turned off, which makes the module
424 somewhat incompatible to Apache configs, since such a setup
425 will be normally considered as an explicit empty block, just as
426 XML defines it.
427
428 For example, if you have the following config:
429
430 <Directory />
431 Index index.awk
432 </Directory>
433
434 you will get such an error message from the parser:
435
436 EndBlock "</Directory>" has no StartBlock statement (level: 1, chunk 10)!
437
438 This is caused by the fact that the config chunk below will be
439 internally converted to:
440
441 <Directory></Directory>
442 Index index.awk
443 </Directory>
444
445 Now there is one '</Directory>' too much. The proper solution
446 is to use quotation to circumvent this error:
447
448 <Directory "/">
449 Index index.awk
450 </Directory>
451
452 However, a raw apache config comes without such quotes. In this
453 case you may consider to turn on -SlashIsDirectory.
454
455 Please note that this is a new option (incorporated in version
456 2.30), it may lead to various unexpected side effects or other
457 failures. You've been warned.
458
459 -UseApacheIfDefine
460 Enables support for Apache <IfDefine> ... </IfDefine>. See
461 -Define.
462
463 -Define
464 Defines the symbols to be used for conditional configuration
465 files. Allowed arguments: scalar, scalar ref, array ref or
466 hash ref.
467
468 Examples:
469
470 -Define => 'TEST'
471 -Define => \$testOrProduction
472 -Define => [qw(TEST VERBOSE)]
473 -Define => {TEST => 1, VERBOSE => 1}
474
475 Sample configuration:
476
477 <Logging>
478 <IfDefine TEST>
479 Level Debug
480 include test/*.cfg
481 </IfDef>
482 <IfDefine !TEST>
483 Level Notice
484 include production/*.cfg
485 </IfDefine>
486 </Logging>
487
488 -ApacheCompatible
489 Over the past years a lot of options has been incorporated into
490 Config::General to be able to parse real Apache configs.
491
492 The new -ApacheCompatible option now makes it possible to tweak
493 all options in a way that Apache configs can be parsed.
494
495 This is called "apache compatibility mode" - if you will ever
496 have problems with parsing Apache configs without this option
497 being set, you'll get no help by me. Thanks :)
498
499 The following options will be set:
500
501 UseApacheInclude = 1
502 IncludeRelative = 1
503 IncludeDirectories = 1
504 IncludeGlob = 1
505 SlashIsDirectory = 1
506 SplitPolicy = 'whitespace'
507 CComments = 0
508 UseApacheIfDefine = 1
509
510 Take a look into the particular documentation sections what
511 those options are doing.
512
513 Beside setting some options it also turns off support for
514 explicit empty blocks.
515
516 -UTF8
517 If turned on, all files will be opened in utf8 mode. This may
518 not work properly with older versions of Perl.
519
520 -SaveSorted
521 If you want to save configs in a sorted manner, turn this
522 parameter on. It is not enabled by default.
523
524 -NoEscape
525 If you want to use the data ( scalar or final leaf ) without
526 escaping special character, turn this parameter on. It is not
527 enabled by default.
528
529 -NormalizeBlock
530 Takes a subroutine reference as parameter and gets the current
531 block or blockname passed as parameter and is expected to
532 return it in some altered way as a scalar string. The sub will
533 be called before anything else will be done by the module
534 itself (e.g. interpolation).
535
536 Example:
537
538 -NormalizeBlock => sub { my $x = shift; $x =~ s/\s*$//; $x; }
539
540 This removes trailing whitespaces of block names.
541
542 -NormalizeOption
543 Same as -NormalizeBlock but applied on options only.
544
545 -NormalizeValue
546 Same as -NormalizeBlock but applied on values only.
547
548 getall()
549 Returns a hash structure which represents the whole config.
550
551 files()
552 Returns a list of all files read in.
553
554 save_file()
555 Writes the config hash back to the hard disk. This method takes one
556 or two parameters. The first parameter must be the filename where
557 the config should be written to. The second parameter is optional,
558 it must be a reference to a hash structure, if you set it. If you
559 do not supply this second parameter then the internal config hash,
560 which has already been parsed, will be used.
561
562 Please note that any occurrence of comments will be ignored by
563 getall() and thus be lost after you call this method.
564
565 You need also to know that named blocks will be converted to nested
566 blocks (which is the same from the perl point of view). An example:
567
568 <user hans>
569 id 13
570 </user>
571
572 will become the following after saving:
573
574 <user>
575 <hans>
576 id 13
577 </hans>
578 </user>
579
580 Example:
581
582 $conf_obj->save_file("newrcfile", \%config);
583
584 or, if the config has already been parsed, or if it didn't change:
585
586 $conf_obj->save_file("newrcfile");
587
588 save_string()
589 This method is equivalent to the previous save_file(), but it does
590 not store the generated config to a file. Instead it returns it as
591 a string, which you can save yourself afterwards.
592
593 It takes one optional parameter, which must be a reference to a
594 hash structure. If you omit this parameter, the internal config
595 hash, which has already been parsed, will be used.
596
597 Example:
598
599 my $content = $conf_obj->save_string(\%config);
600
601 or:
602
603 my $content = $conf_obj->save_string();
604
606 Lines beginning with # and empty lines will be ignored. (see section
607 COMMENTS!) Spaces at the beginning and the end of a line will also be
608 ignored as well as tabulators. If you need spaces at the end or the
609 beginning of a value you can surround it with double quotes. An option
610 line starts with its name followed by a value. An equal sign is
611 optional. Some possible examples:
612
613 user max
614 user = max
615 user max
616
617 If there are more than one statements with the same name, it will
618 create an array instead of a scalar. See the example below.
619
620 The method getall returns a hash of all values.
621
623 You can define a block of options. A block looks much like a block in
624 the wellknown Apache config format. It starts with <blockname> and ends
625 with </blockname>.
626
627 A block start and end cannot be on the same line.
628
629 An example:
630
631 <database>
632 host = muli
633 user = moare
634 dbname = modb
635 dbpass = D4r_9Iu
636 </database>
637
638 Blocks can also be nested. Here is a more complicated example:
639
640 user = hans
641 server = mc200
642 db = maxis
643 passwd = D3rf$
644 <jonas>
645 user = tom
646 db = unknown
647 host = mila
648 <tablestructure>
649 index int(100000)
650 name char(100)
651 prename char(100)
652 city char(100)
653 status int(10)
654 allowed moses
655 allowed ingram
656 allowed joice
657 </tablestructure>
658 </jonas>
659
660 The hash which the method getall returns look like that:
661
662 print Data::Dumper(\%hash);
663 $VAR1 = {
664 'passwd' => 'D3rf$',
665 'jonas' => {
666 'tablestructure' => {
667 'prename' => 'char(100)',
668 'index' => 'int(100000)',
669 'city' => 'char(100)',
670 'name' => 'char(100)',
671 'status' => 'int(10)',
672 'allowed' => [
673 'moses',
674 'ingram',
675 'joice',
676 ]
677 },
678 'host' => 'mila',
679 'db' => 'unknown',
680 'user' => 'tom'
681 },
682 'db' => 'maxis',
683 'server' => 'mc200',
684 'user' => 'hans'
685 };
686
687 If you have turned on -LowerCaseNames (see new()) then blocks as in the
688 following example:
689
690 <Dir>
691 <AttriBUTES>
692 Owner root
693 </attributes>
694 </dir>
695
696 would produce the following hash structure:
697
698 $VAR1 = {
699 'dir' => {
700 'attributes' => {
701 'owner' => "root",
702 }
703 }
704 };
705
706 As you can see, the keys inside the config hash are normalized.
707
708 Please note, that the above config block would result in a valid hash
709 structure, even if -LowerCaseNames is not set! This is because
710 Config::General does not use the block names to check if a block ends,
711 instead it uses an internal state counter, which indicates a block end.
712
713 If the module cannot find an end-block statement, then this block will
714 be ignored.
715
717 If you need multiple blocks of the same name, then you have to name
718 every block. This works much like Apache config. If the module finds a
719 named block, it will create a hashref with the left part of the named
720 block as the key containing one or more hashrefs with the right part of
721 the block as key containing everything inside the block(which may again
722 be nested!). As examples says more than words:
723
724 # given the following sample
725 <Directory /usr/frisco>
726 Limit Deny
727 Options ExecCgi Index
728 </Directory>
729 <Directory /usr/frik>
730 Limit DenyAll
731 Options None
732 </Directory>
733
734 # you will get:
735
736 $VAR1 = {
737 'Directory' => {
738 '/usr/frik' => {
739 'Options' => 'None',
740 'Limit' => 'DenyAll'
741 },
742 '/usr/frisco' => {
743 'Options' => 'ExecCgi Index',
744 'Limit' => 'Deny'
745 }
746 }
747 };
748
749 You cannot have more than one named block with the same name because it
750 will be stored in a hashref and therefore be overwritten if a block
751 occurs once more.
752
754 The normal behavior of Config::General is to look for whitespace in
755 block names to decide if it's a named block or just a simple block.
756
757 Sometimes you may need blocknames which have whitespace in their names.
758
759 With named blocks this is no problem, as the module only looks for the
760 first whitespace:
761
762 <person hugo gera>
763 </person>
764
765 would be parsed to:
766
767 $VAR1 = {
768 'person' => {
769 'hugo gera' => {
770 },
771 }
772 };
773
774 The problem occurs, if you want to have a simple block containing
775 whitespace:
776
777 <hugo gera>
778 </hugo gera>
779
780 This would be parsed as a named block, which is not what you wanted. In
781 this very case you may use quotation marks to indicate that it is not a
782 named block:
783
784 <"hugo gera">
785 </"hugo gera">
786
787 The save() method of the module inserts automatically quotation marks
788 in such cases.
789
791 Beside the notation of blocks mentioned above it is possible to use
792 explicit empty blocks.
793
794 Normally you would write this in your config to define an empty block:
795
796 <driver Apache>
797 </driver>
798
799 To save writing you can also write:
800
801 <driver Apache/>
802
803 which is the very same as above. This works for normal blocks and for
804 named blocks.
805
807 You may have more than one line of the same option with different
808 values. Example:
809
810 log log1
811 log log2
812 log log2
813
814 You will get a scalar if the option occurred only once or an array if
815 it occurred more than once. If you expect multiple identical options,
816 then you may need to check if an option occurred more than once:
817
818 $allowed = $hash{jonas}->{tablestructure}->{allowed};
819 if (ref($allowed) eq "ARRAY") {
820 @ALLOWED = @{$allowed};
821 else {
822 @ALLOWED = ($allowed);
823 }
824 }
825
826 The same applies to blocks and named blocks too (they are described in
827 more detail below). For example, if you have the following config:
828
829 <dir blah>
830 user max
831 </dir>
832 <dir blah>
833 user hannes
834 </dir>
835
836 then you would end up with a data structure like this:
837
838 $VAR1 = {
839 'dir' => {
840 'blah' => [
841 {
842 'user' => 'max'
843 },
844 {
845 'user' => 'hannes'
846 }
847 ]
848 }
849 };
850
851 As you can see, the two identical blocks are stored in a hash which
852 contains an array(-reference) of hashes.
853
854 Under some rare conditions you might not want this behavior with blocks
855 (and named blocks too). If you want to get one single hash with the
856 contents of both identical blocks, then you need to turn the new()
857 parameter -MergeDuplicateBlocks on (see above). The parsed structure of
858 the example above would then look like this:
859
860 $VAR1 = {
861 'dir' => {
862 'blah' => {
863 'user' => [
864 'max',
865 'hannes'
866 ]
867 }
868 }
869 };
870
871 As you can see, there is only one hash "dir->{blah}" containing
872 multiple "user" entries. As you can also see, turning on
873 -MergeDuplicateBlocks does not affect scalar options (i.e. "option =
874 value"). In fact you can tune merging of duplicate blocks and options
875 independent from each other.
876
877 If you don't want to allow more than one identical options, you may
878 turn it off by setting the flag AllowMultiOptions in the new() method
879 to "no". If turned off, Config::General will complain about multiple
880 occurring options with identical names!
881
882 FORCE SINGLE VALUE ARRAYS
883 You may also force a single config line to get parsed into an array by
884 turning on the option -ForceArray and by surrounding the value of the
885 config entry by []. Example:
886
887 hostlist = [ foo.bar ]
888
889 Will be a singlevalue array entry if the option is turned on. If you
890 want it to remain to be an array you have to turn on -ForceArray during
891 save too.
892
894 If you have a config value, which is too long and would take more than
895 one line, you can break it into multiple lines by using the backslash
896 character at the end of the line. The Config::General module will
897 concatenate those lines to one single-value.
898
899 Example:
900
901 command = cat /var/log/secure/tripwire | \
902 mail C<-s> "report from tripwire" \
903 honey@myotherhost.nl
904
905 command will become: "cat /var/log/secure/tripwire | mail "-s" 'report
906 from twire' honey@myotherhost.nl"
907
909 You can also define a config value as a so called "here-document". You
910 must tell the module an identifier which indicates the end of a here
911 document. An identifier must follow a "<<".
912
913 Example:
914
915 message <<EOF
916 we want to
917 remove the
918 homedir of
919 root.
920 EOF
921
922 Everything between the two "EOF" strings will be in the option message.
923
924 There is a special feature which allows you to use indentation with
925 here documents. You can have any amount of whitespace or tabulators in
926 front of the end identifier. If the module finds spaces or tabs then it
927 will remove exactly those amount of spaces from every line inside the
928 here-document.
929
930 Example:
931
932 message <<EOF
933 we want to
934 remove the
935 homedir of
936 root.
937 EOF
938
939 After parsing, message will become:
940
941 we want to
942 remove the
943 homedir of
944 root.
945
946 because there were the string " " in front of EOF, which were cut
947 from every line inside the here-document.
948
950 You can include an external file at any position in your config file
951 using the following statement in your config file:
952
953 <<include externalconfig.rc>>
954
955 If you turned on -UseApacheInclude (see new()), then you can also use
956 the following statement to include an external file:
957
958 include externalconfig.rc
959
960 This file will be inserted at the position where it was found as if the
961 contents of this file were directly at this position.
962
963 You can also recursively include files, so an included file may include
964 another one and so on. Beware that you do not recursively load the
965 same file, you will end with an error message like "too many open files
966 in system!".
967
968 By default included files with a relative pathname will be opened from
969 within the current working directory. Under some circumstances it maybe
970 possible to open included files from the directory, where the
971 configfile resides. You need to turn on the option -IncludeRelative
972 (see new()) if you want that. An example:
973
974 my $conf = Config::General(
975 -ConfigFile => "/etc/crypt.d/server.cfg"
976 -IncludeRelative => 1
977 );
978
979 /etc/crypt.d/server.cfg:
980
981 <<include acl.cfg>>
982
983 In this example Config::General will try to include acl.cfg from
984 /etc/crypt.d:
985
986 /etc/crypt.d/acl.cfg
987
988 The default behavior (if -IncludeRelative is not set!) will be to open
989 just acl.cfg, wherever it is, i.e. if you did a
990 chdir("/usr/local/etc"), then Config::General will include:
991
992 /usr/local/etc/acl.cfg
993
994 Include statements can be case insensitive (added in version 1.25).
995
996 Include statements will be ignored within C-Comments and here-
997 documents.
998
999 By default, a config file will only be included the first time it is
1000 referenced. If you wish to include a file in multiple places, set
1001 /-IncludeAgain to true. But be warned: this may lead to infinite loops,
1002 so make sure, you're not including the same file from within itself!
1003
1004 Example:
1005
1006 # main.cfg
1007 <object billy>
1008 class=Some::Class
1009 <printers>
1010 include printers.cfg
1011 </printers>
1012 # ...
1013 </object>
1014 <object bob>
1015 class=Another::Class
1016 <printers>
1017 include printers.cfg
1018 </printers>
1019 # ...
1020 </object>
1021
1022 Now "printers.cfg" will be include in both the "billy" and "bob"
1023 objects.
1024
1025 You will have to be careful to not recursively include a file.
1026 Behaviour in this case is undefined.
1027
1029 A comment starts with the number sign #, there can be any number of
1030 spaces and/or tab stops in front of the #.
1031
1032 A comment can also occur after a config statement. Example:
1033
1034 username = max # this is the comment
1035
1036 If you want to comment out a large block you can use C-style comments.
1037 A /* signals the begin of a comment block and the */ signals the end of
1038 the comment block. Example:
1039
1040 user = max # valid option
1041 db = tothemax
1042 /*
1043 user = andors
1044 db = toand
1045 */
1046
1047 In this example the second options of user and db will be ignored.
1048 Please beware of the fact, if the Module finds a /* string which is the
1049 start of a comment block, but no matching end block, it will ignore the
1050 whole rest of the config file!
1051
1052 NOTE: If you require the # character (number sign) to remain in the
1053 option value, then you can use a backslash in front of it, to escape
1054 it. Example:
1055
1056 bgcolor = \#ffffcc
1057
1058 In this example the value of $config{bgcolor} will be "#ffffcc",
1059 Config::General will not treat the number sign as the begin of a
1060 comment because of the leading backslash.
1061
1062 Inside here-documents escaping of number signs is NOT required!
1063
1065 You can alter the behavior of the parser by supplying closures which
1066 will be called on certain hooks during config file processing and
1067 parsing.
1068
1069 The general aproach works like this:
1070
1071 sub ck {
1072 my($file, $base) = @_;
1073 print "_open() tries $file ... ";
1074 if ($file =~ /blah/) {
1075 print "ignored\n";
1076 return (0);
1077 } else {
1078 print "allowed\n";
1079 return (1, @_);
1080 }
1081 }
1082
1083 my %c = ParseConfig(
1084 -IncludeGlob => 1,
1085 -UseApacheInclude => 1,
1086 -ConfigFile => shift,
1087 -Plug => { pre_open => *ck }
1088 );
1089
1090 Output:
1091
1092 _open() tries cfg ... allowed
1093 _open() tries x/*.conf ... allowed
1094 _open() tries x/1.conf ... allowed
1095 _open() tries x/2.conf ... allowed
1096 _open() tries x/blah.conf ... ignored
1097
1098 As you can see, we wrote a little sub which takes a filename and a base
1099 directory as parameters. We tell Config::General via the Plug parameter
1100 of new() to call this sub everytime before it attempts to open a file.
1101
1102 General processing continues as usual if the first value of the
1103 returned array is true. The second value of that array depends on the
1104 kind of hook being called.
1105
1106 The following hooks are available so far:
1107
1108 pre_open
1109 Takes two parameters: filename and basedirectory.
1110
1111 Has to return an array consisting of 3 values:
1112
1113 - 1 or 0 (continue processing or not)
1114 - filename
1115 - base directory
1116
1117 pre_read
1118 Takes two parameters: the filehandle of the file to be read and an
1119 array containing the raw contents of said file.
1120
1121 This hook will be applied in _read(). File contents are already
1122 available at this stage, comments will be removed, here-docs
1123 normalized and the like. This hook gets the unaltered, original
1124 contents.
1125
1126 Has to return an array of 3 values:
1127
1128 - 1 or 0 (continue processing or not)
1129 - the filehandle
1130 - an array of strings
1131
1132 You can use this hook to apply your own normalizations or whatever.
1133
1134 Be careful when returning the abort value (1st value of returned
1135 array 0), since in this case nothing else would be done on the
1136 contents. If it still contains comments or something, they will be
1137 parsed as legal config options.
1138
1139 post_read
1140 Takes one parameter: a reference to an array containing the
1141 prepared config lines (after being processed by _read()).
1142
1143 This hook will be applied in _read() when everything else has been
1144 done.
1145
1146 Has to return an array of 2 values:
1147
1148 - 1 or 0 (continue processing or not) [Ignored for post hooks]
1149 - a reference to an array containing the config lines
1150
1151 pre_parse_value
1152 Takes 2 parameters: an option name and its value.
1153
1154 This hook will be applied in _parse_value() before any processing.
1155
1156 Has to return an array of 3 values:
1157
1158 - 1 or 0 (continue processing or not)
1159 - option name
1160 - value of the option
1161
1162 post_parse_value
1163 Almost identical to pre_parse_value, but will be applied after
1164 _parse_value() is finished and all usual processing and
1165 normalization is done.
1166
1167 Not implemented yet: hooks for variable interpolation and block
1168 parsing.
1169
1171 There is a way to access a parsed config the OO-way. Use the module
1172 Config::General::Extended, which is supplied with the Config::General
1173 distribution.
1174
1176 You can use variables inside your config files if you like. To do that
1177 you have to use the module Config::General::Interpolated, which is
1178 supplied with the Config::General distribution.
1179
1181 Config::General exports some functions too, which makes it somewhat
1182 easier to use it, if you like this.
1183
1184 How to import the functions:
1185
1186 use Config::General qw(ParseConfig SaveConfig SaveConfigString);
1187
1188 ParseConfig()
1189 This function takes exactly all those parameters, which are allowed
1190 to the new() method of the standard interface.
1191
1192 Example:
1193
1194 use Config::General qw(ParseConfig);
1195 my %config = ParseConfig(-ConfigFile => "rcfile", -AutoTrue => 1);
1196
1197 SaveConfig()
1198 This function requires two arguments, a filename and a reference to
1199 a hash structure.
1200
1201 Example:
1202
1203 use Config::General qw(SaveConfig);
1204 ..
1205 SaveConfig("rcfile", \%some_hash);
1206
1207 SaveConfigString()
1208 This function requires a reference to a config hash as parameter.
1209 It generates a configuration based on this hash as the object-
1210 interface method save_string() does.
1211
1212 Example:
1213
1214 use Config::General qw(ParseConfig SaveConfigString);
1215 my %config = ParseConfig(-ConfigFile => "rcfile");
1216 .. # change %config something
1217 my $content = SaveConfigString(\%config);
1218
1220 No environment variables will be used.
1221
1223 I recommend you to read the following documents, which are supplied
1224 with Perl:
1225
1226 perlreftut Perl references short introduction
1227 perlref Perl references, the rest of the story
1228 perldsc Perl data structures intro
1229 perllol Perl data structures: arrays of arrays
1230
1231 Config::General::Extended Object oriented interface to parsed configs
1232 Config::General::Interpolated Allows one to use variables inside config files
1233
1235 Copyright (c) 2000-2016 Thomas Linden
1236
1237 This library is free software; you can redistribute it and/or modify it
1238 under the same terms as Perl itself.
1239
1241 See rt.cpan.org for current bugs, if any.
1242
1244 None known.
1245
1247 To debug Config::General use the Perl debugger, see perldebug.
1248
1250 Config::General depends on the modules FileHandle,
1251 File::Spec::Functions, File::Glob, which all are shipped with Perl.
1252
1254 Thomas Linden <tlinden |AT| cpan.org>
1255
1257 2.63
1258
1259
1260
1261perl v5.30.1 2020-01-29 General(3)