***** infoCopter.com/perl *****

CPAN Config::IniFiles

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

#!/usr/bin/perl -w

use Config::IniFiles;

my $cfg = Config::IniFiles->new( -file => 'configini.ini' );

my $log_suffix = $cfg->val('log', 'suffix');
my $foo_foo = $cfg->val('foo', 'foo');

print "[log] suffix = \"$log_suffix\"\n";
print "[foo] foo = \"$foo_foo\"\n";

Input Config File

Both the hash mark (#) and the semicolon (;) are comment characters.

$ cat configini.ini

[log]
suffix = .log

[foo]
foo = bar

Output

$ ./configini.pl

[log] suffix = ".log"
[foo] foo = "bar"


Tips

Get all sections from you ini file

my @all_sections = $cfg->Sections();

foreach (@all_sections) {
        print "$_\n";
}

Or shorter

foreach (sort $cfg->Sections) {
        print "$_\n";
}

Fill all keys from a section into an array

my @values = $cfg->Parameters('yourSection');

Loop sorted through all sections plus print its parameters and values

foreach my $section (sort $cfg->Sections) {
	next unless $section =~ /^test_\d+/;
	print "$section:\n";
	my @values = $cfg->Parameters($section);
	foreach (@values) {
		print "--> $_ = ", $cfg->val($section, $_), "\n";
	}
}


Related Links

  1. perl/config-files.htm (Perl)
    http://www.infocopter.com/perl/config-files.htm
    CPAN Config::IniFiles

  2. perl/simple-config.htm (Perl)
    http://www.infocopter.com/perl/simple-config.htm
    Simple Configuration Processing

© reto :)