user1300922
user1300922

Reputation: 207

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.

Upvotes: 6

Views: 5882

Answers (3)

Eric
Eric

Reputation: 6016

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.

Upvotes: 7

tuxuday
tuxuday

Reputation: 3037

I understand you are happy with parsing of ini files. If you just want to loop through all the sections & their key-pairs then

You can loop through Hash-Of-Hash like this.

foreach my $Section (keys %$Config) {
 print "[$Section]";
 foreach my $Key (keys %{$Config->{$Section}}) {
  print "$Key = $Config->{$Section}->{$Key}";
 }
}

Upvotes: 2

Cfreak
Cfreak

Reputation: 19319

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.

Upvotes: 5

Related Questions