|
NAMEConfig::IniFiles - A module for reading .ini-style configuration files.VERSIONversion 3.000003SYNOPSISuse Config::IniFiles; my $cfg = Config::IniFiles->new( -file => "/path/configfile.ini" ); print "The value is " . $cfg->val( 'Section', 'Parameter' ) . "." if $cfg->val( 'Section', 'Parameter' ); DESCRIPTIONConfig::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 FORMATINI 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 InterfaceGet 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'); METHODSnew ( [-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:
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, ...])Assigns 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 fileReadConfigForces 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. SectionsReturns 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 exist, optionally including groupmembersCopySection ( $old_section_name, $new_section_name, $include_groupmembers)Copies one section to another optionally including groupmembersParameters ($sect_name)Returns an array containing the parameters contained in the specified section.GroupsReturns 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. RewriteConfigSame as WriteConfig, but specifies that the original configuration file should be rewritten.GetFileNameReturns 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 a delta. Also see OutputConfigToFileHandleSetSectionComment($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, $parameter)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, $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.DeleteDeletes the entire configuration file in memory.USAGE -- Tied Hashtie %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
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
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 FEATURESThe -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::errorsContains 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
Data StructureNote 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 ACKNOWLEDGEMENTSThe 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 Rö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). LICENSEThis 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. AUTHORShlomi Fish <shlomif@cpan.org>COPYRIGHT AND LICENSEThis 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. BUGSPlease 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. SUPPORTPerldocYou can find documentation for this module with the perldoc command.perldoc Config::IniFiles WebsitesThe 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.
Bugs / Feature RequestsPlease 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 CodeThe 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
Visit the GSP FreeBSD Man Page Interface. |