Apr 19, 2011

Parsing Windows INI files using Perl

This is a quick dirty little script that I wrote to parse INI files on Microsoft Windows OS where I wasn't allowed to install Config::IniFiles or a similar module from CPAN.

INI files where data is separated by colon (:) or equal to sign (=) are supported.

#!/usr/bin/perl
 
# Released under the same license(s) as Perl
 
use strict;
use warnings;
use Data::Dumper;
 
my $ini = {};
 
my $header;
 
while (<DATA>) {
    chomp;

    # ignore blank lines
    next if /^\s*$/;
 
    # ignore commented lines
    next if /^\s*\;|#/;
 
    # check for section header
    if ( /^\s*\[([^\]]+)\]/ ) {
        $header = $1;
        # remove leading and trailing white spaces
        $header =~ s/^\s*|\s*$//g;
        $ini->{$header} = {};
    }
     
    # check for section data
    if (/(\S+)\s*[=:]\s*(.*?)\s*$/) {
        $ini->{$header}->{$1} = $2;
    }
}

# the data could be printed as
# $ini->{SECTION_HEADER}->{key}
for my $m (qw/odbc.allow_persistent odbc.check_persistent odbc.max_persistent/) {
       print "$m = ", $ini->{ODBC}->{$m}, "\n";
}

for my $n (qw/NoOfReplicas DataDir DataMemory/) {
       print "$n = ", $ini->{'NDBD DEFAULT'}->{$n}, "\n";
}


__DATA__
# taken from vanilla php.ini 
# notice the leading and trailing spaces
 
[ ODBC ]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
 
# taken from config.small.ini
[NDBD DEFAULT]
NoOfReplicas: 2
DataDir: /add/path/here
FileSystemPath: /add/path/here
DataMemory: 600M
IndexMemory: 100M
BackupMemory: 64M

Output

odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
NoOfReplicas = 2
DataDir = /add/path/here
DataMemory = 600M

No comments:

Post a Comment