2 # Config::General.pm - Generic Config Module
4 # Purpose: Provide a convenient way for loading
5 # config values from a given file and
6 # return it as hash structure
8 # Copyright (c) 2000-2009 Thomas Linden <tlinden |AT| cpan.org>.
9 # All Rights Reserved. Std. disclaimer applies.
10 # Artificial License, same as perl itself. Have fun.
13 package Config::General;
17 use English '-no_match_vars';
21 use File::Spec::Functions qw(splitpath file_name_is_absolute catfile catpath);
22 use File::Glob qw/:glob/;
25 # on debian with perl > 5.8.4 croak() doesn't work anymore without this.
26 # There is some require statement which dies 'cause it can't find Carp::Heavy,
27 # I really don't understand, what the hell they made, but the debian perl
28 # installation is definetly bullshit, damn!
35 $Config::General::VERSION = 2.44;
37 use vars qw(@ISA @EXPORT_OK);
38 use base qw(Exporter);
39 @EXPORT_OK = qw(ParseConfig SaveConfig SaveConfigString);
43 # create new Config::General object
45 my($this, @param ) = @_;
46 my $class = ref($this) || $this;
48 # define default options
50 # sha256 of current date
51 # hopefully this lowers the probability that
52 # this matches any configuration key or value out there
54 EOFseparator => 'ad7d7b87f5b81d2a0d5cb75294afeb91aa4801b1f8e8532dc1b633c0e1d47037',
55 SlashIsDirectory => 0,
56 AllowMultiOptions => 1,
57 MergeDuplicateOptions => 0,
58 MergeDuplicateBlocks => 0,
60 ApacheCompatible => 0,
61 UseApacheInclude => 0,
63 IncludeDirectories => 0,
69 true => '^(on|yes|true|1)$',
70 false => '^(off|no|false|0)$',
78 SplitPolicy => 'guess', # also possible: whitespace, equalsign and custom
79 SplitDelimiter => 0, # must be set by the user if SplitPolicy is 'custom'
80 StoreDelimiter => 0, # will be set by me unless user uses 'custom' policy
81 CComments => 1, # by default turned on
82 BackslashEscape => 0, # by default turned off, allows escaping anything using the backslash
83 StrictObjects => 1, # be strict on non-existent keys in OOP mode
84 StrictVars => 1, # be strict on undefined variables in Interpolate mode
85 Tie => q(), # could be set to a perl module for tie'ing new hashes
86 parsed => 0, # internal state stuff for variable interpolation
87 files => {}, # which files we have read, if any
92 # create the class instance
96 # use of the new hash interface!
97 $self->_prepare(@param);
99 elsif ($#param == 0) {
100 # use of the old style
101 $self->{ConfigFile} = $param[0];
102 if (ref($self->{ConfigFile}) eq 'HASH') {
103 $self->{ConfigHash} = delete $self->{ConfigFile};
107 # this happens if $#param == -1,1 thus no param was given to new!
108 $self->{config} = $self->_hashref();
112 # find split policy to use for option/value separation
113 $self->_splitpolicy();
115 # bless into variable interpolation module if neccessary
119 if (!$self->{parsed}) {
123 if ($self->{InterPolateVars}) {
124 $self->{config} = $self->_clean_stack($self->{config});
127 # bless into OOP namespace if required
137 # call _read() and _parse() on the given config
140 if ($self->{DefaultConfig} && $self->{InterPolateVars}) {
141 $self->{DefaultConfig} = $self->_interpolate_hash($self->{DefaultConfig}); # FIXME: _hashref() ?
143 if (exists $self->{StringContent}) {
144 # consider the supplied string as config file
145 $self->_read($self->{StringContent}, 'SCALAR');
146 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
148 elsif (exists $self->{ConfigHash}) {
149 if (ref($self->{ConfigHash}) eq 'HASH') {
150 # initialize with given hash
151 $self->{config} = $self->{ConfigHash};
155 croak "Config::General: Parameter -ConfigHash must be a hash reference!\n";
158 elsif (ref($self->{ConfigFile}) eq 'GLOB' || ref($self->{ConfigFile}) eq 'FileHandle') {
159 # use the file the glob points to
160 $self->_read($self->{ConfigFile});
161 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
164 if ($self->{ConfigFile}) {
165 # open the file and read the contents in
166 $self->{configfile} = $self->{ConfigFile};
167 if ( file_name_is_absolute($self->{ConfigFile}) ) {
168 # look if is is an absolute path and save the basename if it is absolute
169 my ($volume, $path, undef) = splitpath($self->{ConfigFile});
170 $path =~ s#/$##; # remove eventually existing trailing slash
171 if (! $self->{ConfigPath}) {
172 $self->{ConfigPath} = [];
174 unshift @{$self->{ConfigPath}}, catpath($volume, $path, q());
176 $self->_open($self->{configfile});
177 # now, we parse immdediately, getall simply returns the whole hash
178 $self->{config} = $self->_hashref();
179 $self->{config} = $self->_parse($self->{DefaultConfig}, $self->{content});
182 # hm, no valid config file given, so try it as an empty object
183 $self->{config} = $self->_hashref();
192 # bless into ::Extended if neccessary
194 if ($self->{ExtendedAccess}) {
195 # we are blessing here again, to get into the ::Extended namespace
196 # for inheriting the methods available overthere, which we doesn't have.
197 bless $self, 'Config::General::Extended';
199 require Config::General::Extended;
202 croak "Config::General: " . $EVAL_ERROR;
210 # bless into ::Interpolated if neccessary
212 if ($self->{InterPolateVars} || $self->{InterPolateEnv}) {
213 # InterPolateEnv implies InterPolateVars
214 $self->{InterPolateVars} = 1;
216 # we are blessing here again, to get into the ::InterPolated namespace
217 # for inheriting the methods available overthere, which we doesn't have here.
218 bless $self, 'Config::General::Interpolated';
220 require Config::General::Interpolated;
223 croak "Config::General: " . $EVAL_ERROR;
225 # pre-compile the variable regexp
226 $self->{regex} = $self->_set_regex();
234 # find out what split policy to use
236 if ($self->{SplitPolicy} ne 'guess') {
237 if ($self->{SplitPolicy} eq 'whitespace') {
238 $self->{SplitDelimiter} = '\s+';
239 if (!$self->{StoreDelimiter}) {
240 $self->{StoreDelimiter} = q( );
243 elsif ($self->{SplitPolicy} eq 'equalsign') {
244 $self->{SplitDelimiter} = '\s*=\s*';
245 if (!$self->{StoreDelimiter}) {
246 $self->{StoreDelimiter} = ' = ';
249 elsif ($self->{SplitPolicy} eq 'custom') {
250 if (! $self->{SplitDelimiter} ) {
251 croak "Config::General: SplitPolicy set to 'custom' but no SplitDelimiter set.\n";
255 croak "Config::General: Unsupported SplitPolicy: $self->{SplitPolicy}.\n";
259 if (!$self->{StoreDelimiter}) {
260 $self->{StoreDelimiter} = q( );
267 # prepare the class parameters, mangle them, if there
268 # are options to reset or to override, do it here.
269 my ($self, %conf) = @_;
271 # save the parameter list for ::Extended's new() calls
272 $self->{Params} = \%conf;
274 # be backwards compatible
275 if (exists $conf{-file}) {
276 $self->{ConfigFile} = delete $conf{-file};
278 if (exists $conf{-hash}) {
279 $self->{ConfigHash} = delete $conf{-hash};
282 # store input, file, handle, or array
283 if (exists $conf{-ConfigFile}) {
284 $self->{ConfigFile} = delete $conf{-ConfigFile};
286 if (exists $conf{-ConfigHash}) {
287 $self->{ConfigHash} = delete $conf{-ConfigHash};
290 # store search path for relative configs, if any
291 if (exists $conf{-ConfigPath}) {
292 my $configpath = delete $conf{-ConfigPath};
293 $self->{ConfigPath} = ref $configpath eq 'ARRAY' ? $configpath : [$configpath];
296 # handle options which contains values we need (strings, hashrefs or the like)
297 if (exists $conf{-String} ) {
298 #if (ref(\$conf{-String}) eq 'SCALAR') {
299 if (not ref $conf{-String}) {
300 if ( $conf{-String}) {
301 $self->{StringContent} = $conf{-String};
303 delete $conf{-String};
305 # re-implement arrayref support, removed after 2.22 as _read were
308 elsif(ref($conf{-String}) eq 'ARRAY') {
309 $self->{StringContent} = join "\n", @{$conf{-String}};
312 croak "Config::General: Parameter -String must be a SCALAR or ARRAYREF!\n";
314 delete $conf{-String};
316 if (exists $conf{-Tie}) {
318 $self->{Tie} = delete $conf{-Tie};
319 $self->{DefaultConfig} = $self->_hashref();
323 if (exists $conf{-FlagBits}) {
324 if ($conf{-FlagBits} && ref($conf{-FlagBits}) eq 'HASH') {
325 $self->{FlagBits} = 1;
326 $self->{FlagBitsFlags} = $conf{-FlagBits};
328 delete $conf{-FlagBits};
331 if (exists $conf{-DefaultConfig}) {
332 if ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq 'HASH') {
333 $self->{DefaultConfig} = $conf{-DefaultConfig};
335 elsif ($conf{-DefaultConfig} && ref($conf{-DefaultConfig}) eq q()) {
336 $self->_read($conf{-DefaultConfig}, 'SCALAR');
337 $self->{DefaultConfig} = $self->_parse($self->_hashref(), $self->{content});
338 $self->{content} = ();
340 delete $conf{-DefaultConfig};
343 # handle options which may either be true or false
344 # allowing "human" logic about what is true and what is not
345 foreach my $entry (keys %conf) {
348 if (! exists $self->{$key}) {
349 croak "Config::General: Unknown parameter: $entry => \"$conf{$entry}\" (key: <$key>)\n";
351 if ($conf{$entry} =~ /$self->{AutoTrueFlags}->{true}/io) {
354 elsif ($conf{$entry} =~ /$self->{AutoTrueFlags}->{false}/io) {
359 $self->{$key} = $conf{$entry};
363 if ($self->{MergeDuplicateOptions}) {
364 # override if not set by user
365 if (! exists $conf{-AllowMultiOptions}) {
366 $self->{AllowMultiOptions} = 0;
370 if ($self->{ApacheCompatible}) {
371 # turn on all apache compatibility options which has
372 # been incorporated during the years...
373 $self->{UseApacheInclude} = 1;
374 $self->{IncludeRelative} = 1;
375 $self->{IncludeDirectories} = 1;
376 $self->{IncludeGlob} = 1;
377 $self->{SlashIsDirectory} = 1;
378 $self->{SplitPolicy} = 'whitespace';
379 $self->{CComments} = 0;
380 $self->{BackslashEscape} = 1;
386 # just return the whole config hash
389 return (exists $this->{config} ? %{$this->{config}} : () );
395 # return a list of files opened so far
398 return (exists $this->{files} ? keys %{$this->{files}} : () );
404 # open the config file, or expand a directory or glob
406 my($this, $basefile, $basepath) = @_;
407 my($fh, $configfile);
410 # if this doesn't work we can still try later the global config path to use
411 $configfile = catfile($basepath, $basefile);
414 $configfile = $basefile;
417 if ($this->{IncludeGlob} and $configfile =~ /[*?\[\{\\]/) {
418 # Something like: *.conf (or maybe dir/*.conf) was included; expand it and
419 # pass each expansion through this method again.
420 my @include = grep { -f $_ } bsd_glob($configfile, GLOB_BRACE | GLOB_QUOTE);
422 # applied patch by AlexK fixing rt.cpan.org#41030
423 if ( !@include && defined $this->{ConfigPath} ) {
424 foreach my $dir (@{$this->{ConfigPath}}) {
425 my ($volume, $path, undef) = splitpath($basefile);
426 if ( -d catfile( $dir, $path ) ) {
427 push @include, grep { -f $_ } bsd_glob(catfile($dir, $basefile), GLOB_BRACE | GLOB_QUOTE);
434 $configfile = $include[0];
437 # Multiple results or no expansion results (which is fine,
438 # include foo/* shouldn't fail if there isn't anything matching)
439 local $this->{IncludeGlob};
447 if (!-e $configfile) {
449 if (defined $this->{ConfigPath}) {
450 # try to find the file within ConfigPath
451 foreach my $dir (@{$this->{ConfigPath}}) {
452 if( -e catfile($dir, $basefile) ) {
453 $configfile = catfile($dir, $basefile);
460 my $path_message = defined $this->{ConfigPath} ? q( within ConfigPath: ) . join(q(.), @{$this->{ConfigPath}}) : q();
461 croak qq{Config::General The file "$basefile" does not exist$path_message!};
467 carp(q(\$RS (INPUT_RECORD_SEPARATOR) is undefined. Guessing you want a line feed character));
471 if (-d $configfile and $this->{IncludeDirectories}) {
472 # A directory was included; include all the files inside that directory in ASCII order
474 opendir INCLUDEDIR, $configfile or croak "Config::General: Could not open directory $configfile!($!)\n";
475 my @files = sort grep { -f catfile($configfile, $_) } catfile($configfile, $_), readdir INCLUDEDIR;
477 local $this->{CurrentConfigFilePath} = $configfile;
479 my $file = catfile($configfile, $_);
480 if (! exists $this->{files}->{$file} or $this->{IncludeAgain} ) {
481 # support re-read if used urged us to do so, otherwise ignore the file
484 open( $fh, "<:utf8", $file)
485 or croak "Config::General: Could not open $file in UTF8 mode!($!)\n";
488 $fh = IO::File->new( $file, 'r') or croak "Config::General: Could not open $file!($!)\n";
490 $this->{files}->{"$file"} = 1;
494 warn "File $file already loaded. Use -IncludeAgain to load it again.\n";
499 if (exists $this->{files}->{$configfile} and not $this->{IncludeAgain}) {
500 # do not read the same file twice, just return
501 warn "File $configfile already loaded. Use -IncludeAgain to load it again.\n";
507 open( $fh, "<:utf8", $configfile)
508 or croak "Config::General: Could not open $configfile in UTF8 mode!($!)\n";
511 $fh = IO::File->new( "$configfile", 'r')
512 or croak "Config::General: Could not open $configfile!($!)\n";
515 $this->{files}->{$configfile} = 1;
517 my ($volume, $path, undef) = splitpath($configfile);
518 local $this->{CurrentConfigFilePath} = catpath($volume, $path, q());
529 # store the config contents in @content
530 # and prepare it somewhat for easier parsing later
531 # (comments, continuing lines, and stuff)
533 my($this, $fh, $flag) = @_;
534 my(@stuff, @content, $c_comment, $longline, $hier, $hierend, @hierdoc);
537 if ($flag && $flag eq 'SCALAR') {
538 if (ref($fh) eq 'ARRAY') {
542 @stuff = split /\n/, $fh;
550 if ($this->{AutoLaunder}) {
558 if ($this->{CComments}) {
559 # look for C-Style comments, if activated
560 if (/(\s*\/\*.*\*\/\s*)/) {
561 # single c-comment on one line
562 s/\s*\/\*.*\*\/\s*//;
565 # the beginning of a C-comment ("/*"), from now on ignore everything.
567 # C-comment end is already there, so just ignore this line!
576 warn "invalid syntax: found end of C-comment without previous start!\n";
578 $c_comment = 0; # the current C-comment ends here, go on
579 s/^.*\*\///; # if there is still stuff, it will be read
581 next if($c_comment); # ignore EVERYTHING from now on, IF it IS a C-Comment
586 # inside here-doc, only look for $hierend marker
587 if (/^(\s*)\Q$hierend\E\s*$/) {
588 my $indent = $1; # preserve indentation
589 $hier .= ' ' . $this->{EOFseparator}; # bugfix of rt.40925
590 # _parse will also preserver indentation
593 s/^$indent//; # i.e. the end was: " EOF" then we remove " " from every here-doc line
594 $hier .= $_ . "\n"; # and store it in $hier
598 $hier .= join "\n", @hierdoc; # there was no indentation of the end-string, so join it 1:1
600 push @{$this->{content}}, $hier; # push it onto the content stack
606 # everything else onto the stack
613 ### non-heredoc entries from now on
616 # Remove comments and empty lines
617 s/(?<!\\)#.*$//; # .+ => .* bugfix rt.cpan.org#44600
622 # look for multiline option, indicated by a trailing backslash
623 my $extra = $this->{BackslashEscape} ? '(?<!\\\\)' : q();
631 # remove the \ from all characters if BackslashEscape is turned on
632 # FIXME (rt.cpan.org#33218
633 if ($this->{BackslashEscape}) {
637 # remove the \ char in front of masked "#", if any
642 # transform explicit-empty blocks to conforming blocks
643 if (!$this->{ApacheCompatible} && /\s*<([^\/]+?.*?)\/>$/) {
645 if ($block !~ /\"/) {
646 if ($block !~ /\s[^\s]/) {
647 # fix of bug 7957, add quotation to pure slash at the
648 # end of a block so that it will be considered as directory
649 # unless the block is already quoted or contains whitespaces
651 if ($this->{SlashIsDirectory}) {
652 push @{$this->{content}}, '<' . $block . '"/">';
659 $block =~ s/\s\s*.*$//;
660 push @{$this->{content}}, $orig, "</${block}>";
665 # look for here-doc identifier
666 if ($this->{SplitPolicy} eq 'guess') {
667 if (/^\s*([^=]+?)\s*=\s*<<\s*(.+?)\s*$/) {
668 # try equal sign (fix bug rt#36607)
669 $hier = $1; # the actual here-doc variable name
670 $hierend = $2; # the here-doc identifier, i.e. "EOF"
673 elsif (/^\s*(\S+?)\s+<<\s*(.+?)\s*$/) {
675 $hier = $1; # the actual here-doc variable name
676 $hierend = $2; # the here-doc identifier, i.e. "EOF"
681 # no guess, use one of the configured strict split policies
682 if (/^\s*(.+?)($this->{SplitDelimiter})<<\s*(.+?)\s*$/) {
683 $hier = $1; # the actual here-doc variable name
684 $hierend = $3; # the here-doc identifier, i.e. "EOF"
692 ### any "normal" config lines from now on
696 # previous stuff was a longline and this is the last line of the longline
699 push @{$this->{content}}, $longline; # push it onto the content stack
704 # look for include statement(s)
707 if ( $this->{IncludeRelative} and defined $this->{CurrentConfigFilePath}) {
708 $path = $this->{CurrentConfigFilePath};
710 elsif (defined $this->{ConfigPath}) {
711 # fetch pathname of base config file, assuming the 1st one is the path of it
712 $path = $this->{ConfigPath}->[0];
715 # bugfix rt.cpan.org#38635: support quoted filenames
716 if ($this->{UseApacheInclude}) {
717 if (/^\s*include\s*(["'])(.*?)(?<!\\)\1$/i) {
720 elsif (/^\s*include\s+(.+?)\s*$/i) {
725 if (/^\s*<<include\s+(.+?)>>\s*$/i) {
731 if ( $this->{IncludeRelative} && $path && !file_name_is_absolute($incl_file) ) {
732 # include the file from within location of $this->{configfile}
733 $this->_open( $incl_file, $path );
736 # include the file from within pwd, or absolute
737 $this->_open($incl_file);
741 # standard entry, (option = value)
742 push @{$this->{content}}, $_;
757 # parse the contents of the file
759 my($this, $config, $content) = @_;
760 my(@newcontent, $block, $blockname, $chunk,$block_level);
763 foreach (@{$content}) { # loop over content stack
766 $_ =~ s/^\s+//; # strip spaces @ end and begin
770 # build option value assignment, split current input
771 # using whitespace, equal sign or optionally here-doc
772 # separator EOFseparator
774 if (/$this->{EOFseparator}/) {
775 ($option,$value) = split /\s*$this->{EOFseparator}\s*/, $_, 2; # separated by heredoc-finding in _open()
778 if ($this->{SplitPolicy} eq 'guess') {
779 # again the old regex. use equalsign SplitPolicy to get the
780 # 2.00 behavior. the new regexes were too odd.
781 ($option,$value) = split /\s*=\s*|\s+/, $_, 2;
784 # no guess, use one of the configured strict split policies
785 ($option,$value) = split /$this->{SplitDelimiter}/, $_, 2;
789 if ($value && $value =~ /^"/ && $value =~ /"$/) {
790 $value =~ s/^"//; # remove leading and trailing "
793 if (! defined $block) { # not inside a block @ the moment
794 if (/^<([^\/]+?.*?)>$/) { # look if it is a block
795 $block = $1; # store block name
796 if ($block =~ /^"([^"]+)"$/) {
797 # quoted block, unquote it and do not split
801 # If it is a named block store the name separately; allow the block and name to each be quoted
802 if ($block =~ /^(?:"([^"]+)"|(\S+))(?:\s+(?:"([^"]+)"|(.*)))?$/) {
804 $blockname = $3 || $4;
807 if ($this->{InterPolateVars}) {
808 # interpolate block(name), add "<" and ">" to the key, because
809 # it is sure that such keys does not exist otherwise.
810 $block = $this->_interpolate($config, "<$block>", $block);
811 if (defined $blockname) {
812 $blockname = $this->_interpolate($config, "<$blockname>", "$blockname");
815 if ($this->{LowerCaseNames}) {
816 $block = lc $block; # only for blocks lc(), if configured via new()
822 elsif (/^<\/(.+?)>$/) { # it is an end block, but we don't have a matching block!
823 croak "Config::General: EndBlock \"<\/$1>\" has no StartBlock statement (level: $this->{level}, chunk $chunk)!\n";
825 else { # insert key/value pair into actual node
826 if ($this->{LowerCaseNames}) {
827 $option = lc $option;
830 if (exists $config->{$option}) {
831 if ($this->{MergeDuplicateOptions}) {
832 $config->{$option} = $this->_parse_value($config, $option, $value);
834 # bugfix rt.cpan.org#33216
835 if ($this->{InterPolateVars}) {
836 # save pair on local stack
837 $config->{__stack}->{$option} = $config->{$option};
841 if (! $this->{AllowMultiOptions} ) {
842 # no, duplicates not allowed
843 croak "Config::General: Option \"$option\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
846 # yes, duplicates allowed
847 if (ref($config->{$option}) ne 'ARRAY') { # convert scalar to array
848 my $savevalue = $config->{$option};
849 delete $config->{$option};
850 push @{$config->{$option}}, $savevalue;
853 # check if arrays are supported by the underlying hash
854 my $i = scalar @{$config->{$option}};
857 $config->{$option} = $this->_parse_value($config, $option, $value);
860 # it's already an array, just push
861 push @{$config->{$option}}, $this->_parse_value($config, $option, $value);
867 # standard config option, insert key/value pair into node
868 $config->{$option} = $this->_parse_value($config, $option, $value);
870 if ($this->{InterPolateVars}) {
871 # save pair on local stack
872 $config->{__stack}->{$option} = $config->{$option};
877 elsif (/^<([^\/]+?.*?)>$/) { # found a start block inside a block, don't forget it
878 $block_level++; # $block_level indicates wether we are still inside a node
879 push @newcontent, $_; # push onto new content stack for later recursive call of _parse()
881 elsif (/^<\/(.+?)>$/) {
882 if ($block_level) { # this endblock is not the one we are searching for, decrement and push
883 $block_level--; # if it is 0, then the endblock was the one we searched for, see below
884 push @newcontent, $_; # push onto new content stack
886 else { # calling myself recursively, end of $block reached, $block_level is 0
887 if (defined $blockname) {
888 # a named block, make it a hashref inside a hash within the current node
890 if (! exists $config->{$block}) {
891 # Make sure that the hash is not created implicitly
892 $config->{$block} = $this->_hashref();
894 if ($this->{InterPolateVars}) {
895 # inherit current __stack to new block
896 $config->{$block}->{__stack} = $this->_copy($config->{__stack});
900 if (ref($config->{$block}) eq '') {
901 croak "Config::General: Block <$block> already exists as scalar entry!\n";
903 elsif (ref($config->{$block}) eq 'ARRAY') {
904 croak "Config::General: Cannot append named block <$block $blockname> to array of scalars!\n"
905 ."Block <$block> or scalar '$block' occurs more than once.\n"
906 ."Turn on -MergeDuplicateBlocks or make sure <$block> occurs only once in the config.\n";
908 elsif (exists $config->{$block}->{$blockname}) {
909 # the named block already exists, make it an array
910 if ($this->{MergeDuplicateBlocks}) {
911 # just merge the new block with the same name as an existing one into
913 $config->{$block}->{$blockname} = $this->_parse($config->{$block}->{$blockname}, \@newcontent);
916 if (! $this->{AllowMultiOptions}) {
917 croak "Config::General: Named block \"<$block $blockname>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
919 else { # preserve existing data
920 my $savevalue = $config->{$block}->{$blockname};
921 delete $config->{$block}->{$blockname};
923 if (ref $savevalue eq 'ARRAY') {
924 push @ar, @{$savevalue}; # preserve array if any
927 push @ar, $savevalue;
929 push @ar, $this->_parse( $this->_hashref(), \@newcontent); # append it
930 $config->{$block}->{$blockname} = \@ar;
935 # the first occurence of this particular named block
936 my $tmphash = $this->_hashref();
938 if ($this->{InterPolateVars}) {
939 # inherit current __stack to new block
940 $tmphash->{__stack} = $this->_copy($config->{__stack});
941 #$tmphash->{__stack} = $config->{$block}->{__stack};
944 $config->{$block}->{$blockname} = $this->_parse($tmphash, \@newcontent);
949 if (exists $config->{$block}) {
950 if (ref($config->{$block}) eq '') {
951 croak "Config::General: Cannot create hashref from <$block> because there is\n"
952 ."already a scalar option '$block' with value '$config->{$block}'\n";
955 # the block already exists, make it an array
956 if ($this->{MergeDuplicateBlocks}) {
957 # just merge the new block with the same name as an existing one into
959 $config->{$block} = $this->_parse($config->{$block}, \@newcontent);
962 if (! $this->{AllowMultiOptions}) {
963 croak "Config::General: Block \"<$block>\" occurs more than once (level: $this->{level}, chunk $chunk)!\n";
966 my $savevalue = $config->{$block};
967 delete $config->{$block};
969 if (ref $savevalue eq "ARRAY") {
970 push @ar, @{$savevalue};
973 push @ar, $savevalue;
977 my $tmphash = $this->_hashref();
978 if ($this->{InterPolateVars}) {
979 # inherit current __stack to new block
980 $tmphash->{__stack} = $this->_copy($config->{__stack});
983 push @ar, $this->_parse( $tmphash, \@newcontent);
985 $config->{$block} = \@ar;
990 # the first occurence of this particular block
991 my $tmphash = $this->_hashref();
993 if ($this->{InterPolateVars}) {
994 # inherit current __stack to new block
995 $tmphash->{__stack} = $this->_copy($config->{__stack});
998 $config->{$block} = $this->_parse($tmphash, \@newcontent);
1003 $this->{level} -= 1;
1007 else { # inside $block, just push onto new content stack
1008 push @newcontent, $_;
1012 # $block is still defined, which means, that it had
1013 # no matching endblock!
1014 croak "Config::General: Block \"<$block>\" has no EndBlock statement (level: $this->{level}, chunk $chunk)!\n";
1022 # copy the contents of one hash into another
1023 # to circumvent invalid references
1024 # fixes rt.cpan.org bug #35122
1025 my($this, $source) = @_;
1027 while (my ($key, $value) = each %{$source}) {
1028 $hash{$key} = $value;
1036 # parse the value if value parsing is turned on
1037 # by either -AutoTrue and/or -FlagBits
1038 # otherwise just return the given value unchanged
1040 my($this, $config, $option, $value) =@_;
1042 # avoid "Use of uninitialized value"
1043 if (! defined $value) {
1044 $value = undef; # bigfix rt.cpan.org#42721 q();
1047 if ($this->{InterPolateVars}) {
1048 $value = $this->_interpolate($config, $option, $value);
1051 # make true/false values to 1 or 0 (-AutoTrue)
1052 if ($this->{AutoTrue}) {
1053 if ($value =~ /$this->{AutoTrueFlags}->{true}/io) {
1056 elsif ($value =~ /$this->{AutoTrueFlags}->{false}/io) {
1061 # assign predefined flags or undef for every flag | flag ... (-FlagBits)
1062 if ($this->{FlagBits}) {
1063 if (exists $this->{FlagBitsFlags}->{$option}) {
1064 my %__flags = map { $_ => 1 } split /\s*\|\s*/, $value;
1065 foreach my $flag (keys %{$this->{FlagBitsFlags}->{$option}}) {
1066 if (exists $__flags{$flag}) {
1067 $__flags{$flag} = $this->{FlagBitsFlags}->{$option}->{$flag};
1070 $__flags{$flag} = undef;
1084 sub NoMultiOptions {
1086 # turn AllowMultiOptions off, still exists for backward compatibility.
1087 # Since we do parsing from within new(), we must
1088 # call it again if one turns NoMultiOptions on!
1090 croak q(Config::Genera: lThe NoMultiOptions() method is deprecated. Set 'AllowMultiOptions' to 'no' instead!);
1096 # this is the old version of save() whose API interface
1097 # has been changed. I'm very sorry 'bout this.
1099 # I'll try to figure out, if it has been called correctly
1100 # and if yes, feed the call to Save(), otherwise croak.
1102 my($this, $one, @two) = @_;
1104 if ( (@two && $one) && ( (scalar @two) % 2 == 0) ) {
1105 # @two seems to be a hash
1107 $this->save_file($one, \%h);
1110 croak q(Config::General: The save() method is deprecated. Use the new save_file() method instead!);
1118 # save the config back to disk
1120 my($this, $file, $config) = @_;
1125 croak "Config::General: Filename is required!";
1128 if ($this->{UTF8}) {
1130 open($fh, ">:utf8", $file)
1131 or croak "Config::General: Could not open $file in UTF8 mode!($!)\n";
1134 $fh = IO::File->new( "$file", 'w')
1135 or croak "Config::General: Could not open $file!($!)\n";
1138 if (exists $this->{config}) {
1139 $config_string = $this->_store(0, $this->{config});
1142 croak "Config::General: No config hash supplied which could be saved to disk!\n";
1146 $config_string = $this->_store(0, $config);
1149 if ($config_string) {
1150 print {$fh} $config_string;
1153 # empty config for whatever reason, I don't care
1166 # return the saved config as a string
1168 my($this, $config) = @_;
1170 if (!$config || ref($config) ne 'HASH') {
1171 if (exists $this->{config}) {
1172 return $this->_store(0, $this->{config});
1175 croak "Config::General: No config hash supplied which could be saved to disk!\n";
1179 return $this->_store(0, $config);
1188 # internal sub for saving a block
1190 my($this, $level, $config) = @_;
1192 my $indent = q( ) x $level;
1194 my $config_string = q();
1196 if($this->{SaveSorted}) {
1197 # ahm, well this might look strange because the two loops
1198 # are obviously the same, but I don't know how to call
1199 # a foreach() with sort and without sort() on the same
1200 # line (I think it's impossible)
1201 foreach my $entry (sort keys %{$config}) {
1202 if (ref($config->{$entry}) eq 'ARRAY') {
1203 foreach my $line (sort @{$config->{$entry}}) {
1204 if (ref($line) eq 'HASH') {
1205 $config_string .= $this->_write_hash($level, $entry, $line);
1208 $config_string .= $this->_write_scalar($level, $entry, $line);
1212 elsif (ref($config->{$entry}) eq 'HASH') {
1213 $config_string .= $this->_write_hash($level, $entry, $config->{$entry});
1216 $config_string .= $this->_write_scalar($level, $entry, $config->{$entry});
1221 foreach my $entry (keys %{$config}) {
1222 if (ref($config->{$entry}) eq 'ARRAY') {
1223 foreach my $line (@{$config->{$entry}}) {
1224 if (ref($line) eq 'HASH') {
1225 $config_string .= $this->_write_hash($level, $entry, $line);
1228 $config_string .= $this->_write_scalar($level, $entry, $line);
1232 elsif (ref($config->{$entry}) eq 'HASH') {
1233 $config_string .= $this->_write_hash($level, $entry, $config->{$entry});
1236 $config_string .= $this->_write_scalar($level, $entry, $config->{$entry});
1241 return $config_string;
1247 # internal sub, which writes a scalar
1248 # it returns it, in fact
1250 my($this, $level, $entry, $line) = @_;
1252 my $indent = q( ) x $level;
1256 if ($line =~ /\n/ || $line =~ /\\$/) {
1259 my $tmplimiter = 'EOF';
1260 while (!$delimiter) {
1261 # create a unique here-doc identifier
1262 if ($line =~ /$tmplimiter/s) {
1263 $tmplimiter .= q(%);
1266 $delimiter = $tmplimiter;
1269 my @lines = split /\n/, $line;
1270 $config_string .= $indent . $entry . $this->{StoreDelimiter} . "<<$delimiter\n";
1272 $config_string .= $indent . $_ . "\n";
1274 $config_string .= $indent . "$delimiter\n";
1277 # a simple stupid scalar entry
1279 # bugfix rt.cpan.org#42287
1280 if ($line =~ /^\s/ or $line =~ /\s$/) {
1282 $line = "\"$line\"";
1284 $config_string .= $indent . $entry . $this->{StoreDelimiter} . $line . "\n";
1287 return $config_string;
1292 # internal sub, which writes a hash (block)
1293 # it returns it, in fact
1295 my($this, $level, $entry, $line) = @_;
1297 my $indent = q( ) x $level;
1300 if ($entry =~ /\s/) {
1301 # quote the entry if it contains whitespaces
1302 $entry = q(") . $entry . q(");
1305 $config_string .= $indent . q(<) . $entry . ">\n";
1306 $config_string .= $this->_store($level + 1, $line);
1307 $config_string .= $indent . q(</) . $entry . ">\n";
1309 return $config_string
1315 # return a probably tied new empty hash ref
1320 eval qq{require $this->{Tie}};
1323 croak q(Config::General: Could not create a tied hash of type: ) . $this->{Tie} . q(: ) . $EVAL_ERROR;
1326 tie %hash, $this->{Tie};
1337 # Procedural interface
1341 # @_ may contain everything which is allowed for new()
1343 return (new Config::General(@_))->getall();
1348 # 2 parameters are required, filename and hash ref
1350 my ($file, $hash) = @_;
1352 if (!$file || !$hash) {
1353 croak q{Config::General::SaveConfig(): filename and hash argument required.};
1356 if (ref($hash) ne 'HASH') {
1357 croak q(Config::General::SaveConfig() The second parameter must be a reference to a hash!);
1360 (new Config::General(-ConfigHash => $hash))->save_file($file);
1366 sub SaveConfigString {
1368 # same as SaveConfig, but return the config,
1369 # instead of saving it
1374 croak q{Config::General::SaveConfigString(): Hash argument required.};
1377 if (ref($hash) ne 'HASH') {
1378 croak q(Config::General::SaveConfigString() The parameter must be a reference to a hash!);
1381 return (new Config::General(-ConfigHash => $hash))->save_string();
1399 Config::General - Generic Config Module
1405 use Config::General;
1406 $conf = new Config::General("rcfile");
1407 my %config = $conf->getall;
1410 # the procedural way
1411 use Config::General qw(ParseConfig SaveConfig SaveConfigString);
1412 my %config = ParseConfig("rcfile");
1416 This module opens a config file and parses its contents for you. The B<new> method
1417 requires one parameter which needs to be a filename. The method B<getall> returns a hash
1418 which contains all options and its associated values of your config file.
1420 The format of config files supported by B<Config::General> is inspired by the well known Apache config
1421 format, in fact, this module is 100% compatible to Apache configs, but you can also just use simple
1422 name/value pairs in your config files.
1424 In addition to the capabilities of an Apache config file it supports some enhancements such as here-documents,
1425 C-style comments or multiline options.
1428 =head1 SUBROUTINES/METHODS
1434 Possible ways to call B<new()>:
1436 $conf = new Config::General("rcfile");
1438 $conf = new Config::General(\%somehash);
1440 $conf = new Config::General( %options ); # see below for description of possible options
1443 This method returns a B<Config::General> object (a hash blessed into "Config::General" namespace.
1444 All further methods must be used from that returned object. see below.
1446 You can use the new style with hash parameters or the old style which is of course
1447 still supported. Possible parameters to B<new()> are:
1449 * a filename of a configfile, which will be opened and parsed by the parser
1453 * a hash reference, which will be used as the config.
1455 An alternative way to call B<new()> is supplying an option- hash with one or more of
1456 the following keys set:
1460 =item B<-ConfigFile>
1462 A filename or a filehandle, i.e.:
1464 -ConfigFile => "rcfile" or -ConfigFile => \$FileHandle
1468 =item B<-ConfigHash>
1470 A hash reference, which will be used as the config, i.e.:
1472 -ConfigHash => \%somehash
1478 A string which contains a whole config, or an arrayref
1479 containing the whole config line by line.
1480 The parser will parse the contents of the string instead
1483 -String => $complete_config
1485 it is also possible to feed an array reference to -String:
1487 -String => \@config_lines
1491 =item B<-AllowMultiOptions>
1493 If the value is "no", then multiple identical options are disallowed.
1494 The default is "yes".
1497 -AllowMultiOptions => "yes"
1499 see B<IDENTICAL OPTIONS> for details.
1501 =item B<-LowerCaseNames>
1503 If set to a true value, then all options found in the config will be converted
1504 to lowercase. This allows you to provide case-in-sensitive configs. The
1505 values of the options will B<not> lowercased.
1509 =item B<-UseApacheInclude>
1511 If set to a true value, the parser will consider "include ..." as valid include
1512 statement (just like the well known Apache include statement).
1516 =item B<-IncludeRelative>
1518 If set to a true value, included files with a relative path (i.e. "cfg/blah.conf")
1519 will be opened from within the location of the configfile instead from within the
1520 location of the script($0). This works only if the configfile has a absolute pathname
1521 (i.e. "/etc/main.conf").
1523 If the variable B<-ConfigPath> has been set and if the file to be included could
1524 not be found in the location relative to the current config file, the module
1525 will search within B<-ConfigPath> for the file. See the description of B<-ConfigPath>
1529 =item B<-IncludeDirectories>
1531 If set to a true value, you may specify include a directory, in which case all
1532 files inside the directory will be loaded in ASCII order. Directory includes
1533 will not recurse into subdirectories. This is comparable to including a
1534 directory in Apache-style config files.
1537 =item B<-IncludeGlob>
1539 If set to a true value, you may specify a glob pattern for an include to
1540 include all matching files (e.g. <<include conf.d/*.conf>>). Also note that as
1541 with standard file patterns, * will not match dot-files, so <<include dir/*>>
1542 is often more desirable than including a directory with B<-IncludeDirectories>.
1545 =item B<-IncludeAgain>
1547 If set to a true value, you will be able to include a sub-configfile
1548 multiple times. With the default, false, you will get a warning about
1549 duplicate includes and only the first include will succeed.
1551 Reincluding a configfile can be useful if it contains data that you want to
1552 be present in multiple places in the data tree. See the example under
1555 Note, however, that there is currently no check for include recursion.
1558 =item B<-ConfigPath>
1560 As mentioned above, you can use this variable to specify a search path for relative
1561 config files which have to be included. Config::General will search within this
1562 path for the file if it cannot find the file at the location relative to the
1563 current config file.
1565 To provide multiple search paths you can specify an array reference for the
1568 @path = qw(/usr/lib/perl /nfs/apps/lib /home/lib);
1570 -ConfigPath => \@path
1574 =item B<-MergeDuplicateBlocks>
1576 If set to a true value, then duplicate blocks, that means blocks and named blocks,
1577 will be merged into a single one (see below for more details on this).
1578 The default behavior of Config::General is to create an array if some junk in a
1579 config appears more than once.
1582 =item B<-MergeDuplicateOptions>
1584 If set to a true value, then duplicate options will be merged. That means, if the
1585 same option occurs more than once, the last one will be used in the resulting
1588 Setting this option implies B<-AllowMultiOptions == false> unless you set
1589 B<-AllowMultiOptions> explicit to 'true'. In this case duplicate blocks are
1590 allowed and put into an array but duplicate options will be merged.
1593 =item B<-AutoLaunder>
1595 If set to a true value, then all values in your config file will be laundered
1596 to allow them to be used under a -T taint flag. This could be regarded as circumventing
1597 the purpose of the -T flag, however, if the bad guys can mess with your config file,
1598 you have problems that -T will not be able to stop. AutoLaunder will only handle
1599 a config file being read from -ConfigFile.
1605 If set to a true value, then options in your config file, whose values are set to
1606 true or false values, will be normalised to 1 or 0 respectively.
1608 The following values will be considered as B<true>:
1612 The following values will be considered as B<false>:
1616 This effect is case-insensitive, i.e. both "Yes" or "oN" will result in 1.
1621 This option takes one required parameter, which must be a hash reference.
1623 The supplied hash reference needs to define variables for which you
1624 want to preset values. Each variable you have defined in this hash-ref
1625 and which occurs in your config file, will cause this variable being
1626 set to the preset values to which the value in the config file refers to.
1628 Multiple flags can be used, separated by the pipe character |.
1630 Well, an example will clarify things:
1632 my $conf = new Config::General(
1633 -ConfigFile => "rcfile",
1638 UNSECURE => "32bit" }
1642 In this example we are defining a variable named I<"Mode"> which
1643 may contain one or more of "CLEAR", "STRONG" and "UNSECURE" as value.
1645 The appropriate config entry may look like this:
1648 Mode = CLEAR | UNSECURE
1650 The parser will create a hash which will be the value of the key "Mode". This
1651 hash will contain B<all> flags which you have pre-defined, but only those
1652 which were set in the config will contain the pre-defined value, the other
1653 ones will be undefined.
1655 The resulting config structure would look like this after parsing:
1660 UNSECURE => "32bit",
1665 This method allows the user (or, the "maintainer" of the configfile for your
1666 application) to set multiple pre-defined values for one option.
1668 Please beware, that all occurrences of those variables will be handled this
1669 way, there is no way to distinguish between variables in different scopes.
1670 That means, if "Mode" would also occur inside a named block, it would
1671 also parsed this way.
1673 Values which are not defined in the hash-ref supplied to the parameter B<-FlagBits>
1674 and used in the corresponding variable in the config will be ignored.
1681 would result in this hash structure:
1691 "BLAH" will be ignored silently.
1694 =item B<-DefaultConfig>
1696 This can be a hash reference or a simple scalar (string) of a config. This
1697 causes the module to preset the resulting config hash with the given values,
1698 which allows you to set default values for particular config options directly.
1703 B<-Tie> takes the name of a Tie class as argument that each new hash should be
1706 This hash will be used as the 'backing hash' instead of a standard Perl hash,
1707 which allows you to affect the way, variable storing will be done. You could, for
1708 example supply a tied hash, say Tie::DxHash, which preserves ordering of the
1709 keys in the config (which a standard Perl hash won't do). Or, you could supply
1710 a hash tied to a DBM file to save the parsed variables to disk.
1712 There are many more things to do in tie-land, see L<tie> to get some interesting
1715 If you want to use the B<-Tie> feature together with B<-DefaultConfig> make sure
1716 that the hash supplied to B<-DefaultConfig> must be tied to the same Tie class.
1718 Make sure that the hash which receives the generated hash structure (e.g. which
1719 you are using in the assignment: %hash = $config->getall()) must be tied to
1724 use Config::General qw(ParseConfig);
1726 tie my %hash, "Tie::IxHash";
1727 %hash = ParseConfig(
1728 -ConfigFile => shift(),
1729 -Tie => "Tie::IxHash"
1733 =item B<-InterPolateVars>
1735 If set to a true value, variable interpolation will be done on your config
1736 input. See L<Config::General::Interpolated> for more information.
1738 =item B<-InterPolateEnv>
1740 If set to a true value, environment variables can be used in
1743 This implies B<-InterPolateVars>.
1745 =item B<-ExtendedAccess>
1747 If set to a true value, you can use object oriented (extended) methods to
1748 access the parsed config. See L<Config::General::Extended> for more informations.
1750 =item B<-StrictObjects>
1752 By default this is turned on, which causes Config::General to croak with an
1753 error if you try to access a non-existent key using the OOP-way (B<-ExtendedAcess>
1754 enabled). If you turn B<-StrictObjects> off (by setting to 0 or "no") it will
1755 just return an empty object/hash/scalar. This is valid for OOP-access 8via AUTOLOAD
1756 and for the methods obj(), hash() and value().
1759 =item B<-StrictVars>
1761 By default this is turned on, which causes Config::General to croak with an
1762 error if an undefined variable with B<InterPolateVars> turned on occurs
1763 in a config. Set to I<false> (i.e. 0) to avoid such error messages.
1765 =item B<-SplitPolicy>
1767 You can influence the way how Config::General decides which part of a line
1768 in a config file is the key and which one is the value. By default it tries
1769 its best to guess. That means you can mix equalsign assignments and whitespace
1772 However, somtime you may wish to make it more strictly for some reason. In
1773 this case you can set B<-SplitPolicy>. The possible values are: 'guess' which
1774 is the default, 'whitespace' which causes the module to split by whitespace,
1775 'equalsign' which causes it to split strictly by equal sign, or 'custom'. In the
1776 latter case you must also set B<-SplitDelimiter> to some regular expression
1777 of your choice. For example:
1779 -SplitDelimiter => '\s*:\s*'
1781 will cause the module to split by colon while whitespace which surrounds
1782 the delimiter will be removed.
1784 Please note that the delimiter used when saving a config (save_file() or save_string())
1785 will be chosen according to the current B<-SplitPolicy>. If -SplitPolicy is
1786 set to 'guess' or 'whitespace', 3 spaces will be used to delimit saved
1787 options. If 'custom' is set, then you need to set B<-StoreDelimiter>.
1789 =item B<-SplitDelimiter>
1791 Set this to any arbitrary regular expression which will be used for option/value
1792 splitting. B<-SplitPolicy> must be set to 'custom' to make this work.
1794 =item B<-StoreDelimiter>
1796 You can use this parameter to specify a custom delimiter to use when saving
1797 configs to a file or string. You only need to set it if you want to store
1798 the config back to disk and if you have B<-SplitPolicy> set to 'custom'.
1800 Be very careful with this parameter.
1805 Config::General is able to notice c-style comments (see section COMMENTS).
1806 But for some reason you might no need this. In this case you can turn
1807 this feature off by setting B<-CComments> to a false value('no', 0, 'off').
1809 By default B<-CComments> is turned on.
1812 =item B<-BackslashEscape>
1814 If you turn on this parameter, a backslash can be used to escape any special
1815 character within configurations.
1817 By default it is turned off.
1819 Be careful with this option, as it removes all backslashes after parsing.
1821 B<This option might be removed in future versions>.
1823 =item B<-SlashIsDirectory>
1825 If you turn on this parameter, a single slash as the last character
1826 of a named block will be considered as a directory name.
1828 By default this flag is turned off, which makes the module somewhat
1829 incompatible to Apache configs, since such a setup will be normally
1830 considered as an explicit empty block, just as XML defines it.
1832 For example, if you have the following config:
1838 you will get such an error message from the parser:
1840 EndBlock "</Directory>" has no StartBlock statement (level: 1, chunk 10)!
1842 This is caused by the fact that the config chunk below will be
1843 internally converted to:
1845 <Directory><Directory />
1849 Now there is one '</Directory>' too much. The proper solution is
1850 to use quotation to circumvent this error:
1856 However, a raw apache config comes without such quotes. In this
1857 case you may consider to turn on B<-SlashIsDirectory>.
1859 Please note that this is a new option (incorporated in version 2.30),
1860 it may lead to various unexpected side effects or other failures.
1863 =item B<-ApacheCompatible>
1865 Over the past years a lot of options has been incorporated
1866 into Config::General to be able to parse real Apache configs.
1868 The new B<-ApacheCompatible> option now makes it possible to
1869 tweak all options in a way that Apache configs can be parsed.
1871 This is called "apache compatibility mode" - if you will ever
1872 have problems with parsing Apache configs without this option
1873 being set, you'll get no help by me. Thanks :)
1875 The following options will be set:
1877 UseApacheInclude = 1
1879 IncludeDirectories = 1
1881 SlashIsDirectory = 1
1882 SplitPolicy = 'equalsign'
1886 Take a look into the particular documentation sections what
1887 those options are doing.
1889 Beside setting some options it also turns off support for
1890 explicit empty blocks.
1894 If turned on, all files will be opened in utf8 mode. This may
1895 not work properly with older versions of Perl.
1897 =item B<-SaveSorted>
1899 If you want to save configs in a sorted manner, turn this
1900 parameter on. It is not enabled by default.
1909 Returns a hash structure which represents the whole config.
1913 Returns a list of all files read in.
1917 Writes the config hash back to the hard disk. This method takes one or two
1918 parameters. The first parameter must be the filename where the config
1919 should be written to. The second parameter is optional, it must be a
1920 reference to a hash structure, if you set it. If you do not supply this second parameter
1921 then the internal config hash, which has already been parsed, will be
1924 Please note that any occurence of comments will be ignored by getall()
1925 and thus be lost after you call this method.
1927 You need also to know that named blocks will be converted to nested blocks
1928 (which is the same from the perl point of view). An example:
1934 will become the following after saving:
1944 $conf_obj->save_file("newrcfile", \%config);
1946 or, if the config has already been parsed, or if it didn't change:
1948 $conf_obj->save_file("newrcfile");
1953 This method is equivalent to the previous save_file(), but it does not
1954 store the generated config to a file. Instead it returns it as a string,
1955 which you can save yourself afterwards.
1957 It takes one optional parameter, which must be a reference to a hash structure.
1958 If you omit this parameter, the internal config hash, which has already been parsed,
1963 my $content = $conf_obj->save_string(\%config);
1967 my $content = $conf_obj->save_string();
1973 =head1 CONFIG FILE FORMAT
1975 Lines beginning with B<#> and empty lines will be ignored. (see section COMMENTS!)
1976 Spaces at the beginning and the end of a line will also be ignored as well as tabulators.
1977 If you need spaces at the end or the beginning of a value you can surround it with
1979 An option line starts with its name followed by a value. An equal sign is optional.
1980 Some possible examples:
1986 If there are more than one statements with the same name, it will create an array
1987 instead of a scalar. See the example below.
1989 The method B<getall> returns a hash of all values.
1994 You can define a B<block> of options. A B<block> looks much like a block
1995 in the wellknown Apache config format. It starts with E<lt>B<blockname>E<gt> and ends
1996 with E<lt>/B<blockname>E<gt>. An example:
2005 Blocks can also be nested. Here is a more complicated example:
2027 The hash which the method B<getall> returns look like that:
2029 print Data::Dumper(\%hash);
2031 'passwd' => 'D3rf$',
2033 'tablestructure' => {
2034 'prename' => 'char(100)',
2035 'index' => 'int(100000)',
2036 'city' => 'char(100)',
2037 'name' => 'char(100)',
2038 'status' => 'int(10)',
2050 'server' => 'mc200',
2054 If you have turned on B<-LowerCaseNames> (see new()) then blocks as in the
2063 would produce the following hash structure:
2073 As you can see, the keys inside the config hash are normalized.
2075 Please note, that the above config block would result in a
2076 valid hash structure, even if B<-LowerCaseNames> is not set!
2077 This is because I<Config::General> does not
2078 use the block names to check if a block ends, instead it uses an internal
2079 state counter, which indicates a block end.
2081 If the module cannot find an end-block statement, then this block will be ignored.
2087 If you need multiple blocks of the same name, then you have to name every block.
2088 This works much like Apache config. If the module finds a named block, it will
2089 create a hashref with the left part of the named block as the key containing
2090 one or more hashrefs with the right part of the block as key containing everything
2091 inside the block(which may again be nested!). As examples says more than words:
2093 # given the following sample
2094 <Directory /usr/frisco>
2096 Options ExecCgi Index
2098 <Directory /usr/frik>
2107 'Options' => 'None',
2108 'Limit' => 'DenyAll'
2111 'Options' => 'ExecCgi Index',
2117 You cannot have more than one named block with the same name because it will
2118 be stored in a hashref and therefore be overwritten if a block occurs once more.
2121 =head1 WHITESPACE IN BLOCKS
2123 The normal behavior of Config::General is to look for whitespace in
2124 block names to decide if it's a named block or just a simple block.
2126 Sometimes you may need blocknames which have whitespace in their names.
2128 With named blocks this is no problem, as the module only looks for the
2143 The problem occurs, if you want to have a simple block containing whitespace:
2148 This would be parsed as a named block, which is not what you wanted. In this
2149 very case you may use quotation marks to indicate that it is not a named block:
2154 The save() method of the module inserts automatically quotation marks in such
2158 =head1 EXPLICIT EMPTY BLOCKS
2160 Beside the notation of blocks mentioned above it is possible to use
2161 explicit empty blocks.
2163 Normally you would write this in your config to define an empty
2169 To save writing you can also write:
2173 which is the very same as above. This works for normal blocks and
2178 =head1 IDENTICAL OPTIONS
2180 You may have more than one line of the same option with different values.
2187 You will get a scalar if the option occurred only once or an array if it occurred
2188 more than once. If you expect multiple identical options, then you may need to
2189 check if an option occurred more than once:
2191 $allowed = $hash{jonas}->{tablestructure}->{allowed};
2192 if(ref($allowed) eq "ARRAY") {
2193 @ALLOWED = @{$allowed};
2195 @ALLOWED = ($allowed);
2198 The same applies to blocks and named blocks too (they are described in more detail
2199 below). For example, if you have the following config:
2208 then you would end up with a data structure like this:
2223 As you can see, the two identical blocks are stored in a hash which contains
2224 an array(-reference) of hashes.
2226 Under some rare conditions you might not want this behavior with blocks (and
2227 named blocks too). If you want to get one single hash with the contents of
2228 both identical blocks, then you need to turn the B<new()> parameter B<-MergeDuplicateBlocks>
2229 on (see above). The parsed structure of the example above would then look like
2243 As you can see, there is only one hash "dir->{blah}" containing multiple
2244 "user" entries. As you can also see, turning on B<-MergeDuplicateBlocks>
2245 does not affect scalar options (i.e. "option = value"). In fact you can
2246 tune merging of duplicate blocks and options independent from each other.
2248 If you don't want to allow more than one identical options, you may turn it off
2249 by setting the flag I<AllowMultiOptions> in the B<new()> method to "no".
2250 If turned off, Config::General will complain about multiple occurring options
2251 with identical names!
2257 If you have a config value, which is too long and would take more than one line,
2258 you can break it into multiple lines by using the backslash character at the end
2259 of the line. The Config::General module will concatenate those lines to one single-value.
2263 command = cat /var/log/secure/tripwire | \
2264 mail C<-s> "report from tripwire" \
2265 honey@myotherhost.nl
2267 command will become:
2268 "cat /var/log/secure/tripwire | mail C<-s> 'report from twire' honey@myotherhost.nl"
2271 =head1 HERE DOCUMENTS
2273 You can also define a config value as a so called "here-document". You must tell
2274 the module an identifier which idicates the end of a here document. An
2275 identifier must follow a "<<".
2286 Everything between the two "EOF" strings will be in the option I<message>.
2288 There is a special feature which allows you to use indentation with here documents.
2289 You can have any amount of whitespace or tabulators in front of the end
2290 identifier. If the module finds spaces or tabs then it will remove exactly those
2291 amount of spaces from every line inside the here-document.
2302 After parsing, message will become:
2309 because there were the string " " in front of EOF, which were cut from every
2310 line inside the here-document.
2316 You can include an external file at any posision in your config file using the following statement
2317 in your config file:
2319 <<include externalconfig.rc>>
2321 If you turned on B<-UseApacheInclude> (see B<new()>), then you can also use the following
2322 statement to include an external file:
2324 include externalconfig.rc
2326 This file will be inserted at the position where it was found as if the contents of this file
2327 were directly at this position.
2329 You can also recursively include files, so an included file may include another one and so on.
2330 Beware that you do not recursively load the same file, you will end with an error message like
2331 "too many open files in system!".
2333 By default included files with a relative pathname will be opened from within the current
2334 working directory. Under some circumstances it maybe possible to
2335 open included files from the directory, where the configfile resides. You need to turn on
2336 the option B<-IncludeRelative> (see B<new()>) if you want that. An example:
2338 my $conf = Config::General(
2339 -ConfigFile => "/etc/crypt.d/server.cfg"
2340 -IncludeRelative => 1
2343 /etc/crypt.d/server.cfg:
2346 In this example Config::General will try to include I<acl.cfg> from I</etc/crypt.d>:
2348 /etc/crypt.d/acl.cfg
2350 The default behavior (if B<-IncludeRelative> is B<not> set!) will be to open just I<acl.cfg>,
2351 wherever it is, i.e. if you did a chdir("/usr/local/etc"), then Config::General will include:
2353 /usr/local/etc/acl.cfg
2355 Include statements can be case insensitive (added in version 1.25).
2357 Include statements will be ignored within C-Comments and here-documents.
2359 By default, a config file will only be included the first time it is
2360 referenced. If you wish to include a file in multiple places, set
2361 B</-IncludeAgain> to true. But be warned: this may lead to infinite loops,
2362 so make sure, you're not including the same file from within itself!
2370 include printers.cfg
2375 class=Another::Class
2377 include printers.cfg
2382 Now C<printers.cfg> will be include in both the C<billy> and C<bob> objects.
2384 You will have to be careful to not recursively include a file. Behaviour
2385 in this case is undefined.
2391 A comment starts with the number sign B<#>, there can be any number of spaces and/or
2392 tab stops in front of the #.
2394 A comment can also occur after a config statement. Example:
2396 username = max # this is the comment
2398 If you want to comment out a large block you can use C-style comments. A B</*> signals
2399 the begin of a comment block and the B<*/> signals the end of the comment block.
2402 user = max # valid option
2409 In this example the second options of user and db will be ignored. Please beware of the fact,
2410 if the Module finds a B</*> string which is the start of a comment block, but no matching
2411 end block, it will ignore the whole rest of the config file!
2413 B<NOTE:> If you require the B<#> character (number sign) to remain in the option value, then
2414 you can use a backslash in front of it, to escape it. Example:
2418 In this example the value of $config{bgcolor} will be "#ffffcc", Config::General will not treat
2419 the number sign as the begin of a comment because of the leading backslash.
2421 Inside here-documents escaping of number signs is NOT required!
2424 =head1 OBJECT ORIENTED INTERFACE
2426 There is a way to access a parsed config the OO-way.
2427 Use the module B<Config::General::Extended>, which is
2428 supplied with the Config::General distribution.
2430 =head1 VARIABLE INTERPOLATION
2432 You can use variables inside your config files if you like. To do
2433 that you have to use the module B<Config::General::Interpolated>,
2434 which is supplied with the Config::General distribution.
2437 =head1 EXPORTED FUNCTIONS
2439 Config::General exports some functions too, which makes it somewhat
2440 easier to use it, if you like this.
2442 How to import the functions:
2444 use Config::General qw(ParseConfig SaveConfig SaveConfigString);
2448 =item B<ParseConfig()>
2450 This function takes exactly all those parameters, which are
2451 allowed to the B<new()> method of the standard interface.
2455 use Config::General qw(ParseConfig);
2456 my %config = ParseConfig(-ConfigFile => "rcfile", -AutoTrue => 1);
2459 =item B<SaveConfig()>
2461 This function requires two arguments, a filename and a reference
2462 to a hash structure.
2466 use Config::General qw(SaveConfig);
2468 SaveConfig("rcfile", \%some_hash);
2471 =item B<SaveConfigString()>
2473 This function requires a reference to a config hash as parameter.
2474 It generates a configuration based on this hash as the object-interface
2475 method B<save_string()> does.
2479 use Config::General qw(ParseConfig SaveConfigString);
2480 my %config = ParseConfig(-ConfigFile => "rcfile");
2481 .. # change %config something
2482 my $content = SaveConfigString(\%config);
2487 =head1 CONFIGURATION AND ENVIRONMENT
2489 No environment variables will be used.
2493 I recommend you to read the following documents, which are supplied with Perl:
2495 perlreftut Perl references short introduction
2496 perlref Perl references, the rest of the story
2497 perldsc Perl data structures intro
2498 perllol Perl data structures: arrays of arrays
2500 Config::General::Extended Object oriented interface to parsed configs
2501 Config::General::Interpolated Allows to use variables inside config files
2503 =head1 LICENSE AND COPYRIGHT
2505 Copyright (c) 2000-2009 Thomas Linden
2507 This library is free software; you can redistribute it and/or
2508 modify it under the same terms as Perl itself.
2510 =head1 BUGS AND LIMITATIONS
2512 See rt.cpan.org for current bugs, if any.
2514 =head1 INCOMPATIBILITIES
2520 To debug Config::General use the Perl debugger, see L<perldebug>.
2524 Config::General depends on the modules L<FileHandle>,
2525 L<File::Spec::Functions>, L<File::Glob>, which all are
2530 Thomas Linden <tlinden |AT| cpan.org>