Perl: Simple INI file info retrieval

Go To


I have a perl script that's reading an INI file like this:

Hostname =
Port = 161

The library that I'm using for this is Config::Tiny.

Normally when reading the ini file, I would have something like this:

$Config = Config::Tiny->read( 'configfile.ini' );

my $Hostname_property = $Config->{placeholder_title}->{Hostname};

Now I have a case where the section title in the config file is decided by the user, so I don't exactly know what it is.

Before I actually had multiple sections in the config file, so I would iterate through them like this:

 foreach my $Section (keys %{$Config}) {

            my $Hostname_property = $Config->{$Section}->{Hostname};
            my $Port_property = $Config->{$Section}->{Port};

But what if I were to have only 1 section in total?

Is there a particular keyword I can use to substitute for the section name?

I've tried the similar looping logic from the prior example something like this:

$Config = Config::Tiny->read( 'configfile.ini' );

my $Section = keys %{$Config};

my $Hostname_property = $Config->{$Section}->{Hostname};

print $Hostname_property, "\n";

But then I get an error that $Hostname_property is not initialized, so my $Section variable clearly isn't doing what I hoped it to do.

If anybody can help me out or at least point me in the right direction, it would be greatly appreciated.

Thank you.

2012-04-04 18:52
by user1300922


The reason my $Section = keys %{$Config}; doesn't work is that you're calling keys in scalar context, so it's returning the number of keys. Try calling it in list context instead:

my ($Section) = keys %{$Config};

This will set $Section to the first key. ("first" in whatever order keys is returning the keys in. If there's only one key, that doesn't matter.)

2012-04-04 19:08
by cjm
Awesome, it works. Thank you - user1300922 2012-04-04 19:18


It's okay for a hash to have only one key. Consequently, it's okay if there's only one section in your ini file.

For example, if we have a file called blah.ini with contents of


and if we run the following code:

use strict;
use warnings;
use Config::Tiny;
my $cfg=Config::Tiny->read("blah.ini");
use Data::Dumper;
print Dumper($cfg) . "\n";

Then we get the output

$VAR1 = bless( {
                 'title' => {
                              'blah' => 'baz',
                              'foo' => 'bar'
               }, 'Config::Tiny' );

Consequently, we can do something like the following:

use strict;
use warnings;
use Config::Tiny;

my $cfg=Config::Tiny->read("blah.ini");
foreach my $title(sort keys %$cfg)
  foreach my $setting (sort keys %{$cfg->{$title}})
    print "title: $title,setting $setting, value $cfg->{$title}->{$setting}\n";

And the output is

title: title,setting blah, value baz
title: title,setting foo, value bar
2012-04-04 19:01
by NoName
I see. Thanks for the help : - user1300922 2012-04-04 19:19