Copy From http://www.lwolf.cn/blog/article/program/perl-ini.html
I have previously written a C # parsing INI file.ArticleAt that time, I used Perl to parse INI, and then I found a ready-made Resolution on the Internet.CodeIniparser.
Assume that the INI file is like this:
[Directories]
Input=C: \ autoexec. bat
The usage is as follows:
Use Iniparser;
My $ Ini = Iniparser -> New ( " C: \ test. ini " );
My $ Inputdir = $ Ini -> Expectentry ( " Directories " , " Input " );
The following is the iniparser code:
# -------------------------------------------------------------------------------
# Iniparser. Version 1.0
# A freeware module for parsing. ini files.
# Joachim pimiskern, September 13,200 3
#-------------------------------------------------------------------------------
Package Iniparser;
Use Strict;
Sub New
{
My ( $ Class , $ Filename ) = @_ ;
My $ Data = {
Filename => $ Filename
};
Bless ( $ Data , $ Class );
$ Data -> Read ( $ Filename );
Return $ Data ;
}
Sub Read
{
My ( $ Self , $ Filename ) = @_ ;
My $ Sectionname = " Global " ;
My $ Section = {};
My $ Line ;
Local * FP;
$ Self -> { $ Sectionname } = $ Section ;
Open (FP , " <$ Filename " ) Or Die " Read (): Can't open $ filename for read: $! " ;
While ( Defined ( $ Line = < Fp > ))
{
Chomp ( $ Line );
If ( $ Line = ~ /^ \ S * ( .*? ) \ S * = \ S * ( .*? ) \ S * (; .* ) ? $ / ) # Assignment
{
My $ Left = $ 1 ;
My $ Right = $ 2 ;
$ Section -> { $ Left } = $ Right ;
}
Elsif ( $ Line = ~ /^ \ S *\ [ \ S * ( .*? ) \ S *\ ] \ S * (; .* ) ? $ / ) # Section name
{
$ Sectionname = $ 1 ;
$ Section = {};
$ Self -> { $ Sectionname } = $ Section ;
}
Elsif ( $ Line = ~ /^ \ S * (; .* ) ? $ / ) # Comment
{
}
Else
{
Die " Read (): Illegal line <$ line> In File $ filename. " ;
}
}
Close (FP );
}
Sub Expectsection
{
My ( $ Self , $ Section ) = @_ ;
My $ Filename = $ Self -> {Filename };
If ( ! Exists $ Self -> { $ Section })
{
Die " Expectsection (): $ filename has no section [$ section] " ;
}
Return $ Self -> { $ Section };
}
Sub Expectentry
{
My ( $ Self , $ Section , $ Left ) = @_ ;
My $ Filename = $ Self -> {Filename };
My $ Sectionhash = $ Self -> Expectsection ( $ Section );
If ( ! Exists $ Sectionhash -> { $ Left })
{
Die " Expectentry (): $ filename, Section [$ section] has no $ left entry " ;
}
Return $ Sectionhash -> { $ Left };
}
1 ;