Saturday, June 29, 2013

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

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

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

while (<INI>)
{
     chomp($_);
     if($_=~/^#/ || $_=~/^;/ || $_=~/^\/\//)
     {
          #ignore these lines coz they are comments!
     }
     elsif($_=~/^$/)
     {
          #ignore these lines coz they are blank!
     }
     else
     {
          my ( $key, $value ) = split( /=/, $_ );
          $params{ $key } = $value;
     }
}

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

#Get value for individual key
print $params{url};
----------------------------------------------
config.ini:

dev_server=singleton
dev_port=8081
dev_url=http://dev.single-ticket.com/

server=mingleton
port=8080
url=http://www.single-ticket.com/

No comments :