copy from http://www.lwolf.cn/blog/article/program/perl-ini.html
之前有寫過用C#解析INI檔案的文章,那時是因為要用Perl來解析INI,後來就在網上找了個現成的解析代碼IniParser.
假設INI檔案是這樣的:
[Directories]
Input=c:\autoexec.bat
使用方法如下:
use IniParser;
my $ini = IniParser->new("c:\\test.ini");
my $inputdir = $ini->expectEntry("Directories","Input");
以下是IniParser的代碼:
#-------------------------------------------------------------------------------
# IniParser. Version 1.0
# A freeware module for parsing .ini files.
# Joachim Pimiskern, September 13, 2003
#-------------------------------------------------------------------------------
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;