Wednesday, July 3, 2013

How could you populate keys and values of a config file into hash of hashes?

$ini="config.ini";
my %conf = ();

open (INI, "$ini") || die "Can't open $ini: $!\n";
while (<INI>)
{
  chomp;
  if (/^\s*\[(\w+)\].*/)
  {
        $header = $1;
  }
  elsif (/^\W*(\w+)=?(\w+)\W*(#.*)?$/)
  {
    #put them into hash
    $conf{$header}{$1} = $2; 
  }
}
close (INI);

print $conf{'QA'}->{'ip'} . "\n";
---------------------------------------------------------
config.ini:

[DEV]
url=http://readytips.blogspot.in/dev/
ip=127.0.0.0
[QA]
url=http://readytips.blogspot.in/qa/
ip=127.0.0.1
[PROD]
url=http://readytips.blogspot.in/live/
ip=127.0.0.2

No comments :