Perl6 'do (file)' equivalent

In perl5, I used "do (file)" for configuration files as follows:

---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 ---

Also Larry Wall "Perl Programming" also mentions this method:

But FILE is still useful for things like a reader, configuration files. Manual error checking can be performed as follows:

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

Benefits

  • no need to write your own parser every time - perl parse and creating data structures for you;
  • faster / easier: own data perl structures / types without overhead for conversion from an external format (for example, YAML);
  • does not require manipulation of @INC to load a module somewhere compared to a module as a conf file;
  • less code compared to modules as a conf file;
  • "" " " perl;
  • "ad hoc" ;

  • : / - " ";

perl6?
perl6 ( ) , , , ?
- " "?

+4
1

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",
    }
}

script, :

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.";
}
+3

Source: https://habr.com/ru/post/1622941/


All Articles