File Coverage

blib/lib/Config/General.pm
Criterion Covered Total %
statement 165 409 40.3
branch 84 242 34.7
condition 14 54 25.9
subroutine 14 24 58.3
pod 7 9 77.7
total 284 738 38.4


line stmt bran cond sub pod time code
1             #
2             # Config::General.pm - Generic Config Module
3             #
4             # Purpose: Provide a convenient way for loading
5             # config values from a given file and
6             # return it as hash structure
7             #
8             # Copyright (c) 2000-2002 Thomas Linden .
9             # All Rights Reserved. Std. disclaimer applies.
10             # Artificial License, same as perl itself. Have fun.
11             #
12             # namespace
13             package Config::General;
14              
15 2     2   2066 use FileHandle;
  2         28719  
  2         13  
16 2     2   2929 use File::Spec::Functions qw(catfile catpath splitpath file_name_is_absolute);
  2         1843  
  2         297  
17 2     2   12 use strict;
  2         5  
  2         65  
18 2     2   11 use Carp;
  2         5  
  2         108  
19 2     2   11 use Exporter;
  2         6  
  2         111  
20              
21             $Config::General::VERSION = "2.18";
22              
23 2     2   11 use vars qw(@ISA @EXPORT);
  2         4  
  2         18338  
24             @ISA = qw(Exporter);
25             @EXPORT = qw(ParseConfig SaveConfig SaveConfigString);
26              
27             sub new {
28             #
29             # create new Config::General object
30             #
31 8     8 1 33 my($this, @param ) = @_;
32 8   33     52 my $class = ref($this) || $this;
33              
34             # define default options
35 8         197 my $self = {
36             AllowMultiOptions => 1,
37              
38             MergeDuplicateOptions => 0,
39             MergeDuplicateBlocks => 0,
40              
41             LowerCaseNames => 0,
42              
43             UseApacheInclude => 0,
44             IncludeRelative => 0,
45              
46             AutoTrue => 0,
47              
48             AutoTrueFlags => {
49             true => '^(on|yes|true|1)$',
50             false => '^(off|no|false|0)$',
51             },
52              
53             DefaultConfig => {},
54              
55             level => 1,
56              
57             InterPolateVars => 0,
58              
59             ExtendedAccess => 0,
60              
61             SplitPolicy => 'guess', # also possible: whitespace, equalsign and custom
62              
63             SplitDelimiter => 0, # must be set by the user if SplitPolicy is 'custom'
64              
65             StoreDelimiter => 0, # will be set by me unless user uses 'custom' policy
66              
67             CComments => 1, # by default turned on
68              
69             StrictObjects => 1, # be strict on non-existent keys in OOP mode
70              
71             StrictVars => 1, # be strict on undefined variables in Interpolate mode
72              
73             parsed => 0,
74             upperkey => "",
75             lastkey => "",
76             prevkey => " ",
77             };
78              
79             # create the class instance
80 8         26 bless($self,$class);
81              
82              
83 8 50       29 if ($#param >= 1) {
    0          
84             # use of the new hash interface!
85 8         56 my %conf = @param;
86              
87             # save the parameter list for ::Extended's new() calls
88 8         41 $self->{Params} = \%conf;
89              
90             # be backwards compatible
91 8 50       33 $self->{ConfigFile} = delete $conf{-file} if(exists $conf{-file});
92 8 50       28 $self->{ConfigHash} = delete $conf{-hash} if(exists $conf{-hash});
93              
94             # store input, file, handle, or array
95 8 50       54 $self->{ConfigFile} = delete $conf{-ConfigFile} if(exists $conf{-ConfigFile});
96 8 50       39 $self->{ConfigPath} = delete $conf{-ConfigPath} if(exists $conf{-ConfigPath});
97 8 50       53 $self->{ConfigHash} = delete $conf{-ConfigHash} if(exists $conf{-ConfigHash});
98              
99             # handle options which contains values we are needing (strings, hashrefs or the like)
100 8 50       31 if (exists $conf{-String} ) {
101 0 0       0 if ($conf{-String}) {
102 0         0 $self->{StringContent} = $conf{-String};
103             }
104 0         0 delete $conf{-String};
105             }
106 8 50       34 if (exists $conf{-FlagBits}) {
107 0 0 0     0 if ($conf{-FlagBits} && ref($conf{-FlagBits}) eq "HASH") {
108 0         0 $self->{FlagBits} = 1;
109 0         0 $self->{FlagBitsFlags} = $conf{-FlagBits};
110             }
111 0         0 delete $conf{-FlagBits};
112             }
113              
114 8 50       27 if (exists $conf{-DefaultConfig}) {
115 0 0 0     0 if ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq "HASH") {
    0 0        
116 0         0 $self->{DefaultConfig} = $conf{-DefaultConfig};
117             }
118             elsif ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq "") {
119 0         0 $self->_read($conf{-DefaultConfig}, "SCALAR");
120 0         0 $self->{DefaultConfig} = $self->_parse({}, $self->{content});
121 0         0 $self->{content} = ();
122             }
123 0         0 delete $conf{-DefaultConfig};
124 0         0 delete $conf{-BaseHash}; # ignore BaseHash if a default one was given
125             }
126              
127             # handle options which may either be true or false
128             # allowing "human" logic about what is true and what is not
129 8         32 foreach my $entry (keys %conf) {
130 24         35 my $key = $entry;
131 24         83 $key =~ s/^\-//;
132 24 50       70 if (! exists $self->{$key}) {
133 0         0 croak "Unknown parameter: $entry => \"$conf{$entry}\" (key: <$key>)\n";
134             }
135 24 50       240 if ($conf{$entry} =~ /$self->{AutoTrueFlags}->{true}/io) {
    0          
136 24         64 $self->{$key} = 1;
137             }
138             elsif ($conf{$entry} =~ /$self->{AutoTrueFlags}->{false}/io) {
139 0         0 $self->{$key} = 0;
140             }
141             else {
142             # keep it untouched
143 0         0 $self->{$key} = $conf{$entry};
144             }
145             }
146              
147 8 50       34 if ($self->{MergeDuplicateOptions}) {
148             # override if not set by user
149 0 0       0 if (! exists $conf{-AllowMultiOptions}) {
150 0         0 $self->{AllowMultiOptions} = 0;
151             }
152             }
153             }
154             elsif ($#param == 0) {
155             # use of the old style
156 0         0 $self->{ConfigFile} = $param[0];
157             }
158             else {
159             # this happens if $#param == -1,1 thus no param was given to new!
160 0         0 $self->{config} = {};
161 0         0 $self->{parsed} = 1;
162             }
163              
164             # prepare the split delimiter if needed
165 8 50       26 if ($self->{SplitPolicy} ne 'guess') {
166 0 0       0 if ($self->{SplitPolicy} eq 'whitespace') {
    0          
    0          
167 0         0 $self->{SplitDelimiter} = '\s+';
168 0 0       0 $self->{StoreDelimiter} = " " if(!$self->{StoreDelimiter});
169             }
170             elsif ($self->{SplitPolicy} eq 'equalsign') {
171 0         0 $self->{SplitDelimiter} = '\s*=\s*';
172 0 0       0 $self->{StoreDelimiter} = " = " if(!$self->{StoreDelimiter});
173             }
174             elsif ($self->{SplitPolicy} eq 'custom') {
175 0 0       0 if (! $self->{SplitDelimiter} ) {
176 0         0 croak "SplitPolicy set to 'custom' but no SplitDelimiter set.\n";
177             }
178             }
179             else {
180 0         0 croak "Unsupported SplitPolicy: $self->{SplitPolicy}.\n";
181             }
182             }
183             else {
184 8 50       35 $self->{StoreDelimiter} = " " if(!$self->{StoreDelimiter});
185             }
186              
187 8 50       30 if ($self->{InterPolateVars}) {
188             #
189             # we are blessing here again, to get into the ::InterPolated namespace
190             # for inheriting the methods available overthere, which we doesn't have.
191             #
192 0         0 bless($self, "Config::General::Interpolated");
193 0         0 eval {
194 0         0 require Config::General::Interpolated;
195             };
196 0 0       0 if ($@) {
197 0         0 croak $@;
198             }
199             # pre-compile the variable regexp
200 0         0 $self->{regex} = $self->_set_regex();
201             }
202              
203             # process as usual
204 8 50       24 if (!$self->{parsed}) {
205 8 50 33     52 if ($self->{DefaultConfig} && $self->{InterPolateVars}) {
206 0         0 $self->{DefaultConfig} = $self->_interpolate_hash($self->{DefaultConfig});
207             }
208 8 50 33     82 if (exists $self->{StringContent}) {
    50          
    50          
209             # consider the supplied string as config file
210 0         0 $self->_read($self->{StringContent}, "SCALAR");
211 0         0 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
212             }
213             elsif (exists $self->{ConfigHash}) {
214 0 0       0 if (ref($self->{ConfigHash}) eq "HASH") {
215             # initialize with given hash
216 0         0 $self->{config} = $self->{ConfigHash};
217 0         0 $self->{parsed} = 1;
218             }
219             else {
220 0         0 croak "Parameter -ConfigHash must be a hash reference!\n";
221             }
222             }
223             elsif (ref($self->{ConfigFile}) eq "GLOB" || ref($self->{ConfigFile}) eq "FileHandle") {
224             # use the file the glob points to
225 0         0 $self->_read($self->{ConfigFile});
226 0         0 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
227             }
228             else {
229 8 50       24 if ($self->{ConfigFile}) {
230             # open the file and read the contents in
231 8         22 $self->{configfile} = $self->{ConfigFile};
232 8 50       47 if ( file_name_is_absolute($self->{ConfigFile}) ) {
233             # look if is is an absolute path and save the basename if it is absolute
234 8         120 my ($volume, $path, undef) = splitpath($self->{ConfigFile});
235 8         174 $path =~ s#/$##; # remove eventually existing trailing slash
236             # $self->{configpath} = $path;
237 8 50       27 $self->{ConfigPath} = [] unless $self->{ConfigPath};
238 8         51 unshift @{$self->{ConfigPath}}, catpath($volume, $path, '');
  8         37  
239             }
240 8         124 $self->_open($self->{configfile});
241             # now, we parse immdediately, getall simply returns the whole hash
242 8         62 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
243             }
244             else {
245             # hm, no valid config file given, so try it as an empty object
246 0         0 $self->{config} = {};
247 0         0 $self->{parsed} = 1;
248             }
249             }
250             }
251              
252             #
253             # Submodule handling. Parsing is already done at this point.
254             #
255 8 50       30 if ($self->{ExtendedAccess}) {
256             #
257             # we are blessing here again, to get into the ::Extended namespace
258             # for inheriting the methods available overthere, which we doesn't have.
259             #
260 0         0 bless($self, "Config::General::Extended");
261 0         0 eval {
262 0         0 require Config::General::Extended;
263             };
264 0 0       0 if ($@) {
265 0         0 croak $@;
266             }
267             }
268              
269 8         58 return $self;
270             }
271              
272              
273              
274             sub getall {
275             #
276             # just return the whole config hash
277             #
278 8     8 1 13 my($this) = @_;
279 8 50       28 return (exists $this->{config} ? %{$this->{config}} : () );
  8         72  
280             }
281              
282              
283              
284             sub _open {
285             #
286             # open the config file
287             #
288 10     10   21 my($this, $configfile) = @_;
289 10         91 my $fh = new FileHandle;
290             ## added by ptandler, 03-04-16
291            
292 10 100 66     659 if( ! -e $configfile && defined($this->{ConfigPath}) ) {
293 2         4 foreach my $dir (@{$this->{ConfigPath}}) {
  2         104  
294 28 100       579 if( -e catfile($dir, $configfile) ) {
295 2         15 $configfile = catfile($dir, $configfile);
296 2         6 last;
297             };
298             }
299             }
300 10 50       230 if (-e $configfile) {
301 10 50       674 open $fh, "<$configfile" or croak "Could not open $configfile!($!)\n";
302 10         62 $this->_read($fh);
303             }
304             else {
305 0         0 croak "The file \"$configfile\" does not exist!\n";
306             }
307             }
308              
309              
310             sub _read {
311             #
312             # store the config contents in @content
313             #
314 10     10   21 my($this, $fh, $flag) = @_;
315 10         14 my(@stuff, @content, $c_comment, $longline, $hier, $hierend, @hierdoc);
316 10         16 local $_;
317              
318 10 50 33     47 if ($flag && $flag eq "SCALAR") {
319 0 0       0 if (ref($fh) eq "ARRAY") {
320 0         0 @stuff = @{$fh};
  0         0  
321             }
322             else {
323 0         0 @stuff = split "\n", $fh;
324             }
325             }
326             else {
327 10         2364 @stuff = <$fh>;
328             }
329              
330 10         64 foreach (@stuff) {
331 722         1123 chomp;
332              
333 722 50       1652 if ($this->{CComments}) {
334             # look for C-Style comments, if activated
335 722 50       2701 if (/(\s*\/\*.*\*\/\s*)/) {
    100          
    100          
336             # single c-comment on one line
337 0         0 s/\s*\/\*.*\*\/\s*//;
338             }
339             elsif (/^\s*\/\*/) {
340             # the beginning of a C-comment ("/*"), from now on ignore everything.
341 14 50       39 if (/\*\/\s*$/) {
342             # C-comment end is already there, so just ignore this line!
343 0         0 $c_comment = 0;
344             }
345             else {
346 14         25 $c_comment = 1;
347             }
348             }
349             elsif (/\*\//) {
350 14 50       36 if (!$c_comment) {
351 0         0 warn "invalid syntax: found end of C-comment without previous start!\n";
352             }
353 14         20 $c_comment = 0; # the current C-comment ends here, go on
354 14         69 s/^.*\*\///; # if there is still stuff, it will be read
355             }
356 722 100       1372 next if($c_comment); # ignore EVERYTHING from now on, IF it IS a C-Comment
357             }
358              
359              
360 636 50       1064 if ($hier) {
361             # inside here-doc, only look for $hierend marker
362 0 0       0 if (/^(\s*)\Q$hierend\E\s*$/) {
363 0         0 my $indent = $1; # preserve indentation
364 0         0 $hier .= " " . chr(182); # append a "¶" to the here-doc-name, so
365             # _parse will also preserver indentation
366 0 0       0 if ($indent) {
367 0         0 foreach (@hierdoc) {
368 0         0 s/^$indent//; # i.e. the end was: " EOF" then we remove " " from every here-doc line
369 0         0 $hier .= $_ . "\n"; # and store it in $hier
370             }
371             }
372             else {
373 0         0 $hier .= join "\n", @hierdoc; # there was no indentation of the end-string, so join it 1:1
374             }
375 0         0 push @{$this->{content}}, $hier; # push it onto the content stack
  0         0  
376 0         0 @hierdoc = ();
377 0         0 undef $hier;
378 0         0 undef $hierend;
379             }
380             else {
381             # everything else onto the stack
382 0         0 push @hierdoc, $_;
383             }
384 0         0 next;
385             }
386              
387             ###
388             ### non-heredoc entries from now on
389             ##
390              
391             # Remove comments and empty lines
392 636         861 s/(?
393 636 50       1201 next if /^\s*#/;
394 636 100       1681 next if /^\s*$/;
395              
396              
397              
398             # remove the \ char in front of masked "#", if any
399 514         671 s/\\#/#/g;
400              
401              
402              
403              
404             # look for here-doc identifier
405 514 50       1055 if ($this->{SplitPolicy} eq 'guess') {
406 514 50       1130 if (/^\s*(\S+?)(\s*=\s*|\s+)<<\s*(.+?)\s*$/) {
407 0         0 $hier = $1; # the actual here-doc variable name
408 0         0 $hierend = $3; # the here-doc identifier, i.e. "EOF"
409 0         0 next;
410             }
411             }
412             else {
413             # no guess, use one of the configured strict split policies
414 0 0       0 if (/^\s*(\S+?)($this->{SplitDelimiter})<<\s*(.+?)\s*$/) {
415 0         0 $hier = $1; # the actual here-doc variable name
416 0         0 $hierend = $3; # the here-doc identifier, i.e. "EOF"
417 0         0 next;
418             }
419             }
420              
421              
422              
423             # look for multiline option, indicated by a trailing backslash
424 514 50       1026 if (/\\$/) {
425 0         0 chop;
426 0         0 s/^\s*//;
427 0         0 $longline .= $_;
428 0         0 next;
429             }
430              
431              
432              
433             ###
434             ### any "normal" config lines from now on
435             ###
436              
437 514 50       780 if ($longline) {
438             # previous stuff was a longline and this is the last line of the longline
439 0         0 s/^\s*//;
440 0         0 $longline .= $_;
441 0         0 push @{$this->{content}}, $longline; # push it onto the content stack
  0         0  
442 0         0 undef $longline;
443 0         0 next;
444             }
445             else {
446             # look for include statement(s)
447 514         600 my $incl_file;
448 514 100 33     9395 if (/^\s*<>\s*$/i || (/^\s*include\s+(.+?)\s*$/i && $this->{UseApacheInclude})) {
      66        
449 2         8 $incl_file = $1;
450 2 50 33     25 if ( $this->{IncludeRelative} && $this->{configpath} && !file_name_is_absolute($incl_file) ) {
      33        
451             # include the file from within location of $this->{configfile}
452 0         0 $this->_open($incl_file);
453             }
454             else {
455             # include the file from within pwd, or absolute
456 2         12 $this->_open($incl_file);
457             }
458             }
459             else {
460             # standard entry, (option = value)
461 512         650 push @{$this->{content}}, $_;
  512         1484  
462             }
463             }
464              
465             }
466 10         262 return 1;
467             }
468              
469              
470              
471              
472              
473             sub _parse {
474             #
475             # parse the contents of the file
476             #
477 70     70   147 my($this, $config, $content) = @_;
478 70         81 my(@newcontent, $block, $blockname, $grab, $chunk,$block_level);
479 70         77 local $_;
480 70         91 my $indichar = chr(182); # ¶, inserted by _open, our here-doc indicator
481              
482 70         75 foreach (@{$content}) { # loop over content stack
  70         142  
483 1308         1785 chomp;
484 1308         1274 $chunk++;
485 1308         3819 $_ =~ s/^\s*//; # strip spaces @ end and begin
486 1308         6098 $_ =~ s/\s*$//;
487              
488             #
489             # build option value assignment, split current input
490             # using whitespace, equal sign or optionally here-doc
491             # separator (ascii 182).
492 1308         1470 my ($option,$value);
493 1308 50       2806 if (/$indichar/) {
494 0         0 ($option,$value) = split /\s*$indichar\s*/, $_, 2; # separated by heredoc-finding in _open()
495             }
496             else {
497 1308 50       2459 if ($this->{SplitPolicy} eq 'guess') {
498             # again the old regex. use equalsign SplitPolicy to get the
499             # 2.00 behavior. the new regexes were too odd.
500 1308         7190 ($option,$value) = split /\s*=\s*|\s+/, $_, 2;
501             }
502             else {
503             # no guess, use one of the configured strict split policies
504 0         0 ($option,$value) = split /$this->{SplitDelimiter}/, $_, 2;
505             }
506             }
507              
508 1308 50 66     5623 if ($value && $value =~ /^"/ && $value =~ /"$/) {
      33        
509 0         0 $value =~ s/^"//; # remove leading and trailing "
510 0         0 $value =~ s/"$//;
511             }
512 1308 100       3370 if (! defined $block) { # not inside a block @ the moment
    100          
    100          
513 450 100       1108 if (/^<([^\/]+?.*?)>$/) { # look if it is a block
    50          
514 62         137 $block = $1; # store block name
515 62         152 ($grab, $blockname) = split /\s\s*/, $block, 2; # is it a named block? if yes, store the name separately
516 62 50       145 if ($blockname) {
517 0         0 $block = $grab;
518             }
519 62 50       138 if ($this->{InterPolateVars}) {
520             # interpolate block(name), add "<" and ">" to the key, because
521             # it is sure that such keys does not exist otherwise.
522 0         0 $block = $this->_interpolate("<$block>", $block);
523 0 0       0 if ($blockname) {
524 0         0 $blockname = $this->_interpolate("<$blockname>", $blockname);
525             }
526             }
527 62 50       154 $block = lc($block) if $this->{LowerCaseNames}; # only for blocks lc(), if configured via new()
528 62         93 $this->{level} += 1;
529 62         146 undef @newcontent;
530 62         107 next;
531             }
532             elsif (/^<\/(.+?)>$/) { # it is an end block, but we don't have a matching block!
533 0         0 croak "EndBlock \"<\/$1>\" has no StartBlock statement (level: $this->{level}, chunk $chunk)!\n";
534             }
535             else { # insert key/value pair into actual node
536 388 50       762 $option = lc($option) if $this->{LowerCaseNames};
537 388 50       698 if (exists $config->{$option}) {
538 0 0       0 if ($this->{MergeDuplicateOptions}) {
539 0         0 $config->{$option} = $this->_parse_value($option, $value);
540             }
541             else {
542 0 0       0 if (! $this->{AllowMultiOptions} ) {
543             # no, duplicates not allowed
544 0         0 croak "Option \"$option\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
545             }
546             else {
547             # yes, duplicates allowed
548 0 0       0 if (ref($config->{$option}) ne "ARRAY") { # convert scalar to array
549 0         0 my $savevalue = $config->{$option};
550 0         0 delete $config->{$option};
551 0         0 push @{$config->{$option}}, $savevalue;
  0         0  
552             }
553 0         0 eval {
554             # check if arrays are supported by the underlying hash
555 0         0 my $i = scalar @{$config->{$option}};
  0         0  
556             };
557 0 0       0 if ($@) {
558 0         0 $config->{$option} = $this->_parse_value($option, $value);
559             }
560             else {
561 0         0 push @{$config->{$option}}, $this->_parse_value($option, $value); # it's already an array, just push
  0         0  
562             }
563             }
564             }
565             }
566             else {
567 388         789 $config->{$option} = $this->_parse_value($option, $value); # standard config option, insert key/value pair into node
568             }
569             }
570             }
571             elsif (/^<([^\/]+?.*?)>$/) { # found a start block inside a block, don't forget it
572 30         36 $block_level++; # $block_level indicates wether we are still inside a node
573 30         67 push @newcontent, $_; # push onto new content stack for later recursive call of _parse()
574             }
575             elsif (/^<\/(.+?)>$/) {
576 92 100       167 if ($block_level) { # this endblock is not the one we are searching for, decrement and push
577 30         33 $block_level--; # if it is 0, then the endblock was the one we searched for, see below
578 30         64 push @newcontent, $_; # push onto new content stack
579             }
580             else { # calling myself recursively, end of $block reached, $block_level is 0
581 62 50       93 if ($blockname) { # a named block, make it a hashref inside a hash within the current node
582 0         0 $this->_savelast($blockname);
583 0 0       0 if (exists $config->{$block}->{$blockname}) { # the named block already exists, make it an array
    0          
584 0 0       0 if ($this->{MergeDuplicateBlocks}) {
585             # just merge the new block with the same name as an existing one into
586             # this one.
587 0         0 $config->{$block}->{$blockname} = $this->_parse($config->{$block}->{$blockname}, \@newcontent);
588             }
589             else {
590 0 0       0 if (! $this->{AllowMultiOptions}) {
591 0         0 croak "Named block \"<$block $blockname>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
592             }
593             else { # preserve existing data
594 0         0 my $savevalue = $config->{$block}->{$blockname};
595 0         0 delete $config->{$block}->{$blockname};
596 0         0 my @ar;
597 0 0       0 if (ref $savevalue eq "ARRAY") {
598 0         0 push @ar, @{$savevalue}; # preserve array if any
  0         0  
599             }
600             else {
601 0         0 push @ar, $savevalue;
602             }
603 0         0 push @ar, $this->_parse( {}, \@newcontent); # append it
604 0         0 $config->{$block}->{$blockname} = \@ar;
605             }
606             }
607             }
608             elsif (ref($config->{$block}) eq "ARRAY") {
609 0         0 croak "Cannot add named block <$block $blockname> to hash! Block <$block> occurs more than once.\n"
610             ."Turn on -MergeDuplicateBlocks or make sure <$block> occurs only once in the config.\n";
611             }
612             else {
613             # the first occurence of this particular named block
614 0         0 $config->{$block}->{$blockname} = $this->_parse($config->{$block}->{$blockname}, \@newcontent);
615             }
616 0         0 $this->_backlast($blockname);
617             }
618             else { # standard block
619 62         165 $this->_savelast($block);
620 62 50       132 if (exists $config->{$block}) { # the block already exists, make it an array
621 0 0       0 if ($this->{MergeDuplicateBlocks}) {
622             # just merge the new block with the same name as an existing one into
623             # this one.
624 0         0 $config->{$block} = $this->_parse($config->{$block}, \@newcontent);
625             }
626             else {
627 0 0       0 if (! $this->{AllowMultiOptions}) {
628 0         0 croak "Block \"<$block>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
629             }
630             else {
631 0         0 my $savevalue = $config->{$block};
632 0         0 delete $config->{$block};
633 0         0 my @ar;
634 0 0       0 if (ref $savevalue eq "ARRAY") {
635 0         0 push @ar, @{$savevalue};
  0         0  
636             }
637             else {
638 0         0 push @ar, $savevalue;
639             }
640 0         0 push @ar, $this->_parse( {}, \@newcontent);
641 0         0 $config->{$block} = \@ar;
642             }
643             }
644             }
645             else {
646             # the first occurence of this particular block
647 62         302 $config->{$block} = $this->_parse($config->{$block}, \@newcontent);
648             }
649 62         186 $this->_backlast($block);
650             }
651 62         73 undef $blockname;
652 62         65 undef $block;
653 62         98 $this->{level} -= 1;
654 62         314 next;
655             }
656             }
657             else { # inside $block, just push onto new content stack
658 736         1625 push @newcontent, $_;
659             }
660             }
661 70 50       239 if ($block) {
662             # $block is still defined, which means, that it had
663             # no matching endblock!
664 0         0 croak "Block \"<$block>\" has no EndBlock statement (level: $this->{level}, chunk $chunk)!\n";
665             }
666 70         254 return $config;
667             }
668              
669              
670             sub _savelast {
671 62     62   101 my($this, $key) = @_;
672 62         118 $this->{upperkey} = $this->{lastkey};
673 62         122 $this->{lastkey} = $this->{prevkey};
674 62         121 $this->{prevkey} = $key;
675             }
676              
677             sub _backlast {
678 62     62   94 my($this, $key) = @_;
679 62         108 $this->{prevkey} = $this->{lastkey};
680 62         118 $this->{lastkey} = $this->{upperkey};
681             }
682              
683             sub _parse_value {
684             #
685             # parse the value if value parsing is turned on
686             # by either -AutoTrue and/or -FlagBits
687             # otherwise just return the given value unchanged
688             #
689 388     388   547 my($this, $option, $value) =@_;
690              
691             # avoid "Use of uninitialized value"
692 388 100       798 $value = '' unless defined $value;
693              
694 388 50       768 if ($this->{InterPolateVars}) {
695 0         0 $value = $this->_interpolate($option, $value);
696             }
697              
698             # make true/false values to 1 or 0 (-AutoTrue)
699 388 50       731 if ($this->{AutoTrue}) {
700 388 100       1703 if ($value =~ /$this->{AutoTrueFlags}->{true}/io) {
    100          
701 16         24 $value = 1;
702             }
703             elsif ($value =~ /$this->{AutoTrueFlags}->{false}/io) {
704 4         8 $value = 0;
705             }
706             }
707              
708             # assign predefined flags or undef for every flag | flag ... (-FlagBits)
709 388 50       834 if ($this->{FlagBits}) {
710 0 0       0 if (exists $this->{FlagBitsFlags}->{$option}) {
711 0         0 my %__flags = map { $_ => 1 } split /\s*\|\s*/, $value;
  0         0  
712 0         0 foreach my $flag (keys %{$this->{FlagBitsFlags}->{$option}}) {
  0         0  
713 0 0       0 if (exists $__flags{$flag}) {
714 0         0 $__flags{$flag} = $this->{FlagBitsFlags}->{$option}->{$flag};
715             }
716             else {
717 0         0 $__flags{$flag} = undef;
718             }
719             }
720 0         0 $value = \%__flags;
721             }
722             }
723 388         1535 return $value;
724             }
725              
726              
727              
728              
729              
730              
731             sub NoMultiOptions {
732             #
733             # turn AllowMultiOptions off, still exists for backward compatibility.
734             # Since we do parsing from within new(), we must
735             # call it again if one turns NoMultiOptions on!
736             #
737 0     0 0   croak "The NoMultiOptions() method is deprecated. Set 'AllowMultiOptions' to 'no' instead!";
738             }
739              
740              
741             sub save {
742             #
743             # this is the old version of save() whose API interface
744             # has been changed. I'm very sorry 'bout this.
745             #
746             # I'll try to figure out, if it has been called correctly
747             # and if yes, feed the call to Save(), otherwise croak.
748             #
749 0     0 0   my($this, $one, @two) = @_;
750              
751 0 0 0       if ( (@two && $one) && ( (scalar @two) % 2 == 0) ) {
      0        
752             # @two seems to be a hash
753 0           my %h = @two;
754 0           $this->save_file($one, \%h);
755             }
756             else {
757 0           croak "The save() method is deprecated. Use the new save_file() method instead!";
758             }
759             }
760              
761              
762             sub save_file {
763             #
764             # save the config back to disk
765             #
766 0     0 1   my($this, $file, $config) = @_;
767 0           my $fh = new FileHandle;
768 0           my $config_string;
769              
770 0 0         if (!$file) {
771 0           croak "Filename is required!";
772             }
773             else {
774 0 0         open $fh, ">$file" or croak "Could not open $file!($!)\n";
775              
776 0 0         if (!$config) {
777 0 0         if (exists $this->{config}) {
778 0           $config_string = $this->_store(0, %{$this->{config}});
  0            
779             }
780             else {
781 0           croak "No config hash supplied which could be saved to disk!\n";
782             }
783             }
784             else {
785 0           $config_string = $this->_store(0,%{$config});
  0            
786             }
787              
788 0 0         if ($config_string) {
789 0           print $fh $config_string;
790             }
791             else {
792             # empty config for whatever reason, I don't care
793 0           print $fh "";
794             }
795              
796 0           close $fh;
797             }
798             }
799              
800              
801              
802             sub save_string {
803             #
804             # return the saved config as a string
805             #
806 0     0 1   my($this, $config) = @_;
807              
808 0 0 0       if (!$config || ref($config) ne "HASH") {
809 0 0         if (exists $this->{config}) {
810 0           return $this->_store(0, %{$this->{config}});
  0            
811             }
812             else {
813 0           croak "No config hash supplied which could be saved to disk!\n";
814             }
815             }
816             else {
817 0           return $this->_store(0, %{$config});
  0            
818             }
819             }
820              
821              
822              
823             sub _store {
824             #
825             # internal sub for saving a block
826             #
827 0     0     my($this, $level, %config) = @_;
828 0           local $_;
829 0           my $indent = " " x $level;
830              
831 0           my $config_string;
832              
833 0           foreach my $entry (sort keys %config) {
834 0 0         if (ref($config{$entry}) eq "ARRAY") {
    0          
835 0           foreach my $line (@{$config{$entry}}) {
  0            
836 0 0         if (ref($line) eq "HASH") {
837 0           $config_string .= $this->_write_hash($level, $entry, $line);
838             }
839             else {
840 0           $config_string .= $this->_write_scalar($level, $entry, $line);
841             }
842             }
843             }
844             elsif (ref($config{$entry}) eq "HASH") {
845 0           $config_string .= $this->_write_hash($level, $entry, $config{$entry});
846             }
847             else {
848 0           $config_string .= $this->_write_scalar($level, $entry, $config{$entry});
849             }
850             }
851              
852 0           return $config_string;
853             }
854              
855              
856             sub _write_scalar {
857             #
858             # internal sub, which writes a scalar
859             # it returns it, in fact
860             #
861 0     0     my($this, $level, $entry, $line) = @_;
862              
863 0           my $indent = " " x $level;
864              
865 0           my $config_string;
866              
867 0 0         if ($line =~ /\n/) {
868             # it is a here doc
869 0           my $delimiter;
870 0           my $tmplimiter = "EOF";
871 0           while (!$delimiter) {
872             # create a unique here-doc identifier
873 0 0         if ($line =~ /$tmplimiter/s) {
874 0           $tmplimiter .= "%";
875             }
876             else {
877 0           $delimiter = $tmplimiter;
878             }
879             }
880 0           my @lines = split /\n/, $line;
881 0           $config_string .= $indent . $entry . $this->{StoreDelimiter} . "<<$delimiter\n";
882 0           foreach (@lines) {
883 0           $config_string .= $indent . $_ . "\n";
884             }
885 0           $config_string .= $indent . "$delimiter\n";
886             }
887             else {
888             # a simple stupid scalar entry
889 0           $line =~ s/#/\\#/g;
890 0           $config_string .= $indent . $entry . $this->{StoreDelimiter} . $line . "\n";
891             }
892              
893 0           return $config_string;
894             }
895              
896             sub _write_hash {
897             #
898             # internal sub, which writes a hash (block)
899             # it returns it, in fact
900             #
901 0     0     my($this, $level, $entry, $line) = @_;
902              
903 0           my $indent = " " x $level;
904 0           my $config_string;
905              
906 0           $config_string .= $indent . "<" . $entry . ">\n";
907 0           $config_string .= $this->_store($level + 1, %{$line});
  0            
908 0           $config_string .= $indent . "\n";
909              
910 0           return $config_string
911             }
912              
913              
914              
915             #
916             # Procedural interface
917             #
918             sub ParseConfig {
919             #
920             # @_ may contain everything which is allowed for new()
921             #
922 0     0 1   return (new Config::General(@_))->getall();
923             }
924              
925             sub SaveConfig {
926             #
927             # 2 parameters are required, filename and hash ref
928             #
929 0     0 1   my ($file, $hash) = @_;
930              
931 0 0 0       if (!$file || !$hash) {
932 0           croak "SaveConfig(): filename and hash argument required.";
933             }
934             else {
935 0 0         if (ref($hash) ne "HASH") {
936 0           croak "The second parameter must be a reference to a hash!";
937             }
938             else {
939 0           (new Config::General(-ConfigHash => $hash))->save_file($file);
940             }
941             }
942             }
943              
944             sub SaveConfigString {
945             #
946             # same as SaveConfig, but return the config,
947             # instead of saving it
948             #
949 0     0 1   my ($hash) = @_;
950              
951 0 0         if (!$hash) {
952 0           croak "SaveConfigString(): Hash argument required.";
953             }
954             else {
955 0 0         if (ref($hash) ne "HASH") {
956 0           croak "The parameter must be a reference to a hash!";
957             }
958             else {
959 0           return (new Config::General(-ConfigHash => $hash))->save_string();
960             }
961             }
962             }
963              
964              
965              
966             # keep this one
967             1;
968              
969              
970              
971              
972              
973             =head1 NAME
974              
975             Config::General - Generic Config Module
976              
977             =head1 SYNOPSIS
978              
979             #
980             # the OOP way
981             use Config::General;
982             $conf = new Config::General("rcfile");
983             my %config = $conf->getall;
984              
985             #
986             # the procedural way
987             use Config::General;
988             my %config = ParseConfig("rcfile");
989              
990             =head1 DESCRIPTION
991              
992             This module opens a config file and parses it's contents for you. The B method
993             requires one parameter which needs to be a filename. The method B returns a hash
994             which contains all options and it's associated values of your config file.
995              
996             The format of config files supported by B is inspired by the well known apache config
997             format, in fact, this module is 100% compatible to apache configs, but you can also just use simple
998             name/value pairs in your config files.
999              
1000             In addition to the capabilities of an apache config file it supports some enhancements such as here-documents,
1001             C-style comments or multiline options.
1002              
1003              
1004             =head1 METHODS
1005              
1006             =over
1007              
1008             =item new()
1009              
1010             Possible ways to call B:
1011              
1012             $conf = new Config::General("rcfile");
1013              
1014             $conf = new Config::General(\%somehash);
1015              
1016             $conf = new Config::General( %options ); # see below for description of possible options
1017              
1018              
1019             This method returns a B object (a hash blessed into "Config::General" namespace.
1020             All further methods must be used from that returned object. see below.
1021              
1022             You can use the new style with hash parameters or the old style which is of course
1023             still supported. Possible parameters to B are:
1024              
1025             * a filename of a configfile, which will be opened and parsed by the parser
1026              
1027             or
1028              
1029             * a hash reference, which will be used as the config.
1030              
1031             An alternative way to call B is supplying an option- hash with one or more of
1032             the following keys set:
1033              
1034             =over
1035              
1036             =item B<-ConfigFile>
1037              
1038             A filename or a filehandle, i.e.:
1039              
1040             -ConfigFile => "rcfile" or -ConfigFile => \$FileHandle
1041              
1042              
1043              
1044             =item B<-ConfigHash>
1045              
1046             A hash reference, which will be used as the config, i.e.:
1047              
1048             -ConfigHash => \%somehash
1049              
1050              
1051              
1052             =item B<-String>
1053              
1054             A string which contains a whole config, or an arrayref
1055             containing the whole config line by line.
1056             The parser will parse the contents of the string instead
1057             of a file. i.e:
1058              
1059             -String => $complete_config
1060              
1061             it is also possible to feed an array reference to -String:
1062              
1063             -String => \@config_lines
1064              
1065              
1066              
1067             =item B<-AllowMultiOptions>
1068              
1069             If the value is "no", then multiple identical options are disallowed.
1070             The default is "yes".
1071             i.e.:
1072              
1073             -AllowMultiOptions => "no"
1074              
1075             see B for details.
1076              
1077             =item B<-LowerCaseNames>
1078              
1079             If set to a true value, then all options found in the config will be converted
1080             to lowercase. This allows you to provide case-in-sensitive configs. The
1081             values of the options will B lowercased.
1082              
1083              
1084              
1085             =item B<-UseApacheInclude>
1086              
1087             If set to a true value, the parser will consider "include ..." as valid include
1088             statement (just like the well known apache include statement).
1089              
1090              
1091              
1092             =item B<-IncludeRelative>
1093              
1094             If set to a true value, included files with a relative path (i.e. "cfg/blah.conf")
1095             will be opened from within the location of the configfile instead from within the
1096             location of the script($0). This works only if the configfile has a absolute pathname
1097             (i.e. "/etc/main.conf").
1098              
1099              
1100              
1101             =item B<-MergeDuplicateBlocks>
1102              
1103             If set to a true value, then duplicate blocks, that means blocks and named blocks,
1104             will be merged into a single one (see below for more details on this).
1105             The default behavior of Config::General is to create an array if some junk in a
1106             config appears more than once.
1107              
1108              
1109             =item B<-MergeDuplicateOptions>
1110              
1111             If set to a true value, then duplicate options will be merged. That means, if the
1112             same option occurs more than once, the last one will be used in the resulting
1113             config hash.
1114              
1115             Setting this option implies B<-AllowMultiOptions == false> unless you set
1116             B<-AllowMultiOptions> explicit to 'true'. In this case duplicate blocks are
1117             allowed and put into an array but dupclicate options will be merged.
1118              
1119              
1120             =item B<-AutoTrue>
1121              
1122             If set to a true value, then options in your config file, whose values are set to
1123             true or false values, will be normalised to 1 or 0 respectively.
1124              
1125             The following values will be considered as B:
1126              
1127             yes, on, 1, true
1128              
1129             The following values will be considered as B:
1130              
1131             no, off, 0, false
1132              
1133             This effect is case-insensitive, i.e. both "Yes" or "oN" will result in 1.
1134              
1135              
1136             =item B<-FlagBits>
1137              
1138             This option takes one required parameter, which must be a hash reference.
1139              
1140             The supplied hash reference needs to define variables for which you
1141             want to preset values. Each variable you have defined in this hash-ref
1142             and which occurs in your config file, will cause this variable being
1143             set to the preset values to which the value in the config file refers to.
1144              
1145             Multiple flags can be used, separated by the pipe character |.
1146              
1147             Well, an example will clarify things:
1148              
1149             my $conf = new Config::General(
1150             -ConfigFile => "rcfile",
1151             -FlagBits => {
1152             Mode => {
1153             CLEAR => 1,
1154             STRONG => 1,
1155             UNSECURE => "32bit" }
1156             }
1157             );
1158              
1159             In this example we are defining a variable named I<"Mode"> which
1160             may contain one or more of "CLEAR", "STRONG" and "UNSECURE" as value.
1161              
1162             The appropriate config entry may look like this:
1163              
1164             # rcfile
1165             Mode = CLEAR | UNSECURE
1166              
1167             The parser will create a hash which will be the value of the key "Mode". This
1168             hash will contain B flags which you have pre-defined, but only those
1169             which were set in the config will contain the pre-defined value, the other
1170             ones will be undefined.
1171              
1172             The resulting config structure would look like this after parsing:
1173              
1174             %config = (
1175             Mode => {
1176             CLEAR => 1,
1177             UNSECURE => "32bit",
1178             STRONG => undef,
1179             }
1180             );
1181              
1182             This method allows the user (or, the "maintainer" of the configfile for your
1183             application) to set multiple pre-defined values for one option.
1184              
1185             Please beware, that all occurencies of those variables will be handled this
1186             way, there is no way to distinguish between variables in different scopes.
1187             That means, if "Mode" would also occur inside a named block, it would
1188             also parsed this way.
1189              
1190             Values which are not defined in the hash-ref supplied to the parameter B<-FlagBits>
1191             and used in the corresponding variable in the config will be ignored.
1192              
1193             Example:
1194              
1195             # rcfile
1196             Mode = BLAH | CLEAR
1197              
1198             would result in this hash structure:
1199              
1200             %config = (
1201             Mode => {
1202             CLEAR => 1,
1203             UNSECURE => undef,
1204             STRONG => undef,
1205             }
1206             );
1207              
1208             "BLAH" will be ignored silently.
1209              
1210              
1211             =item B<-DefaultConfig>
1212              
1213             This can be a hash reference or a simple scalar (string) of a config. This
1214             causes the module to preset the resulting config hash with the given values,
1215             which allows you to set default values for particular config options directly.
1216              
1217             This hash will be used as the 'backing hash' instead of a standard perl hash,
1218             which allows you to affect the way, variable storing will be done. You could, for
1219             example supply a tied hash, say Tie::DxHash, which preserves ordering of the
1220             keys in the config (which a standard perl hash won't do). Or, you could supply
1221             a hash tied to a DBM file to save the parsed variables to disk.
1222              
1223             There are many more things to do in tie-land, see L to get some interesting
1224             ideas.
1225              
1226             =item B<-InterPolateVars>
1227              
1228             If set to a true value, variable interpolation will be done on your config
1229             input. See L for more informations.
1230              
1231             =item B<-ExtendedAccess>
1232              
1233             If set to a true value, you can use object oriented (extended) methods to
1234             access the parsed config. See L for more informations.
1235              
1236             =item B<-StrictObjects>
1237              
1238             By default this is turned on, which causes Config::General to croak with an
1239             error if you try to access a non-existent key using the oop-way (B<-ExtendedAcess>
1240             enabled). If you turn B<-StrictObjects> off (by setting to 0 or "no") it will
1241             just return an empty object/hash/scalar. This is valid for OOP-access 8via AUTOLOAD
1242             and for the methods obj(), hash() and value().
1243              
1244              
1245             =item B<-StrictVars>
1246              
1247             By default this is turned on, which causes Config::General to croak with an
1248             error if an undefined variable with B turned on occurs
1249             in a config. Set to I (i.e. 0) to avoid such error messages.
1250              
1251             =item B<-SplitPolicy>
1252              
1253             You can influence the way how Config::General decides which part of a line
1254             in a config file is the key and which one is the value. By default it tries
1255             it's best to guess. That means you can mix equalsign assignments and whitespace
1256             assignments.
1257              
1258             However, somtimes you may wish to make it more strictly for some reason. In
1259             this case you can set B<-SplitPolicy>. The possible values are: 'guess' which
1260             is the default, 'whitespace' which causes the module to split by whitespace,
1261             'equalsign' which causes it to split strictly by equal sign, or 'custom'. In the
1262             latter case you must also set B<-SplitDelimiter> to some regular expression
1263             of your choice. For example:
1264              
1265             -SplitDelimiter => '\s*:\s*'
1266              
1267             will cause the module to split by colon while whitespaces which surrounds
1268             the delimiter will be removed.
1269              
1270             Please note that the delimiter used when saving a config (save_file() or save_string())
1271             will be choosen accordingto the current B<-SplitPolicy>. If -SplitPolicy is
1272             set to 'guess' or 'whitespace', 3 whitespaces will be used to delimit saved
1273             options. If 'custom' is set, then you need to set B<-StoreDelimiter>.
1274              
1275             =item B<-SplitDelimiter>
1276              
1277             Set this to any arbitrary regular expression which will be used for option/value
1278             splitting. B<-SplitPolicy> must be set to 'custom' to make this work.
1279              
1280             =item B<-StoreDelimiter>
1281              
1282             You can use this parameter to specify a custom delimiter to use when saving
1283             configs to a file or string. You only need to set it if you want to store
1284             the config back to disk and if you have B<-SplitPolicy> set to 'custom'.
1285              
1286             Be very carefull with this parameter.
1287              
1288              
1289             =item B<-CComments>
1290              
1291             Config::General is able to notice c-style comments (see section COMMENTS).
1292             But for some reason you might no need this. In this case you can turn
1293             this feature off by setting B<-CComments> to a false value('no', 0, 'off').
1294              
1295             By default B<-CComments> is turned on.
1296              
1297             =back
1298              
1299              
1300              
1301              
1302             =item getall()
1303              
1304             Returns a hash structure which represents the whole config.
1305              
1306              
1307             =item save_file()
1308              
1309             Writes the config hash back to the harddisk. This method takes one or two
1310             parameters. The first parameter must be the filename where the config
1311             should be written to. The second parameter is optional, it must be a
1312             reference to a hash structure, if you set it. If you do not supply this second parameter
1313             then the internal config hash, which has already been parsed, will be
1314             used.
1315              
1316             Please note, that any occurence of comments will be ignored by getall()
1317             and thus be lost after you call this method.
1318              
1319             You need also to know that named blocks will be converted to nested blocks
1320             (which is the same from the perl point of view). An example:
1321              
1322            
1323             id 13
1324            
1325              
1326             will become the following after saving:
1327              
1328            
1329            
1330             id 13
1331            
1332            
1333              
1334             Example:
1335              
1336             $conf_obj->save_file("newrcfile", \%config);
1337              
1338             or, if the config has already been parsed, or if it didn't change:
1339              
1340             $conf_obj->save_file("newrcfile");
1341              
1342              
1343             =item save_string()
1344              
1345             This method is equivalent to the previous save_file(), but it does not
1346             store the generated config to a file. Instead it returns it as a string,
1347             which you can save yourself afterwards.
1348              
1349             It takes one optional parameter, which must be a reference to a hash structure.
1350             If you omit this parameter, the internal config hash, which has already been parsed,
1351             will be used.
1352              
1353             Example:
1354              
1355             my $content = $conf_obj->save_string(\%config);
1356              
1357             or:
1358              
1359             my $content = $conf_obj->save_string();
1360              
1361              
1362             =back
1363              
1364              
1365             =head1 CONFIG FILE FORMAT
1366              
1367             Lines begining with B<#> and empty lines will be ignored. (see section COMMENTS!)
1368             Spaces at the begining and the end of a line will also be ignored as well as tabulators.
1369             If you need spaces at the end or the beginning of a value you can use
1370             apostrophs B<">.
1371             An optionline starts with it's name followed by a value. An equalsign is optional.
1372             Some possible examples:
1373              
1374             user max
1375             user = max
1376             user max
1377              
1378             If there are more than one statements with the same name, it will create an array
1379             instead of a scalar. See the example below.
1380              
1381             The method B returns a hash of all values.
1382              
1383              
1384             =head1 BLOCKS
1385              
1386             You can define a B of options. A B looks much like a block
1387             in the wellknown apache config format. It starts with EBE and ends
1388             with E/BE. An example:
1389              
1390            
1391             host = muli
1392             user = moare
1393             dbname = modb
1394             dbpass = D4r_9Iu
1395            
1396              
1397             Blocks can also be nested. Here is a more complicated example:
1398              
1399             user = hans
1400             server = mc200
1401             db = maxis
1402             passwd = D3rf$
1403            
1404             user = tom
1405             db = unknown
1406             host = mila
1407            
1408             index int(100000)
1409             name char(100)
1410             prename char(100)
1411             city char(100)
1412             status int(10)
1413             allowed moses
1414             allowed ingram
1415             allowed joice
1416            
1417            
1418              
1419             The hash which the method B returns look like that:
1420              
1421             print Data::Dumper(\%hash);
1422             $VAR1 = {
1423             'passwd' => 'D3rf$',
1424             'jonas' => {
1425             'tablestructure' => {
1426             'prename' => 'char(100)',
1427             'index' => 'int(100000)',
1428             'city' => 'char(100)',
1429             'name' => 'char(100)',
1430             'status' => 'int(10)',
1431             'allowed' => [
1432             'moses',
1433             'ingram',
1434             'joice',
1435             ]
1436             },
1437             'host' => 'mila',
1438             'db' => 'unknown',
1439             'user' => 'tom'
1440             },
1441             'db' => 'maxis',
1442             'server' => 'mc200',
1443             'user' => 'hans'
1444             };
1445              
1446             If you have turned on B<-LowerCaseNames> (see new()) then blocks as in the
1447             following example:
1448              
1449            
1450            
1451             Owner root
1452            
1453            
1454              
1455             would produce the following hash structure:
1456              
1457             $VAR1 = {
1458             'dir' => {
1459             'attributes' => {
1460             'owner => "root",
1461             }
1462             }
1463             };
1464              
1465             As you can see, the keys inside the config hash are normalized.
1466              
1467             Please note, that the above config block would result in a
1468             valid hash structure, even if B<-LowerCaseNames> is not set!
1469             This is because I does not
1470             use the blocknames to check if a block ends, instead it uses an internal
1471             state counter, which indicates a block end.
1472              
1473             If the module cannot find an end-block statement, then this block will be ignored.
1474              
1475              
1476              
1477             =head1 NAMED BLOCKS
1478              
1479             If you need multiple blocks of the same name, then you have to name every block.
1480             This works much like apache config. If the module finds a named block, it will
1481             create a hashref with the left part of the named block as the key containing
1482             one or more hashrefs with the right part of the block as key containing everything
1483             inside the block(which may again be nested!). As examples says more than words:
1484              
1485             # given the following sample
1486            
1487             Limit Deny
1488             Options ExecCgi Index
1489            
1490            
1491             Limit DenyAll
1492             Options None
1493            
1494              
1495             # you will get:
1496             $VAR1 = {
1497             'Directory' => {
1498             '/usr/frik' => {
1499             'Options' => 'None',
1500             'Limit' => 'DenyAll'
1501             },
1502             '/usr/frisco' => {
1503             'Options' => 'ExecCgi Index',
1504             'Limit' => 'Deny'
1505             }
1506             }
1507             };
1508              
1509             You cannot have more than one named block with the same name because it will
1510             be stored in a hashref and therefore be overwritten if a block occurs once more.
1511              
1512              
1513              
1514             =head1 IDENTICAL OPTIONS
1515              
1516             You may have more than one line of the same option with different values.
1517              
1518             Example:
1519             log log1
1520             log log2
1521             log log2
1522              
1523             You will get a scalar if the option occured only once or an array if it occured
1524             more than once. If you expect multiple identical options, then you may need to
1525             check if an option occured more than once:
1526              
1527             $allowed = $hash{jonas}->{tablestructure}->{allowed};
1528             if(ref($allowed) eq "ARRAY") {
1529             @ALLOWED = @{$allowed};
1530             else {
1531             @ALLOWED = ($allowed);
1532             }
1533              
1534             The same applies to blocks and named blocks too (they are described in more detail
1535             below). For example, if you have the following config:
1536              
1537            
1538             user max
1539            
1540            
1541             user hannes
1542            
1543              
1544             then you would end up with a data structure like this:
1545              
1546             $VAR1 = {
1547             'dir' => {
1548             'blah' => [
1549             {
1550             'user' => 'max'
1551             },
1552             {
1553             'user' => 'hannes'
1554             }
1555             ]
1556             }
1557             };
1558              
1559             As you can see, the two identical blocks are stored in a hash which contains
1560             an array(-reference) of hashes.
1561              
1562             Under some rare conditions you might not want this behavior with blocks (and
1563             named blocks too). If you want to get one single hash with the contents of
1564             both identical blocks, then you need to turn the B parameter B<-MergeDuplicateBlocks>
1565             on (see above). The parsed structure of the example above would then look like
1566             this:
1567              
1568             $VAR1 = {
1569             'dir' => {
1570             'blah' => [
1571             'user' => 'max',
1572             'user' => 'hannes'
1573             ]
1574             }
1575             };
1576              
1577             As you can see, there is only one hash "dir->{blah}" containing multiple
1578             "user" entries. As you can also see, turning on B<-MergeDuplicateBlocks>
1579             does not affect scalar options (i.e. "option = value"). In fact you can
1580             tune merging of duplicate blocks and options independent from each other.
1581              
1582             If you don't want to allow more than one identical options, you may turn it off
1583             by setting the flag I in the B method to "no".
1584             If turned off, Config::General will complain about multiple occuring options
1585             with identical names!
1586              
1587              
1588              
1589             =head1 LONG LINES
1590              
1591             If you have a config value, which is too long and would take more than one line,
1592             you can break it into multiple lines by using the backslash character at the end
1593             of the line. The Config::General module will concatenate those lines to one single-value.
1594              
1595             Example:
1596              
1597             command = cat /var/log/secure/tripwire | \
1598             mail C<-s> "report from tripwire" \
1599             honey@myotherhost.nl
1600              
1601             command will become:
1602             "cat /var/log/secure/tripwire | mail C<-s> 'report from twire' honey@myotherhost.nl"
1603              
1604              
1605             =head1 HERE DOCUMENTS
1606              
1607             You can also define a config value as a so called "here-document". You must tell
1608             the module an identifier which identicates the end of a here document. An
1609             identifier must follow a "<<".
1610              
1611             Example:
1612              
1613             message <
1614             we want to
1615             remove the
1616             homedir of
1617             root.
1618             EOF
1619              
1620             Everything between the two "EOF" strings will be in the option I.
1621              
1622             There is a special feature which allows you to use indentation with here documents.
1623             You can have any amount of whitespaces or tabulators in front of the end
1624             identifier. If the module finds spaces or tabs then it will remove exactly those
1625             amount of spaces from every line inside the here-document.
1626              
1627             Example:
1628              
1629             message <
1630             we want to
1631             remove the
1632             homedir of
1633             root.
1634             EOF
1635              
1636             After parsing, message will become:
1637              
1638             we want to
1639             remove the
1640             homedir of
1641             root.
1642              
1643             because there were the string " " in front of EOF, which were cutted from every
1644             line inside the here-document.
1645              
1646              
1647              
1648             =head1 INCLUDES
1649              
1650             You can include an external file at any posision in your config file using the following statement
1651             in your config file:
1652              
1653             <>
1654              
1655             If you turned on B<-UseApacheInclude> (see B), then you can also use the following
1656             statement to include an external file:
1657              
1658             include externalconfig.rc
1659              
1660             This file will be inserted at the position where it was found as if the contents of this file
1661             were directly at this position.
1662              
1663             You can also recurively include files, so an included file may include another one and so on.
1664             Beware that you do not recursively load the same file, you will end with an errormessage like
1665             "too many open files in system!".
1666              
1667             By default included files with a relative pathname will be opened from within the current
1668             working directory. Under some circumstances it maybe possible to
1669             open included files from the directory, where the configfile resides. You need to turn on
1670             the option B<-IncludeRelative> (see B) if you want that. An example:
1671              
1672             my $conf = Config::General(
1673             -ConfigFile => "/etc/crypt.d/server.cfg"
1674             -IncludeRelative => 1
1675             );
1676              
1677             /etc/crypt.d/server.cfg:
1678             <>
1679              
1680             In this example Config::General will try to include I from I:
1681              
1682             /etc/crypt.d/acl.cfg
1683              
1684             The default behavior (if B<-IncludeRelative> is B set!) will be to open just I,
1685             whereever it is, i.e. if you did a chdir("/usr/local/etc"), then Config::General will include:
1686              
1687             /usr/local/etc/acl.cfg
1688              
1689             Include statements can be case insensitive (added in version 1.25).
1690              
1691             Include statements will be ignored within C-Comments and here-documents.
1692              
1693              
1694              
1695             =head1 COMMENTS
1696              
1697             A comment starts with the number sign B<#>, there can be any number of spaces and/or
1698             tabstops in front of the #.
1699              
1700             A comment can also occur after a config statement. Example:
1701              
1702             username = max # this is the comment
1703              
1704             If you want to comment out a large block you can use C-style comments. A B signals
1705             the begin of a comment block and the B<*/> signals the end of the comment block.
1706             Example:
1707              
1708             user = max # valid option
1709             db = tothemax
1710             /*
1711             user = andors
1712             db = toand
1713             */
1714              
1715             In this example the second options of user and db will be ignored. Please beware of the fact,
1716             if the Module finds a B string which is the start of a comment block, but no matching
1717             end block, it will ignore the whole rest of the config file!
1718              
1719             B If you require the B<#> character (number sign) to remain in the option value, then
1720             you can use a backlsash in front of it, to escape it. Example:
1721              
1722             bgcolor = \#ffffcc
1723              
1724             In this example the value of $config{bgcolor} will be "#ffffcc", Config::General will not treat
1725             the number sign as the begin of a comment because of the leading backslash.
1726              
1727             Inside here-documents escaping of number signs is NOT required!
1728              
1729              
1730             =head1 OBJECT ORIENTED INTERFACE
1731              
1732             There is a way to access a parsed config the OO-way.
1733             Use the module B, which is
1734             supplied with the Config::General distribution.
1735              
1736             =head1 VARIABLE INTERPOLATION
1737              
1738             You can use variables inside your configfiles if you like. To do
1739             that you have to use the module B,
1740             which is supplied with the Config::General distribution.
1741              
1742              
1743             =head1 EXPORTED FUNCTIONS
1744              
1745             Config::General exports some functions too, which makes it somewhat
1746             easier to use it, if you like this.
1747              
1748             =over
1749              
1750             =item B
1751              
1752             This function takes exactly all those parameters, which are
1753             allowed to the B method of the standard interface.
1754              
1755             Example:
1756              
1757             use Config::General;
1758             my %config = ParseConfig(-ConfigFile => "rcfile", -AutoTrue => 1);
1759              
1760              
1761             =item B
1762              
1763             This function requires two arguments, a filename and a reference
1764             to a hash structure.
1765              
1766             Example:
1767              
1768             use Config::General;
1769             ..
1770             SaveConfig("rcfile", \%some_hash);
1771              
1772              
1773             =item B
1774              
1775             This function requires a reference to a config hash as parameter.
1776             It generates a configuration based on this hash as the object-interface
1777             method B does.
1778              
1779             Example:
1780              
1781             use Config::General;
1782             my %config = ParseConfig(-ConfigFile => "rcfile");
1783             .. # change %config something
1784             my $content = SaveConfigString(\%config);
1785              
1786              
1787             =back
1788              
1789              
1790             =head1 SEE ALSO
1791              
1792             I recommend you to read the following documentations, which are supplied with perl:
1793              
1794             perlreftut Perl references short introduction
1795             perlref Perl references, the rest of the story
1796             perldsc Perl data structures intro
1797             perllol Perl data structures: arrays of arrays
1798              
1799             Config::General::Extended Object oriented interface to parsed configs
1800             Config::General::Interpolated Allows to use variables inside config files
1801              
1802             =head1 COPYRIGHT
1803              
1804             Copyright (c) 2000-2003 Thomas Linden
1805              
1806             This library is free software; you can redistribute it and/or
1807             modify it under the same terms as Perl itself.
1808              
1809              
1810             =head1 BUGS
1811              
1812             none known yet.
1813              
1814             =head1 AUTHOR
1815              
1816             Thomas Linden
1817              
1818              
1819             =head1 VERSION
1820              
1821             2.18
1822              
1823             =cut
1824