【问题标题】:Reading new format in INI file perl在 INI 文件 perl 中读取新格式
【发布时间】:2014-05-14 16:26:20
【问题描述】:

我还有一个关于 INI 文件的问题。我的老师已经更新了文件的配置。现在我的代码无法读取这个新的配置文件。它的格式已更改。 perl中如何读取INI文件中的这种格式?

[section1]
value1
value2

如您所见,INI 文件的格式现在只有值。参数没了。 perl 如何读取这一行?它没有任何参数,只剩下。我只想读取。我之前使用 Config::Tiny 来阅读该行,但我似乎无法用这个来解决这个问题:

my $file = "file directory";

my $Config = Config::Tiny->read($file);
$Config->{"section1"}->{_};

我的代码错了吗?因为我无法从此代码中获取输出。有人可以帮我解决这个问题吗?谢谢。

【问题讨论】:

  • 那不是一个有效的ini文件。
  • 那读不出来?还是我必须使用其他方法? @jaypal
  • 可能是另一种方法。所有这些模块(包括Config::SimpleConfig::IniFiles 等)都基于文档化的 INI 格式。
  • 你还知道这些方法吗?我似乎无法解决这个问题。我认为它仍然使用 Config::Tiny @jaypal
  • 就像@jaypal 所说,您必须使用另一种方法来读取此文件。我希望这方面的专家可以帮助你。

标签: linux perl ubuntu parameters cgi


【解决方案1】:

你需要自己处理:

#!/usr/bin/perl

use 5.10.0;

sub read_not_ini
{
    my $file = shift;

    my %values;
    my $section;

    open my $fh, '<', $file or die "Can't read $file: $!";
    while (<$fh>)
    {
        # skip comments, blank lines.
        next if /^\s*#/ or /^\s*$/;

        # don't need/want end-line character.
        chomp;

        if (/^\[([^\]]+)\]/)
        {
            my $s = $1;
            $section = $values{$s} //= [];
        }
        elsif($section)
        {
            push @$section, $_;
        }
        else
        {
            say STDERR "$file: values without a section: line $.";
        }
    }
    return \%values;
}

my $Config = read_not_ini(shift); # pass in as param
say for @{$Config->{"section1"}};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2019-02-25
    • 2013-04-18
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多