在perl5中,我常常对这样的配置文件执行“do(file)”:
---script.pl start ---
our @conf = ();
do '/path/some_conf_file';
...
foreach $item (@conf) {
$item->{rules} ...
...
---script.pl end ---
---/path/some_conf_file start ---
# arbitrary code to 'fill' @conf
@conf = (
{name => 'gateway',
rules => [
{verdict => 'allow', srcnet => 'gw', dstnet => 'lan2'}
]
},
{name => 'lan <-> lan2',
rules => [
{srcnet => 'lan', dstnet => 'lan2',
verdict => 'allow', dstip => '192.168.5.0/24'}
]
},
);
---/path/some_conf_file end ---
Larry Wall的“Programming Perl”也提到了这种方法:
但是FILE对阅读程序这样的东西仍然有用 配置文件。手动错误检查可以这样做:
# read in config files: system first, then user
for $file ("/usr/share/proggie/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;
} }
优势:
缺点:
如何使用perl6获得相同的效果?
有没有办法在perl6中做得更好(没有缺点)并且没有解析自己的语法,语法,模块包括?
像“从文件中的文本表示加载哈希值或数组”这样的东西?
答案 0 :(得分:4)
您可以使用EVALFILE($file)
(参考http://doc.perl6.org/language/5to6-perlfunc#do)。
正如您所指出的,使用EVALFILE
有缺点,所以我不会在这个方向上添加任何内容: - )
这是一个示例配置文件:
# Sample configuration (my.conf)
{
colour => "yellow",
pid => $*PID,
homedir => %*ENV<HOME> ~ "/.myscript",
data_source => {
driver => "postgres",
dbname => "test",
user => "test_user",
}
}
以下是使用它的示例脚本:
use v6;
# Our configuration is in this file
my $config_file = "my.conf";
my %config := EVALFILE($config_file);
say "Hello, world!\n";
say "My homedir is %config<homedir>";
say "My favourite colour is %config<colour>";
say "My process ID is %config<pid>";
say "My database configuration is:";
say %config<data_source>;
if $*PID != %config<pid> {
say "Strange. I'm not the same process that evaluated my configuration.";
}
else {
say "BTW, I am still the same process after reading my own configuration.";
}