Config::General - Generic Config Module
| Use Case | Command | Description |
|---|---|---|
| 📄 Parse config file (OOP) | Config::General->new("rcfile") | Create new config object from file |
| 📄 Parse config file (procedural) | ParseConfig("rcfile") | Parse config file returning hash |
| 📋 Get all config values | $conf->getall() | Return hash of entire config |
| 💾 Save config to file | $conf->save_file("newrcfile", \%config) | Write config hash to disk |
| 🔤 Save config as string | $conf->save_string(\%config) | Return config as string |
| 🧩 Parse with hash parameters | Config::General->new(-ConfigFile => "rcfile", -AutoTrue => 1) | Parse with options hash |
| 📂 Include external file | >]]> | Include config file inline |
| 🔗 Merge duplicate blocks | -MergeDuplicateBlocks => 1 | Merge identical blocks into one |
#
# the OOP way
use Config::General;
$conf = Config::General->new("rcfile");
my %config = $conf->getall;
#
# the procedural way
use Config::General qw(ParseConfig SaveConfig SaveConfigString);
my %config = ParseConfig("rcfile");
This module opens a config file and parses its contents for you. The new method requires one parameter which needs to be a filename. The method getall returns a hash which contains all options and its associated values of your config file.
The format of config files supported by Config::General is inspired by the well known Apache config format, in fact, this module is 100% compatible to Apache configs, but you can also just use simple name/value pairs in your config files.
In addition to the capabilities of an Apache config file it supports some enhancements such as here-documents, C-style comments or multiline options.
Possible ways to call new():
$conf = Config::General->new("rcfile");
$conf = Config::General->new(\%somehash);
$conf = Config::General->new( %options ); # see below for description of possible options
This method returns a Config::General object. All further methods must be used from that returned object.
You can use the new style with hash parameters or the old style which is of course still supported. Possible parameters to new() are:
An alternative way to call new() is supplying an option-hash with one or more of the following keys set:
-ConfigFile => "rcfile" or -ConfigFile => \$FileHandle-ConfigHash => \%somehash-String => $complete_config. It is also possible to feed an array reference to -String: -String => \@config_lines-AllowMultiOptions => "yes". See IDENTICAL OPTIONS for details.>]]>). Also note that as with standard file patterns, * will not match dot-files, so >]]> is often more desirable than including a directory with -IncludeDirectories. An include option will not cause a parser error if the glob didn't return anything.@path = qw(/usr/lib/perl /nfs/apps/lib /home/lib); .. -ConfigPath => \@pathyes, on, 1, true. The following values will be considered as false: no, off, 0, false. This effect is case-insensitive, i.e. both "Yes" or "No" will result in 1.my $conf = Config::General->new(-ConfigFile => "rcfile", -FlagBits => { Mode => { CLEAR => 1, STRONG => 1, UNSECURE => "32bit" } }); The config entry Mode = CLEAR | UNSECURE would result in: %config = ( Mode => { CLEAR => 1, UNSECURE => "32bit", STRONG => undef, } ); Values which are not defined in the hash-ref and used in the corresponding variable in the config will be ignored silently.%hash = $config->getall()) must be tied to the same Tie class. Example: use Config::General qw(ParseConfig); use Tie::IxHash; tie my %hash, "Tie::IxHash"; %hash = ParseConfig(-ConfigFile => shift(), -Tie => "Tie::IxHash");-SplitDelimiter => '\s*:\s*' will cause the module to split by colon while whitespace which surrounds the delimiter will be removed. Please note that the delimiter used when saving a config (save_file() or save_string()) will be chosen according to the current -SplitPolicy. If -SplitPolicy is set to 'guess' or 'whitespace', 3 spaces will be used to delimit saved options. If 'custom' is set, then you need to set -StoreDelimiter.]]> ... ]]> you will get an error message. The proper solution is to use quotation to circumvent this error: ]]>. However, a raw apache config comes without such quotes. In this case you may consider to turn on -SlashIsDirectory. Please note that this is a new option (incorporated in version 2.30), it may lead to various unexpected side effects or other failures. You've been warned.]]> ... ]]>. See -Define.-Define => 'TEST', -Define => \$testOrProduction, -Define => [qw(TEST VERBOSE)], -Define => {TEST => 1, VERBOSE => 1}. Sample configuration: Level Debug include test/*.cfg Level Notice include production/*.cfg ]]>UseApacheInclude = 1, IncludeRelative = 1, IncludeDirectories = 1, IncludeGlob = 1, SlashIsDirectory = 1, SplitPolicy = 'whitespace', CComments = 0, UseApacheIfDefine = 1. Beside setting some options it also turns off support for explicit empty blocks.-NormalizeBlock => sub { my $x = shift; $x =~ s/\s*$//; $x; }. This removes trailing whitespaces of block names.Returns a hash structure which represents the whole config.
Returns a list of all files read in.
Writes the config hash back to the hard disk. This method takes one or two parameters. The first parameter must be the filename where the config should be written to. The second parameter is optional, it must be a reference to a hash structure, if you set it. If you do not supply this second parameter then the internal config hash, which has already been parsed, will be used.
Please note that any occurrence of comments will be ignored by getall() and thus be lost after you call this method.
You need also to know that named blocks will be converted to nested blocks (which is the same from the perl point of view). An example:
<user hans>
id 13
</user>
will become the following after saving:
<user>
<hans>
id 13
</hans>
</user>
Example:
$conf_obj->save_file("newrcfile", \%config);
or, if the config has already been parsed, or if it didn't change:
$conf_obj->save_file("newrcfile");
This method is equivalent to the previous save_file(), but it does not store the generated config to a file. Instead it returns it as a string, which you can save yourself afterwards.
It takes one optional parameter, which must be a reference to a hash structure. If you omit this parameter, the internal config hash, which has already been parsed, will be used.
Example:
my $content = $conf_obj->save_string(\%config);
or:
my $content = $conf_obj->save_string();
Lines beginning with # and empty lines will be ignored. (see section COMMENTS!) Spaces at the beginning and the end of a line will also be ignored as well as tabulators. If you need spaces at the end or the beginning of a value you can surround it with double quotes. An option line starts with its name followed by a value. An equal sign is optional. Some possible examples:
user max
user = max
user max
If there are more than one statements with the same name, it will create an array instead of a scalar. See the example below.
The method getall returns a hash of all values.
You can define a block of options. A block looks much like a block in the well-known Apache config format. It starts with ]]> and ends with ]]>.
A block start and end cannot be on the same line.
An example:
<database>
host = muli
user = moare
dbname = modb
dbpass = D4r_9Iu
</database>
Blocks can also be nested. Here is a more complicated example:
user = hans
server = mc200
db = maxis
passwd = D3rf$
<jonas>
user = tom
db = unknown
host = mila
<tablestructure>
index int(100000)
name char(100)
prename char(100)
city char(100)
status int(10)
allowed moses
allowed ingram
allowed joice
</tablestructure>
</jonas>
The hash which the method getall returns look like that:
print Data::Dumper(\%hash);
$VAR1 = {
'passwd' => 'D3rf$',
'jonas' => {
'tablestructure' => {
'prename' => 'char(100)',
'index' => 'int(100000)',
'city' => 'char(100)',
'name' => 'char(100)',
'status' => 'int(10)',
'allowed' => [
'moses',
'ingram',
'joice',
]
},
'host' => 'mila',
'db' => 'unknown',
'user' => 'tom'
},
'db' => 'maxis',
'server' => 'mc200',
'user' => 'hans'
};
If you have turned on -LowerCaseNames (see new()) then blocks as in the following example:
<Dir>
<AttriBUTES>
Owner root
</attributes>
</dir>
would produce the following hash structure:
$VAR1 = {
'dir' => {
'attributes' => {
'owner' => "root",
}
}
};
As you can see, the keys inside the config hash are normalized.
Please note, that the above config block would result in a valid hash structure, even if -LowerCaseNames is not set! This is because Config::General does not use the block names to check if a block ends, instead it uses an internal state counter, which indicates a block end.
If the module cannot find an end-block statement, then this block will be ignored.
If you need multiple blocks of the same name, then you have to name every block. This works much like Apache config. If the module finds a named block, it will create a hashref with the left part of the named block as the key containing one or more hashrefs with the right part of the block as key containing everything inside the block (which may again be nested!). As examples says more than words:
# given the following sample
<Directory /usr/frisco>
Limit Deny
Options ExecCgi Index
</Directory>
<Directory /usr/frik>
Limit DenyAll
Options None
</Directory>
# you will get:
$VAR1 = {
'Directory' => {
'/usr/frik' => {
'Options' => 'None',
'Limit' => 'DenyAll'
},
'/usr/frisco' => {
'Options' => 'ExecCgi Index',
'Limit' => 'Deny'
}
}
};
You cannot have more than one named block with the same name because it will be stored in a hashref and therefore be overwritten if a block occurs once more.
The normal behavior of Config::General is to look for whitespace in block names to decide if it's a named block or just a simple block.
Sometimes you may need blocknames which have whitespace in their names.
With named blocks this is no problem, as the module only looks for the first whitespace:
<person hugo gera>
</person>
would be parsed to:
$VAR1 = {
'person' => {
'hugo gera' => {
},
}
};
The problem occurs, if you want to have a simple block containing whitespace:
<hugo gera>
</hugo gera>
This would be parsed as a named block, which is not what you wanted. In this very case you may use quotation marks to indicate that it is not a named block:
<"hugo gera">
</"hugo gera">
The save() method of the module inserts automatically quotation marks in such cases.
Beside the notation of blocks mentioned above it is possible to use explicit empty blocks.
Normally you would write this in your config to define an empty block:
<driver Apache>
</driver>
To save writing you can also write:
<driver Apache/>
which is the very same as above. This works for normal blocks and for named blocks.
You may have more than one line of the same option with different values. Example:
log log1
log log2
log log2
You will get a scalar if the option occurred only once or an array if it occurred more than once. If you expect multiple identical options, then you may need to check if an option occurred more than once:
$allowed = $hash{jonas}->{tablestructure}->{allowed};
if (ref($allowed) eq "ARRAY") {
@ALLOWED = @{$allowed};
else {
@ALLOWED = ($allowed);
}
}
The same applies to blocks and named blocks too. For example, if you have the following config:
<dir blah>
user max
</dir>
<dir blah>
user hannes
</dir>
then you would end up with a data structure like this:
$VAR1 = {
'dir' => {
'blah' => [
{
'user' => 'max'
},
{
'user' => 'hannes'
}
]
}
};
As you can see, the two identical blocks are stored in a hash which contains an array(-reference) of hashes.
Under some rare conditions you might not want this behavior with blocks (and named blocks too). If you want to get one single hash with the contents of both identical blocks, then you need to turn the new() parameter -MergeDuplicateBlocks on (see above). The parsed structure of the example above would then look like this:
$VAR1 = {
'dir' => {
'blah' => {
'user' => [
'max',
'hannes'
]
}
}
};
As you can see, there is only one hash "dir->{blah}" containing multiple "user" entries. As you can also see, turning on -MergeDuplicateBlocks does not affect scalar options (i.e. "option = value"). In fact you can tune merging of duplicate blocks and options independent from each other.
If you don't want to allow more than one identical options, you may turn it off by setting the flag AllowMultiOptions in the new() method to "no". If turned off, Config::General will complain about multiple occurring options with identical names!
You may also force a single config line to get parsed into an array by turning on the option -ForceArray and by surrounding the value of the config entry by []. Example:
hostlist = [ foo.bar ]
Will be a single value array entry if the option is turned on. If you want it to remain to be an array you have to turn on -ForceArray during save too.
If you have a config value, which is too long and would take more than one line, you can break it into multiple lines by using the backslash character at the end of the line. The Config::General module will concatenate those lines to one single-value.
Example:
command = cat /var/log/secure/tripwire | \
mail -s "report from tripwire" \
honey AT myotherhost.nl
command will become: "cat /var/log/secure/tripwire | mail -s 'report from twire' honey AT myotherhost.nl"
You can also define a config value as a so called "here-document". You must tell the module an identifier which indicates the end of a here document. An identifier must follow a "<<".
Example:
message <<EOF
we want to
remove the
homedir of
root.
EOF
Everything between the two "EOF" strings will be in the option message.
There is a special feature which allows you to use indentation with here documents. You can have any amount of whitespace or tabulators in front of the end identifier. If the module finds spaces or tabs then it will remove exactly those amount of spaces from every line inside the here-document.
Example:
message <<EOF
we want to
remove the
homedir of
root.
EOF
After parsing, message will become:
we want to
remove the
homedir of
root.
because there were the string " " in front of EOF, which were cut from every line inside the here-document.
You can include an external file at any position in your config file using the following statement in your config file:
<<include externalconfig.rc>>
If you turned on -UseApacheInclude (see new()), then you can also use the following statement to include an external file:
include externalconfig.rc
This file will be inserted at the position where it was found as if the contents of this file were directly at this position.
You can also recursively include files, so an included file may include another one and so on. Beware that you do not recursively load the same file, you will end with an error message like "too many open files in system!".
By default included files with a relative pathname will be opened from within the current working directory. Under some circumstances it maybe possible to open included files from the directory, where the configfile resides. You need to turn on the option -IncludeRelative (see new()) if you want that. An example:
my $conf = Config::General(
-ConfigFile => "/etc/crypt.d/server.cfg"
-IncludeRelative => 1
);
/etc/crypt.d/server.cfg:
<<include acl.cfg>>
In this example Config::General will try to include acl.cfg from /etc/crypt.d:
/etc/crypt.d/acl.cfg
The default behavior (if -IncludeRelative is not set!) will be to open just acl.cfg, wherever it is, i.e. if you did a chdir("/usr/local/etc"), then Config::General will include:
/usr/local/etc/acl.cfg
Include statements can be case insensitive (added in version 1.25).
Include statements will be ignored within C-Comments and here-documents.
By default, a config file will only be included the first time it is referenced. If you wish to include a file in multiple places, set /-IncludeAgain to true. But be warned: this may lead to infinite loops, so make sure, you're not including the same file from within itself!
Example:
# main.cfg
<object billy>
class=Some::Class
<printers>
include printers.cfg
</printers>
# ...
</object>
<object bob>
class=Another::Class
<printers>
include printers.cfg
</printers>
# ...
</object>
Now "printers.cfg" will be included in both the "billy" and "bob" objects.
You will have to be careful to not recursively include a file. Behaviour in this case is undefined.
A comment starts with the number sign #, there can be any number of spaces and/or tab stops in front of the #.
A comment can also occur after a config statement. Example:
username = max # this is the comment
If you want to comment out a large block you can use C-style comments. A /* signals the begin of a comment block and the */ signals the end of the comment block. Example:
user = max # valid option
db = tothemax
/*
user = andors
db = toand
*/
In this example the second options of user and db will be ignored. Please beware of the fact, if the Module finds a /* string which is the start of a comment block, but no matching end block, it will ignore the whole rest of the config file!
NOTE: If you require the # character (number sign) to remain in the option value, then you can use a backslash in front of it, to escape it. Example:
bgcolor = \#ffffcc
In this example the value of $config{bgcolor} will be "#ffffcc", Config::General will not treat the number sign as the begin of a comment because of the leading backslash.
Inside here-documents escaping of number signs is NOT required!
You can alter the behavior of the parser by supplying closures which will be called on certain hooks during config file processing and parsing.
The general approach works like this:
sub ck {
my($file, $base) = @_;
print "_open() tries $file ... ";
if ($file =~ /blah/) {
print "ignored\n";
return (0);
} else {
print "allowed\n";
return (1, @_);
}
}
my %c = ParseConfig(
-IncludeGlob => 1,
-UseApacheInclude => 1,
-ConfigFile => shift,
-Plug => { pre_open => *ck }
);
Output:
_open() tries cfg ... allowed
_open() tries x/*.conf ... allowed
_open() tries x/1.conf ... allowed
_open() tries x/2.conf ... allowed
_open() tries x/blah.conf ... ignored
As you can see, we wrote a little sub which takes a filename and a base directory as parameters. We tell Config::General via the Plug parameter of new() to call this sub every time before it attempts to open a file.
General processing continues as usual if the first value of the returned array is true. The second value of that array depends on the kind of hook being called.
The following hooks are available so far:
Not implemented yet: hooks for variable interpolation and block parsing.
There is a way to access a parsed config the OO-way. Use the module Config::General::Extended, which is supplied with the Config::General distribution.
You can use variables inside your config files if you like. To do that you have to use the module Config::General::Interpolated, which is supplied with the Config::General distribution.
Config::General exports some functions too, which makes it somewhat easier to use it, if you like this.
How to import the functions:
use Config::General qw(ParseConfig SaveConfig SaveConfigString);
use Config::General qw(ParseConfig); my %config = ParseConfig(-ConfigFile => "rcfile", -AutoTrue => 1);use Config::General qw(SaveConfig); .. SaveConfig("rcfile", \%some_hash);use Config::General qw(ParseConfig SaveConfigString); my %config = ParseConfig(-ConfigFile => "rcfile"); .. # change %config something my $content = SaveConfigString(\%config);No environment variables will be used.
I recommend you to read the following documents, which are supplied with Perl:
Copyright (c) 2000-2016 Thomas Linden
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
See rt.cpan.org for current bugs, if any.
None known.
To debug Config::General use the Perl debugger, see perldebug.
Config::General depends on the modules FileHandle, File::Spec::Functions, File::Glob, which all are shipped with Perl.
Thomas Linden <tlinden |AT| cpan.org>
2.63
perl v5.22.2 2016-07-31 General(3pm)
Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-23 23:07 @216.73.216.102
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)