gpt4 book ai didi

raku - perl6 'do(file)' 等效

转载 作者:行者123 更新时间:2023-12-01 06:37:07 26 4
gpt4 key购买 nike

在 perl5 中,我曾经为这样的配置文件“做(文件)”:

---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”也提到了这种方法:

But do FILE is still useful for such things as reading program configuration files. Manual error checking can be done this way:


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

福利 :
  • 不需要每次都编写自己的解析器 - perl 解析和
    为您创建数据结构;
  • 更快/更简单: native perl 数据
    结构/类型,无需从外部格式转换的开销(如 YAML);
  • 不需要操纵@INC 来加载
    来自某个地方的模块与作为 conf 文件的模块相比;
  • 少额外
    将代码与模块比较为 conf 文件;
  • “配置文件”的“语法”与 perl 本身一样强大;
  • “临时”格式;

  • 缺点 :
  • 没有隔离:我们可以从“配置”中执行/销毁任何东西
    文件”;

  • perl6 如何获得相同的效果?
    有没有办法在 perl6 中做得更好(没有 缺点 )并且不解析自己的语法,语法,模块包括?
    诸如“从文件中的文本表示中加载哈希或数组”之类的东西?

    最佳答案

    您可以使用 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.";
    }

    关于raku - perl6 'do(file)' 等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34616160/

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