2016-01-05 25 views
4

在我使用 '做(文件)' 像這樣的配置文件的perl5:perl6 '做(文件)' 等同

---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的 「編程的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: [email protected]" if [email protected]; 
      warn "couldn't do $file: $!" unless defined $return; 
      warn "couldn't run $file"  unless $return; 
     } } 

優勢

  • 不需要每次寫自己的解析器 - perl的解析和 創建的數據結構爲您服務;
  • 更快/簡單:天然Perl數據 結構/類型,而塔頂餾用於從外部格式(如YAML)轉換;
  • 不需要操作@INC從模塊作爲conf文件加載 模塊;
  • 更少額外 代碼相比模塊作爲conf文件;
  • 「配置文件」的「語法」與perl本身一樣強大;
  • 「ad hoc」格式;

缺點

  • 沒有隔離:我們可以執行/銷燬從 「配置文件 」 任何東西;

如何獲得與perl6一樣嗎?
有沒有辦法做到這一點在perl6(不缺點),並沒有更好的分析自己的語法,語法,模塊,包括?
類似於「從文件中加載散列或從文本表示形式的數組」?

+0

https://github.com/teodozjan/perl-store? – teodozjan

+1

有更多的缺點/反對意見:https://stackoverflow.com/q/5969417 – daxim

+1

'EVALFILE',cf [5to6-perlfunc](http://doc.perl6.org/language/5to6-perlfunc#do) – Christoph

回答

3

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