use Config::IniFiles; my $cfg = Config::IniFiles->new( -file => "/path/configfile.ini" ); print "The value is " . $cfg->val( 'Section', 'Parameter' ) . "." if $cfg->val( 'Section', 'Parameter' );
[a section] Parameter=Value [section 2] AnotherParameter=Some value Setting=Something else Parameter=Different scope than the one in the first section
The first non-blank character of the line indicating a section must be a left bracket and the last non-blank character of a line indicating a section must be a right bracket. The characters making up the section name can be any symbols at all. However section names must be unique.
Parameters are specified in each section as Name=Value. Any spaces around the equals sign will be ignored, and the value extends to the end of the line (including any whitespace at the end of the line. Parameter names are localized to the namespace of the section, but must be unique within a section.
Both the hash mark (#) and the semicolon (;) are comment characters. by default (this can be changed by configuration). Lines that begin with either of these characters will be ignored. Any amount of whitespace may precede the comment character.
Multi-line or multi-valued parameters may also be defined ala UNIX ``here document'' syntax:
Parameter=<<EOT value/line 1 value/line 2 EOT
You may use any string you want in place of ``EOT''. Note that whatever follows the ``<<'' and what appears at the end of the text MUST match exactly, including any trailing whitespace.
Alternately, as a configuration option (default is off), continuation lines can be allowed:
[Section] Parameter=this parameter \ spreads across \ a few lines
$cfg = Config::IniFiles->new( -file => "/path/config_file.ini" ); $cfg = new Config::IniFiles -file => "/path/config_file.ini";
Optional named parameters may be specified after the configuration file name. See the new in the METHODS section, below.
Values from the config file are fetched with the val method:
$value = $cfg->val('Section', 'Parameter');
If you want a multi-line/value field returned as an array, just specify an array as the receiver:
@values = $cfg->val('Section', 'Parameter');
1) the pathname of a file $cfg = Config::IniFiles->new( -file => "/path/to/config_file.ini" ); 2) a simple filehandle $cfg = Config::IniFiles->new( -file => STDIN ); 3) a filehandle glob open( CONFIG, "/path/to/config_file.ini" ); $cfg = Config::IniFiles->new( -file => *CONFIG ); 4) a reference to a glob open( CONFIG, "/path/to/config_file.ini" ); $cfg = Config::IniFiles->new( -file => \*CONFIG ); 5) an IO::File object $io = IO::File->new( "/path/to/config_file.ini" ); $cfg = Config::IniFiles->new( -file => $io ); or open my $fh, '<', "/path/to/config_file.ini" or die $!; $cfg = Config::IniFiles->new( -file => $fh ); 6) A reference to a scalar (requires newer versions of IO::Scalar) $ini_file_contents = <<EOT [section name] Parameter=A value Setting=Another value EOT $cfg = Config::IniFiles->new( -file => \$ini_file_contents );
If this option is not specified, (i.e. you are creating a config file from scratch) you must specify a target file using SetFileName in order to save the parameters.
[all] permissions=Nothing [jane] name=Jane permissions=Open files [joe] name=Joseph
If you create your Config::IniFiles object with a default section of ``all'' like this:
$cfg = Config::IniFiles->new( -file => "file.ini", -default => "all" );
Then requesting a value for a ``permissions'' in the [joe] section will check for a value from [all] before returning undef.
$permissions = $cfg->val( "joe", "permissions"); // returns "Nothing"
wrong=wronger [joe] name=Joseph
will be assumed as:
[GENERAL] wrong=wronger [joe] name=Joseph
Note that Config::IniFiles will also omit the fallback section header when outputting such configuration.
If a -default section is also given on this call, and it does not coincide with the default of the imported object, the new default section will be used instead. If no -default section is given, then the default of the imported object will be used.
Default behavior is to keep a trailing backslash "\" as a parameter value. Note that continuation cannot be mixed with the ``here'' value syntax.
; [somesection] is deleted
or
[inthissection] ; thisparameter is deleted
If set to 0 (the default if not importing), these comments are treated like ordinary ones.
The WriteConfig1)> form will output such comments to indicate deleted sections or parameters. This way, reloading a delta file using the same imported object produces the same results in memory again. See `` DELTA FEATURES'' in IMPORT for more details.
Note: that the character specified by -commentchar (see above) is always part of the allowed comment characters.
Note 2: The given string is evaluated as a regular expression character class, so '\' must be escaped if you wish to use it.
PID <PID> reloading config file <file> at YYYY.MM.DD HH:MM:SS
Default behavior is to not warn (i.e. -reloadwarn => 0).
This is generally only useful when using Config::IniFiles in a server or daemon application. The application is still responsible for determining when the object is to be reloaded.
param=value1 param=value2
instead of the default:
param=<<EOT value1 value2 EOT
As the latter might not be compatible with all applications.
For example, if we have a parameter line like this:
param1=value1;comment1
by default, handle_trailing_comment will be set to 0, and we will get value1;comment1 as the value of param1. If we have -handle_trailing_comment set to 1, then we will get value1 as the value for param1, and comment1 as the trailing comment of param1.
Set and get methods for trailing comments are provided as ``SetParameterTrailingComment'' and ``GetParameterTrailingComment''.
The differences between parse_ini_file and Config::IniFiles are:
# parse_ini_file [group] val1="value" val2[]=1 val2[]=2 vs # Config::IniFiles [group] val1=value val2=1 val2=2
This option only affect parsing, not writing new configfiles.
Some features from parse_ini_file are not compatible:
[group] val1="val"'ue' val1[key]=1
If you want a multi-line/value field returned as an array, just specify an array as the receiver:
@values = $cfg->val('Section', 'Parameter');
A multi-line/value field that is returned in a scalar context will be joined using $/ (input record separator, default is \n) if defined, otherwise the values will be joined using \n.
You may not set a parameter that didn't exist in the original configuration file. push will return undef if this is attempted. See newval below to do this. Otherwise, it returns 1.
You may not set a parameter that didn't exist in the original configuration file. setval will return undef if this is attempted. See newval below to do this. Otherwise, it returns 1.
If an error occurs while parsing the INI file the @Config::IniFiles::errors array will contain messages that might help you figure out where the problem is in the file.
If you really need to have a new section with no parameters in it, check that the name that you're adding isn't in the list of sections already.
Groups are specified in the config file as new sections of the form
[GroupName MemberName]
This is useful for building up lists. Note that parameters within a ``member'' section are referenced normally (i.e., the section name is still ``Groupname Membername'', including the space) - the concept of Groups is to aid people building more complex configuration files.
Only intended for use in newval.
[Group Element 1] ... [Group Element 2] ...
GroupMembers would return (``Group Element 1'', ``Group Element 2'').
$mode must be a string representation of the octal mode.
$mode is a string representation of the octal mode.
If "-delta" is set to a true value in %options, and this object was imported from another (see ``new''), only the differences between this object and the imported one will be recorded. Negative deltas will be encoded into comments, so that a subsequent invocation of new() with the same imported object produces the same results (see the -negativedeltas option in ``new'').
%options is not required.
Returns true on success, "undef" on failure.
If no filename has been specified, returns undef.
Returns $filename if that was a valid name, undef otherwise.
Each comment line will be prepended with the comment character (default is "#") if it doesn't already have a comment character (ie: if the line does not start with whitespace followed by an allowed comment character, default is "#" and ";").
To clear a section comment, use DeleteSectionComment ($section)
The lines are presented as-is, with whatever comment character was originally used on that line.
Any line of @comment that does not have a comment character will be prepended with one. See ``SetSectionComment($section, @comment)'' above
To un-set the EOT text, use DeleteParameterEOT ($section, $parameter).
If there is a new parameter trailing comment to be added, the value should be added first.
Here's an example:
use Config::IniFiles; my %ini; tie %ini, 'Config::IniFiles', ( -file => "/path/configfile.ini" ); print "We have $ini{Section}{Parameter}." if $ini{Section}{Parameter};
Accessing and using the hash works just like accessing a regular hash and many of the object methods are made available through the hash interface.
For those methods that do not coincide with the hash paradigm, you can use the Perl "tied" function to get at the underlying object tied to the hash and call methods on that object. For example, to write the hash out to a new ini file, you would do something like this:
tied( %ini )->WriteConfig( "/newpath/newconfig.ini" ) || die "Could not write settings to new file.";
Multiline values accessed through a hash will be returned as a list in list context and a concatenated value in scalar context.
To set a multiline or multi-value parameter just assign an array reference to the hash entry, like this:
$ini{$section}{$parameter} = [$value1, $value2, ...];
If the parameter did not exist in the original file, it will be created. However, Perl does not seem to extend autovivification to tied hashes. That means that if you try to say
$ini{new_section}{new_paramters} = $val;
and the section 'new_section' does not exist, then Perl won't properly create it. In order to work around this you will need to create a hash reference in that section and then assign the parameter value. Something like this should do nicely:
$ini{new_section} = {}; $ini{new_section}{new_paramters} = $val;
When tied to a hash, you use the Perl "keys" and "each" functions to iteratively list the parameters ("keys") or parameters and their values ("each") in a given section.
You can also use the Perl "exists" function to see if a parameter is defined in a given section.
Note that none of these will return parameter names that are part of the default section (if set), although accessing an unknown parameter in the specified section will return a value from the default section if there is one.
When tied to a hash, you use the Perl "keys" and "each" functions to iteratively list the sections in the ini file.
You can also use the Perl "exists" function to see if a section is defined in the file.
my $master = Config::IniFiles->new(-file => "master.ini"); my $overlay = Config::IniFiles->new(-file => "overlay.ini", -import => $master);
If the contents of "master.ini" and "overlay.ini" are respectively
; master.ini [section1] arg0=unchanged from master.ini arg1=val1 [section2] arg2=val2
and
; overlay.ini [section1] arg1=overridden
Then "$overlay->val("section1", "arg1")" is ``overridden'', while "$overlay->val("section1", "arg0")" is ``unchanged from master.ini''.
This feature may be used to ship a ``global defaults'' configuration file for a Perl application, that can be overridden piecewise by a much shorter, per-site configuration file. Assuming UNIX-style path names, this would be done like this:
my $defaultconfig = Config::IniFiles->new (-file => "/usr/share/myapp/myapp.ini.default"); my $config = Config::IniFiles->new (-file => "/etc/myapp.ini", -import => $defaultconfig); # Now use $config and forget about $defaultconfig in the rest of # the program
Starting with version 2.39, Config::IniFiles also provides features to keep the importing / per-site configuration file small, by only saving those options that were modified by the running program. That is, if one calls
$overlay->setval("section1", "arg1", "anotherval"); $overlay->newval("section3", "arg3", "val3"); $overlay->WriteConfig('overlay.ini', -delta=>1);
"overlay.ini" would now contain
; overlay.ini [section1] arg1=anotherval [section3] arg3=val3
This is called a delta file (see ``WriteConfig''). The untouched [section2] and arg0 do not appear, and the config file is therefore shorter; while of course, reloading the configuration into $master and $overlay, either through "$overlay->ReadConfig()" or through the same code as above (e.g. when application restarts), would yield exactly the same result had the overlay object been saved in whole to the file system.
The only problem with this delta technique is one cannot delete the default values in the overlay configuration file, only change them. This is solved by a file format extension, enabled by the -negativedeltas option to ``new'': if, say, one would delete parameters like this,
$overlay->DeleteSection("section2"); $overlay->delval("section1", "arg0"); $overlay->WriteConfig('overlay.ini', -delta=>1);
The overlay.ini file would now read:
; overlay.ini [section1] ; arg0 is deleted arg1=anotherval ; [section2] is deleted [section3] arg3=val3
Assuming $overlay was later re-read with "-negativedeltas => 1", the parser would interpret the deletion comments to yield the correct result, that is, [section2] and arg0 would cease to exist in the $overlay object.
$iniconf->{cf} = "config_file_name" ->{startup_settings} = \%orginal_object_parameters ->{imported} = $object WHERE $object->isa("Config::IniFiles") ->{nocase} = 0 ->{reloadwarn} = 0 ->{sects} = \@sections ->{mysects} = \@sections ->{sCMT}{$sect} = \@comment_lines ->{group}{$group} = \@group_members ->{parms}{$sect} = \@section_parms ->{myparms}{$sect} = \@section_parms ->{EOT}{$sect}{$parm} = "end of text string" ->{pCMT}{$sect}{$parm} = \@comment_lines ->{v}{$sect}{$parm} = $value OR \@values ->{e}{$sect} = 1 OR does not exist ->{mye}{$sect} = 1 OR does not exists
In particular, special thanks go to (in roughly chronological order):
Bernie Cosell, Alan Young, Alex Satrapa, Mike Blazer, Wilbert van de Pieterman, Steve Campbell, Robert Konigsberg, Scott Dellinger, R. Bernstein, Daniel Winkelmann, Pires Claudio, Adrian Phillips, Marek Rouchal, Luc St Louis, Adam Fischler, Kay Ro.pke, Matt Wilson, Raviraj Murdeshwar and Slaven Rezic, Florian Pfaff
Geez, that's a lot of people. And apologies to the folks who were missed.
If you want someone to bug about this, that would be:
Shlomi Fish <shlomif@cpan.org>
If you want more information, or want to participate, go to:
<http://sourceforge.net/projects/config-inifiles/>
Please submit bug reports using the Request Tracker interface at <https://rt.cpan.org/Public/Dist/Display.html?Name=Config-IniFiles> .
Development discussion occurs on the mailing list config-inifiles-dev@lists.sourceforge.net, which you can subscribe to by going to the project web site (link above).
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature.
perldoc Config::IniFiles
A modern, open-source CPAN search engine, useful to view POD in HTML format.
The default CPAN search engine, useful to view POD in HTML format.
The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.
<https://rt.cpan.org/Public/Dist/Display.html?Name=Config-IniFiles>
The AnnoCPAN is a website that allows community annotations of Perl module documentation.
The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.
The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.
The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
<https://github.com/shlomif/perl-Config-IniFiles>
git clone git://github.com/shlomif/perl-Config-IniFiles.git