The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Config::Simple - Perl extension for reading and writing configuration files

SYNOPSIS

  use Config::Simple;
  my $cfg = new Config::Simple(_filename=>'/home/sherzodr/lib/Poll.cfg');
  print "Your mysql password is: ", $cfg->param('mysql.password'), "\n";
  print "Your mysql login is: ", $cfg->param('mysql.login'), "\n";

  # modifying parameters:

  $cfg->set_param('mysql.password', 'new_password');

  print "Now your new password is ", $cfg->param("mysql.password"), "\n";

  # now writing all the modifications back to the configuration file:

  $cfg->write;

  # now creating a copy of the configuration file, instead of
  # writing it back to the same file:

  $cfg->write('new_file.cfg.bk');

DESCRIPTION

Config::Simple is used for reading and writing configuration files in the following format:

    [mysql]
    host=ultracgis.com
    login=sherzodr
    password=secret

    [site]
    admin=Sherzod B. Ruzmetov
    admin_email=sherzodr@cpan.org
    url=http://www.ultracgis.com

You could also use this module to creat brand new configuration files. If the file you pass to new() does not exist, it will create the file. If you want to create the section called '[author]' in the configuration file with two attributes, 'first name' and 'last name', the following trick would work:

    my $cfg = new Config::Simple(_filename=>'MyConfig.cfg');
    $cfg->set_param('author.first name', 'Sherzod');
    $cfg->set_param('author.last name', 'Ruzmetov');

    $cfg->write;

MyConfig.cfg file looks like the following:

    [author]
    first name=Sherzod
    last name=Ruzmetov

If you want to get all the attributes in the configuration file, just call param() method with no arguments.

    my @attr = $cfg->param;

Now @attr array consists of all the attributes available in the configuration file. If we use the following piece of code

    print join "\n", $cfg->param;

to the bove create MyConfig.cfg file, the result would look like the following:

    author.first name
    author.last name

It's also handy to use param_hash() method, which returns the key value pairs which yrou can store into a hash variable right away. I believe one could do that by rolling a loop that uses param() like:

    my %Config;
    for ($cfg->param) {
        $Config{$_} = $cfg->param($_);
    }

After the introduction of param_hash(), we can shorten the above process into:

    my %Config = $cfg->param_hash();

Enjoy!

AUTHOR

Sherzod Ruzmetov <sherzodr@cpan.org>

SEE ALSO