I have a perl script that's reading an INI file like this:
[placeholder_title]
Hostname = 127.0.0.1
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.
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.)
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
[title]
foo=bar
blah=baz
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