Saturday, June 29, 2013

How could you parse config file with "key=value" format with a header in Perl?

my %params = ();
my $INIFILE='config.ini';

open (INI, $INIFILE) || die "could not open $INIFILE - $!";

while (<INI>)
{
chomp($_);
if($_=~/^#/ || $_=~/^;/ || $_=~/^\/\//)
{
#ignore these lines coz they are comments!
}
elsif($_=~/^$/)
{
#ignore these lines coz they are blank!
#die "Blank line detected at $.\n";
}
elsif ($_ =~ /^\[(.+)\]/) #extract string enclosed in '[]'
{
$header = $1;
}
else
{
my ( $key, $value ) = split( /=/, $_ );
$params{$header}{$key} = $value;
}
}

foreach $header(keys %params)
{
  print "$header: ";
  foreach $subheader (sort keys %{$params{$header}})
  {
    print "$subheader = $params{$header}{$subheader} ";
  }
  print "\n";
}

#To access individual key, value
print $params{'DEV'}{'url'};
-----------------------------------------------------------------
config.ini:

[DEV]
server=rocket
port=8080
url=http://dev.single-ticket.com/

[QA]
server=princeton
port=8081
url=http://beta.single-ticket.com/

[PROD]
server=saboo
port=8082
url=http://www.single-ticket.com/

No comments :