【问题标题】:Need explanation on reading "config" file in Perl需要解释在 Perl 中读取“配置”文件
【发布时间】:2014-02-14 18:25:49
【问题描述】:

我正在学习 Perl。

我看到一个在文件上使用函数“do”的脚本。然后我读到了那个函数:

如果 do 可以读取文件但不能编译它,它返回 undef 和 在 $@ 中设置错误消息。如果 do 无法读取文件,则返回 undef 并设置 $!到错误。总是先检查 $@,作为编译 可能会以同样设置 $! 的方式失败.如果文件成功 编译后,返回最后一个表达式的值。

通过 use 和 require 更好地包含库模块 运算符,它们还进行自动错误检查并引发 如果有问题,则例外。

您可能希望使用 do 来读取程序配置文件。 可以通过以下方式进行手动错误检查: 您可能喜欢使用 do 来读取程序配置文件。 可以通过这种方式进行手动错误检查:

# read in config files: system first, then user 
for $file ("/share/prog/defaults.rc",
           "$ENV{HOME}/.someprogrc")     {
    unless ($return = do $file) {
        warn "couldn't parse $file: $@" if $@;
        warn "couldn't do $file: $!"    unless defined $return;
        warn "couldn't run $file"       unless $return;
    }
}

我不明白他们为什么要编译配置文件? 它是什么样的配置文件?我们为什么/何时使用该配置文件?

谢谢

【问题讨论】:

  • 感谢您的回答。现在我明白了

标签: perl file config


【解决方案1】:

有时,使用脚本代替配置文件。然后可以设置全局状态,或返回一些值。例如:

myprogrc:

{
  foo => "bar",
  baz => 42,
}

用法:

my $file = "myprogrc";
if (my $config = do $file) {
   # do something with the config values
   print "config values were $config->{foo} and $config->{baz}\n";
}
else {
    warn "couldn't parse $file: $@" if $@;
    warn "couldn't do $file: $!"    unless defined $config;
    warn "couldn't run $file"       unless $config;
}

不要这样做。因为配置文件只是 Perl 代码,它可以执行任意东西——危险!例如。 `rm -rf ~` 将是一个令人讨厌的惊喜。

还有很多更好的配置格式:

如果确实需要,您可以使用 JSON 或 XML。所有这些格式的优点是它们只是数据,而不是代码。因此它们可以安全使用(假设解析器没有错误)。

【讨论】:

    猜你喜欢
    • 2016-08-29
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2021-05-04
    • 2020-07-18
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多