Config::IniFiles(3)

NAME
Config::IniFiles - A module for reading .ini-style configuration files.

SYNOPSIS
  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' );

DESCRIPTION
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.

FILE FORMAT
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=<<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

USAGE -- Object Interface
Get a new Config::IniFiles object with the new method:

  $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');

METHODS

  new ( [-option=>value ...] )
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:

      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.

-default section
    Specifies a section to be used for default values. For example, in the following configuration file, if you look up the "permissions" parameter in the "joe" section, there is none.

       [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 requsting 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"

-fallback section
    Specifies a section to be used for parameters outside a section. Default is none. Without -fallback specified (which is the default), reading a configuration file which has a parameter outside a section will fail. With this set to, say, "GENERAL", this configuration:

       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 outputing such configuration.

-nocase 0|1
    Set -nocase => 1 to handle the config file in a case-insensitive manner (case in values is preserved, however). By default, config files are case-sensitive (i.e., a section named 'Test' is not the same as a section named 'test'). Note that there is an added overhead for turning off case sensitivity.

-import object
    This allows you to import or inherit existing setting from another Config::IniFiles object. When importing settings from another object, sections with the same name will be merged and parameters that are defined in both the imported object and the -file will take the value of given in the -file.

    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.

-allowcontinue 0|1
    Set -allowcontinue => 1 to enable continuation lines in the config file. i.e. if a line ends with a backslash "\", then the following line is appended to the parameter value, dropping the backslash and the newline character(s).

    Default behavior is to keep a trailing backslash "\" as a parameter value. Note that continuation cannot be mixed with the "here" value syntax.

-allowempty 0|1
    If set to 1, then empty files are allowed at ReadConfig time. If set to 0 (the default), an empty configuration file is considered an error.

-negativedeltas 0|1
    If set to 1 (the default if importing this object from another one), parses and honors lines of the following form in the configuration file:

      ; [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.

-commentchar 'char'
    The default comment character is "#". You may change this by specifying this option to another character. This can be any character except alphanumeric characters, square brackets or the "equal" sign.

-allowedcommentchars 'chars'
    Allowed default comment characters are "#" and ";". By specifying this option you may change the range of characters that are used to denote a comment line to include any set of characters

    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.

-reloadwarn 0|1
    Set -reloadwarn => 1 to enable a warning message (output to STDERR) whenever the config file is reloaded. The reload message is of the form:

      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.

-nomultiline 0|1
    Set -nomultiline => 1 to output multi-valued parameter as:

     param=value1
     param=value2

    instead of the default:

     param=<<EOT
     value1
     value2
     EOT

    As the later might not be compatible with all applications.

-handle_trailing_comment 0|1
    Set -handle_trailing_comment => 1 to enable support of parameter trailing comments.

    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".

  val ($section, $parameter [, $default] )
Returns the value of the specified parameter ($parameter) in section $section, returns undef (or $default if specified) if no section or no parameter for the given section exists.

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.

  exists($section, $parameter)
True if and only if there exists a section $section, with a parameter $parameter inside, not counting default values.

  push ($section, $parameter, $value, [ $value2, ...])
Pushes new values at the end of existing value(s) of parameter $parameter in section $section. See below for methods to write the new configuration back out to a file.

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.

  setval ($section, $parameter, $value, [ $value2, ... ])
Sets the value of parameter $parameter in section $section to $value (or to a set of values). See below for methods to write the new configuration back out to a file.

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.

  newval($section, $parameter, $value [, $value2, ...])
Assignes a new value, $value (or set of values) to the parameter $parameter in section $section in the configuration file.

  delval($section, $parameter)
Deletes the specified parameter from the configuration file

  ReadConfig
Forces the configuration file to be re-read. Returns undef if the file can not be opened, no filename was defined (with the "-file" option) when the object was constructed, or an error occurred while reading.

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.

  Sections
Returns an array containing section names in the configuration file. If the nocase option was turned on when the config object was created, the section names will be returned in lowercase.

  SectionExists ( $sect_name )
Returns 1 if the specified section exists in the INI file, 0 otherwise (undefined if section_name is not defined).

  AddSection ( $sect_name )
Ensures that the named section exists in the INI file. If the section already exists, nothing is done. In this case, the "new" section will possibly contain data already.

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.

  DeleteSection ( $sect_name )
Completely removes the entire section from the configuration.

  RenameSection ( $old_section_name, $new_section_name, $include_groupmembers)
Renames a section if it does not already exists optionally including groupmembers

  CopySection ( $old_section_name, $new_section_name, $include_groupmembers)
Copies one section to another optionally including groupmembers

  Parameters ($sect_name)
Returns an array containing the parameters contained in the specified section.

  Groups
Returns an array containing the names of available groups.

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.

  SetGroupMember ( $sect )
Makes sure that the specified section is a member of the appropriate group.

Only intended for use in newval.

  RemoveGroupMember ( $sect )
Makes sure that the specified section is no longer a member of the appropriate group. Only intended for use in DeleteSection.

  GroupMembers ($group)
Returns an array containing the members of specified $group. Each element of the array is a section name. For example, given the sections

  [Group Element 1]
  ...

  [Group Element 2]
  ...

GroupMembers would return ("Group Element 1", "Group Element 2").

  SetWriteMode ($mode)
Sets the mode (permissions) to use when writing the INI file.

$mode must be a string representation of the octal mode.

  GetWriteMode ($mode)
Gets the current mode (permissions) to use when writing the INI file.

$mode is a string representation of the octal mode.

  WriteConfig ($filename [, %options])
Writes out a new copy of the configuration file. A temporary file is written out and then renamed to the specified filename. Also see BUGS below.

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.

  RewriteConfig
Same as WriteConfig, but specifies that the original configuration file should be rewritten.

  GetFileName
Returns the filename associated with this INI file.

If no filename has been specified, returns undef.

  SetFileName ($filename)
If you created the Config::IniFiles object without initialising from a file, or if you just want to change the name of the file to use for ReadConfig/RewriteConfig from now on, use this method.

Returns $filename if that was a valid name, undef otherwise.

  $ini->OutputConfigToFileHandle($fh, $delta)
Writes OutputConfig to the $fh filehandle. $delta should be set to 1 1 if writing only delta. This is a newer and safer version of "OutputConfig()" and one is encouraged to use it instead.

  $ini->OutputConfig($delta)
Writes OutputConfig to STDOUT. Use select() to redirect STDOUT to the output target before calling this function. Optional argument should be set to 1 if writing only delta. Also see OutputConfigToFileHandle

  SetSectionComment($section, @comment)
Sets the comment for section $section to the lines contained in @comment.

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)

  GetSectionComment ($section)
Returns a list of lines, being the comment attached to section $section. In scalar context, returns a string containing the lines of the comment separated by newlines.

The lines are presented as-is, with whatever comment character was originally used on that line.

  DeleteSectionComment ($section)
Removes the comment for the specified section.

  SetParameterComment ($section, $parameter, @comment)
Sets the comment attached to a particular parameter.

Any line of @comment that does not have a comment character will be prepended with one. See "SetSectionComment($section, @comment)" above

  GetParameterComment ($section, $parameter)
Gets the comment attached to a parameter. In list context returns all comments - in scalar context returns them joined by newlines.

  DeleteParameterComment ($section, $parmeter)
Deletes the comment attached to a parameter.

  GetParameterEOT ($section, $parameter)
Accessor method for the EOT text (in fact, style) of the specified parameter. If any text is used as an EOT mark, this will be returned. If the parameter was not recorded using HERE style multiple lines, GetParameterEOT returns undef.

  $cfg->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, $parmeter)
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 no comment for it. otherwise, undef will be returned.

  Delete
Deletes the entire configuration file in memory.

USAGE -- Tied Hash

  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 multiv-alue 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=overriden

Then "$overlay->val("section1", "arg1")" is "overriden", 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
          ->{firstload} = 0 OR 1
          ->{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 RXpke, 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).

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.