Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Iterating through INI files

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.

like image 645
user1300922 Avatar asked Mar 29 '12 14:03

user1300922


2 Answers

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.

like image 33
Cfreak Avatar answered Sep 24 '22 14:09

Cfreak


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.

like image 63
Eric Avatar answered Sep 23 '22 14:09

Eric