Perl Config::IniFiles - how do I create the ini file 'if not exists'? WriteConfig method fails with error

Viewed 205

I want to use a number of .ini files to store sets of values to pick up later, when I re-run the script (after a reboot, e.g.). I am trying to write my code such that it will first check to see if the specific .ini file exists, and if so, read in the values, but if not, then create it (the script will subsequently proceed to store values in it).

if (-f '/path/to/file.ini') { # if file exists
    # read file into object
    my $ini = Config::IniFiles->new(-file => '/path/to/file.ini',
         -nomultiline => 1, -fallback => 'parameters', -commentchar => ';'
    );
} else {
    # create first instance of ini file
    WriteConfig('/path/to/file.ini');
}

Obviously I don't understand how to use Config::InFiles because it keeps failing on WriteConfig('/path/to/file.ini');.

Can I create a file with this module, or do I have to do it another way?

1 Answers

WriteConfig is an object method and would be called as $ini->WriteConfig(...);

This creates a new file:

use warnings;
use strict;
use Config::IniFiles;

my $ini = Config::IniFiles->new();

$ini->AddSection('section1');
$ini->newval('section1', 'param1', 123);
$ini->WriteConfig('./file.ini');

File file.ini now contains:

[section1]
param1=123
Related