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.
You can do what you want with
Config::Tiny. Simply use thekeysfunction to iterate over all of the keys of the hash, as follows: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.