Perl解析INI檔案

來源:互聯網
上載者:User

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;
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.