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 callingkeysin scalar context, so it’s returning the number of keys. Try calling it in list context instead:This will set
$Sectionto the first key. (“first” in whatever orderkeysis returning the keys in. If there’s only one key, that doesn’t matter.)