James Parsons
James Parsons

Reputation: 6057

getting ini information from perl

I was wondering how to retrieve information from an INI file in perl. I found something at the perl.org documentation here, however it is not commented, and would need some explaining. Are there any easier to use modules for parsing the INI information??

[version]
ver=1.0.3

[ServerInfo]
port=1234
address="localhost"

Upvotes: 0

Views: 236

Answers (4)

Unos
Unos

Reputation: 1361

You can also check out the Config::Auto module.

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69314

When working out how to do something in Perl, your first step should always be to search CPAN for useful-looking modules.

In this case, searching for "ini" gives you plenty of options to choose from.

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141850

There is a good INI file reader in CPAN, which you can sublclass if you want.

% cpan install 'Config::INI::Reader'

Then...

% cat blah.pl 
#!/usr/bin/env perl -w

use strict;
use Config::INI::Reader;

my $filename = "blah.ini";

my $ini = Config::INI::Reader->read_file($filename);
my $server_info = $ini->{'ServerInfo'};

printf "Will connect to %s:%d\n"
    , $server_info->{'address'}
    , $server_info->{'port'}
    ;

Running:

% ./blah.pl 
Will connect to "localhost":1234

You don't need the " in your INI file.

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185530

Try doing this by example :

use strict;
use warnings;

use Config::IniFiles;

my $ini = new Config::IniFiles(
    -file => '/tmp/config.ini',
    -allowcontinue => 1
);

print $ini->val('version', 'ver');

See perldoc Config::IniFiles

Upvotes: 3

Related Questions