Config::IniFiles - A module for reading .ini-style configuration files.
| Use Case | Command | Description |
|---|---|---|
| Create object from file | $cfg = Config::IniFiles->new( -file => "/path/config.ini" ) | Load INI configuration |
| Fetch a single value | $value = $cfg->val('Section', 'Parameter') | Get parameter value |
| Fetch multi-line as array | @values = $cfg->val('Section', 'Parameter') | Retrieve multi-value setting |
| Write config to file | $cfg->WriteConfig('/path/config.ini') | Save changes |
| Tied hash interface | tie %ini, 'Config::IniFiles', ( -file => "config.ini" ); $ini{Section}{Param} | Hash-style access |
| Set existing value | $cfg->setval('Section', 'Parameter', 'newval') | Change a parameter |
| Create new parameter | $cfg->newval('Section', 'Parameter', 'value') | Add new entry |
| Delete parameter | $cfg->delval('Section', 'Parameter') | Remove parameter |
| List sections | @sections = $cfg->Sections | Get all section names |
| Reload configuration | $cfg->ReadConfig | Re-read the file |
| Import (inherit) settings | $cfg = Config::IniFiles->new( -file => "overlay.ini", -import => $master ) | Stack configurations |
version 3.000003
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' );
Config::IniFiles provides a way to have readable configuration files outside your Perl script. Configurations can be imported (inherited, stacked,...), sections can be grouped, and settings can be accessed from a tied hash.
INI files consist of a number of sections, each preceded with the section name in square brackets, followed by parameter names and their values.
[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= "/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');
Returns a new configuration object (or "undef" if the configuration file has an error, in which case check the global @Config::IniFiles::errors array for reasons why). One Config::IniFiles object is required per configuration file. The following named parameters are available:
-file filename
Specifies a file to load the parameters from. This 'file' may actually be any of the following things:
$cfg = Config::IniFiles->new( -file => "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => STDIN );
open( CONFIG, "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => *CONFIG );
open( CONFIG, "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => \*CONFIG );
$io = IO::File->new( "/path/to/config_file.ini" );
$cfg = Config::IniFiles->new( -file => $io );
or
open my $fh, 'SetParameterEOT ($section, $parameter, $EOT)
Accessor method for the EOT text for the specified parameter. Sets the HERE style marker text to the value $EOT. Once the EOT text is set, that parameter will be saved in HERE style.
To un-set the EOT text, use DeleteParameterEOT ($section, $parameter).
DeleteParameterEOT ($section, $parameter)
Removes the EOT marker for the given section and parameter. When writing a configuration file, if no EOT marker is defined then "EOT" is used.
SetParameterTrailingComment ($section, $parameter, $cmt)
Set the end trailing comment for the given section and parameter. If there is a old comment for the parameter, it will be overwritten by the new one.
If there is a new parameter trailing comment to be added, the value should be added first.
GetParameterTrailingComment ($section, $parameter)
An accessor method to read the trailing comment after the parameter. The trailing comment will be returned if there is one. A null string will be returned if the parameter exists but there is no comment for it. otherwise, undef will be returned.
Delete
Deletes the entire configuration file in memory.
Tied Hash Interface
tie %ini, 'Config::IniFiles', (-file=>$filename, [-option=>value ...] )
Using "tie", you can tie a hash to a Config::IniFiles object. This creates a new object which you can access through your hash, so you use this instead of the new method. This actually creates a hash of hashes to access the values in the INI file. The options you provide through "tie" are the same as given for the new method, above.
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.";
$val = $ini{$section}{$parameter}
Returns the value of $parameter in $section.
Multiline values accessed through a hash will be returned as a list in list context and a concatenated value in scalar context.
$ini{$section}{$parameter} = $value;
Sets the value of $parameter in $section to $value.
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;
%hash = %{$ini{$section}}
Using the tie interface, you can copy whole sections of the ini file into another hash. Note that this makes a copy of the entire section. The new hash in no longer tied to the ini file, In particular, this means -default and -nocase settings will not apply to %hash.
$ini{$section} = {}; %{$ini{$section}} = %parameters;
Through the hash interface, you have the ability to replace the entire section with a new set of parameters. This call will fail, however, if the argument passed in NOT a hash reference. You must use both lines, as shown above so that Perl recognizes the section as a hash reference context before COPYing over the values from your %parameters hash.
delete $ini{$section}{$parameter}
When tied to a hash, you can use the Perl "delete" function to completely remove a parameter from a section.
delete $ini{$section}
The tied interface also allows you to delete an entire section from the ini file using the Perl "delete" function.
%ini = ();
If you really want to delete all the items in the ini file, this will do it. Of course, the changes won't be written to the actual file unless you call RewriteConfig on the object tied to the hash.
Parameter names
my @keys = keys %{$ini{$section}}
while (($k, $v) = each %{$ini{$section}}) {...}
if( exists %{$ini{$section}}, $parameter ) {...}
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.
Section names
foreach( keys %ini ) {...}
while (($k, $v) = each %ini) {...}
if( exists %ini, $section ) {...}
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.
đ IMPORT / DELTA FEATURES
The -import option to "new" allows one to stack one Config::IniFiles object on top of another (which might be itself stacked in turn and so on recursively, but this is beyond the point). The effect, as briefly explained in "new", is that the fields appearing in the composite object will be a superposition of those coming from the ``original'' one and the lines coming from the file, the latter taking precedence. For example, let's say that $master and "overlay" were created like this:
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.
đ DIAGNOSTICS
@Config::IniFiles::errors
Contains a list of errors encountered while parsing the configuration file. If the new method returns undef, check the value of this to find out what's wrong. This value is reset each time a config file is read.
đ BUGS
- The output from [Re]WriteConfig/OutputConfig might not be as pretty as it can be. Comments are tied to whatever was immediately below them. And case is not preserved for Section and Parameter names if the -nocase option was used.
- No locking is done by [Re]WriteConfig. When writing servers, take care that only the parent ever calls this, and consider making your own backup.
đī¸ Data Structure
Note that this is only a reference for the package maintainers - one of the upcoming revisions to this package will include a total clean up of the data structure.
$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
đ AUTHOR and ACKNOWLEDGEMENTS
The original code was written by Scott Hutton. Then handled for a time by Rich Bowen (thanks!), and was later managed by Jeremy Wadsack (thanks!), and now is managed by Shlomi Fish (http://www.shlomifish.org/) with many contributions from various other people.
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 Roepke, 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
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 AT lists.net, which you can subscribe to by going to the project web site (link above).
âī¸ LICENSE
This software is copyright (c) 2000 by Scott Hutton and the rest of the Config::IniFiles contributors.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
âī¸ AUTHOR
Shlomi Fish
ÂŠī¸ COPYRIGHT AND LICENSE
This software is copyright (c) 2000 by RBOW and others.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
đ BUGS (Report)
Please report any bugs or feature requests on the bugtracker website https://github.com/shlomif/perl-Config-IniFiles/issues
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.
đ SUPPORT
đ Perldoc
You can find documentation for this module with the perldoc command.
perldoc Config::IniFiles
đ Websites
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
- MetaCPAN
A modern, open-source CPAN search engine, useful to view POD in HTML format.
https://metacpan.org/release/Config-IniFiles
- RT: CPAN's Bug Tracker
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
- CPANTS
The CPANTS is a website that analyzes the Kwalitee (code metrics) of a distribution.
http://cpants.cpanauthors.org/dist/Config-IniFiles
- CPAN Testers
The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.
http://www.cpantesters.org/distro/C/Config-IniFiles
- CPAN Testers Matrix
The CPAN Testers Matrix provides a visual overview of test results on various Perls/platforms.
http://matrix.cpantesters.org/?dist=Config-IniFiles
- CPAN Testers Dependencies
A chart of test results of all dependencies.
http://deps.cpantesters.org/?module=Config::IniFiles
đ Bugs / Feature Requests
Please report any bugs or feature requests by email to bug-config-inifiles at rt.cpan.org, or through the web interface at https://rt.cpan.org/Public/Bug/Report.html?Queue=Config-IniFiles. You will be automatically notified of any progress on the request by the system.
đ Source Code
The code is open to the world, and available for you to hack on. Please feel free to browse it and play with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull from your repository :)
https://github.com/shlomif/perl-Config-IniFiles
git clone git://github.com/shlomif/perl-Config-IniFiles.git
Generated by phpman v4.9.26-5-g7740029 Author: Che Dong Under GNU General Public License
2026-08-25 07:23 @216.73.217.127
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)