I'm making a Perl script that needs to read and obtain the values of an INI file.
INI File Format:
[name]
Property=value
Example:
[switch_6500]
cpu=1.5.1.12.4
free_memory=1.45.32.16
[oracle_db_11g]
param1=value1
param2=value2
param3=value3
param4=value4
...
As you can see, there can be any amount of sections, that contain any number of parameters. The names of the section names/parameters will always be different.
What I need to do is have my Perl script iterate through every section, and obtain all parameter names/values of that section. What I'm used to doing with INI files is simply specifying the section name along with the name of the parameter like this:
#!/usr/bin/perl -w
use strict;
use warnings;
use Config::Tiny;
# Read the configuration file
my $Config = Config::Tiny->new();
$Config = Config::Tiny->read( 'configfile.ini' );
my $Metric1_var = $Config->{switch_6500}->{cpu};
my $Metric2_var = $Config->{switch_6500}->{free_memory};
However, now that I have an indefinite amount of section names/parameters, as well as not knowing their names, I can't seem to figure out a way to extract all the values. I was looking around at the Config::IniFiles module, and it has some interesting stuff, but I can't seem to find a way to obtain a parameter value without knowing the section/parameter name.
If anyone can help me with iterating through this INI file, it would be greatly appreciated.
Thank you.
I personally prefer Config::Simple. You can call it's param()
method with no arguments to return all of the parameters from your file. It also has a few other nice features over Config::Tiny
.
You can do what you want with Config::Tiny
. Simply use the keys
function to iterate over all of the keys of the hash, as follows:
use strict;
use Config::Tiny;
my $config = Config::Tiny->read('configfile.ini');
foreach my $section (keys %{$config}) {
print "[$section]\n";
foreach my $parameter (keys %{$config->{$section}}) {
print "\t$parameter = $config->{$section}->{$parameter}\n";
}
}
Note: Because hashes are "hashed", and not ordered like arrays are, the order of keys returned may seem nonsensical. Since order doesn't matter in an INI file (only the placement of which parameters are in which section matters), this shouldn't be a problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With