zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    mysql常用基本命令
    mysql8.0.13下载与安装图文教程
    k8s ingress 增加跨域配置
    Jenkins 备份恢复插件 thinBackup 使用
    k8s HA master 节点宕机修复
    nginx 跨域问题解决
    mongodb 3.4.24 主从复制
    k8s 线上安装 jenkins并结合 jenkinsfile 实现 helm 自动化部署
    k8s helm 运用与自建helm仓库chartmuseum
    centos6 源码安装 unzip
  • 原文地址:https://www.cnblogs.com/morya/p/1996481.html
Copyright © 2011-2022 走看看