gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:38:28 29 4
gpt4 key购买 nike

我正在学习 Perl。

我看到一个脚本在一个文件上使用函数“do”。然后我阅读了有关该功能的内容:

If do can read the file but cannot compile it, it returns undef and sets an error message in $@ . If do cannot read the file, it returns undef and sets $! to the error. Always check $@ first, as compilation could fail in a way that also sets $! . If the file is successfully compiled, do returns the value of the last expression evaluated.

Inclusion of library modules is better done with the use and require operators, which also do automatic error checking and raise an exception if there's a problem.

You might like to use do to read in a program configuration file. Manual error checking can be done this way: You might like to use do to read in a program configuration file. Manual error checking can be done this way:

# 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;
}
}

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

谢谢

最佳答案

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

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。所有这些格式的优点是它们只是数据,而不是代码。因此它们可以安全使用(假设解析器没有错误)。

关于perl - 需要解释在 Perl 中读取 "config"文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321165/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com