需要解释在Perl中读取"config"文件

use*_*862 2 perl config file

我正在学习Perl.

我在文件上看到了一个使用函数"do"的脚本.然后我读到了关于该功能:

如果可以读取文件但无法编译它,则返回undef并在$ @中设置错误消息.如果无法读取文件,则返回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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢

amo*_*mon 8

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

myprogrc:

{
  foo => "bar",
  baz => 42,
}
Run Code Online (Sandbox Code Playgroud)

用法:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

有许多更好的配置格式:

  • YAML
  • INI格式,无穷无尽的变化

如果真的必须,你可以使用JSON或XML.所有这些格式都具有以下优点:它们只是数据而不是代码.因此它们是安全的(假设解析器没有错误).