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