• Perl解析INI文件


    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;

  • 相关阅读:
    css实现鼠标移入table时出现滚动条且table内容不移位
    SASS学习笔记
    html5--canvas学习笔记
    在iframe里调用parent.func()引出的js函数运行在它们被定义的作用域里,而不是它们被执行的作用域里
    css background-position:x% y%
    js十进制等互相转换
    jsp中的动作元素:<jsp:plugin>
    终于有时间写代码了
    OK 开始实践书上的项目一:即使标记
    我没有忘记敲代码
  • 原文地址:https://www.cnblogs.com/morya/p/1996481.html
Copyright © 2020-2023  润新知