首页 | 新闻 | 交流 | 问吧 | 文档 | 手册 | 下载 | 博客

Perl解析INI文件

作者:  时间: 2011-03-26

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;