Config::General - Generic Config Module
# # the OOP way use Config::General; $conf = new Config::General("rcfile"); my %config = $conf->getall;
# # the procedural way use Config::General; my %config = ParseConfig("rcfile");
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.
$conf = new Config::General("rcfile");
$conf = new Config::General(\%somehash);
$conf = new Config::General( %options ); # see below for description of possible options
This method returns a Config::General object (a hash blessed into ``Config::General'' namespace. All further methods must be used from that returned object. see below.
You can use the new style with hash parameters or the old style which is of course still supported. Possible parameters to new() are:
* a filename of a configfile, which will be opened and parsed by the parser
or
* a hash reference, which will be used as the config.
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 => "no"
see IDENTICAL OPTIONS for details.
If the variable -ConfigPath has been set and if the file to be included could not be found in the location relative to the current config file, the module will search within -ConfigPath for the file. See the description of -ConfigPath for more details.
You must specify the path as an array ref. For example:
@path = qw(/usr/lib/perl /nfs/apps/lib /home/lib); .. -ConfigPath => \@path
Setting this option implies -AllowMultiOptions == false unless you set -AllowMultiOptions explicit to 'true'. In this case duplicate blocks are allowed and put into an array but dupclicate options will be merged.
The following values will be considered as true:
yes, 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 ``oN'' will result in 1.
The supplied hash reference needs to define variables for which you want to preset values. Each variable you have defined in this hash-ref and which occurs in your config file, will cause this variable being set to the preset values to which the value in the config file refers to.
Multiple flags can be used, separated by the pipe character |.
Well, an example will clarify things:
my $conf = new Config::General( -ConfigFile => "rcfile", -FlagBits => { Mode => { CLEAR => 1, STRONG => 1, UNSECURE => "32bit" } } );
In this example we are defining a variable named ``Mode'' which may contain one or more of ``CLEAR'', ``STRONG'' and ``UNSECURE'' as value.
The appropriate config entry may look like this:
# rcfile Mode = CLEAR | UNSECURE
The parser will create a hash which will be the value of the key ``Mode''. This hash will contain all flags which you have pre-defined, but only those which were set in the config will contain the pre-defined value, the other ones will be undefined.
The resulting config structure would look like this after parsing:
%config = ( Mode => { CLEAR => 1, UNSECURE => "32bit", STRONG => undef, } );
This method allows the user (or, the ``maintainer'' of the configfile for your application) to set multiple pre-defined values for one option.
Please beware, that all occurencies of those variables will be handled this way, there is no way to distinguish between variables in different scopes. That means, if ``Mode'' would also occur inside a named block, it would also parsed this way.
Values which are not defined in the hash-ref supplied to the parameter -FlagBits and used in the corresponding variable in the config will be ignored.
Example:
# rcfile Mode = BLAH | CLEAR
would result in this hash structure:
%config = ( Mode => { CLEAR => 1, UNSECURE => undef, STRONG => undef, } );
``BLAH'' will be ignored silently.
This hash will be used as the 'backing hash' instead of a standard perl hash, which allows you to affect the way, variable storing will be done. You could, for example supply a tied hash, say Tie::DxHash, which preserves ordering of the keys in the config (which a standard perl hash won't do). Or, you could supply a hash tied to a DBM file to save the parsed variables to disk.
There are many more things to do in tie-land, see tie to get some interesting ideas.
If you want to use the -Tie feature together with -DefaultConfig make sure that the hash supplied to -DefaultConfig must be tied to the same Tie class.
Make sure that the hash which receives the generated hash structure (e.g. which you are using in the assignment: %hash = $config->getall()) must be tied to the same Tie class.
Example:
use Config::General; use Tie::IxHash; tie my %hash, "Tie::IxHash"; %hash = ParseConfig( -ConfigFile => shift(), -Tie => "Tie::IxHash" );
However, somtimes you may wish to make it more strictly for some reason. In this case you can set -SplitPolicy. The possible values are: 'guess' which is the default, 'whitespace' which causes the module to split by whitespace, 'equalsign' which causes it to split strictly by equal sign, or 'custom'. In the latter case you must also set -SplitDelimiter to some regular expression of your choice. For example:
-SplitDelimiter => '\s*:\s*'
will cause the module to split by colon while whitespaces which surrounds the delimiter will be removed.
Please note that the delimiter used when saving a config (save_file() or save_string()) will be choosen accordingto the current -SplitPolicy. If -SplitPolicy is set to 'guess' or 'whitespace', 3 whitespaces will be used to delimit saved options. If 'custom' is set, then you need to set -StoreDelimiter.
Be very carefull with this parameter.
By default -CComments is turned on.
Please note, that any occurence 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");
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();
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.
<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 blocknames 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.
# 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.
Example:
log log1
log log2
log log2
You will get a scalar if the option occured only once or an array if it occured more than once. If you expect multiple identical options, then you may need to check if an option occured 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 (they are described in more detail below). 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', 'user' => '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 occuring options with identical names!
Example:
command = cat /var/log/secure/tripwire | \
mail "-s" ``report from tripwire'' \
honey@myotherhost.nl
command will become:
"cat /var/log/secure/tripwire | mail "-s" 'report from twire' honey@myotherhost.nl"
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 whitespaces 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 cutted from every line inside the here-document.
<<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 recurively 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 errormessage 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, whereever 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.
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 backlsash 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!
Example:
use Config::General; my %config = ParseConfig(-ConfigFile => "rcfile", -AutoTrue => 1);
Example:
use Config::General; .. SaveConfig("rcfile", \%some_hash);
Example:
use Config::General; my %config = ParseConfig(-ConfigFile => "rcfile"); .. # change %config something my $content = SaveConfigString(\%config);
perlreftut Perl references short introduction perlref Perl references, the rest of the story perldsc Perl data structures intro perllol Perl data structures: arrays of arrays
Config::General::Extended Object oriented interface to parsed configs Config::General::Interpolated Allows to use variables inside config files
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |