What are some other ways this loop can be rewritten?

Viewed 123

Got this simple loop:

use Config::Simple:from<Perl5>;

my $cfg = Config::Simple.new(syntax => 'ini');


%config{'short_name'} = 'blah';
for %config.kv -> $k, $v {
    $cfg.param("%config{'short_name'}.$k", $v);
}

Works fine. But I want to get more familiar with other ways to achieve the same goal, if only to get comfortable reading other people's code. Plus, loops seem to be the "old" school way of doing things and not very "Raku-like" and I need to get more comfortable working with using functions in more advanced ways.

Anyway, to stretch my new Raku muscles, I came up with this one-liner as an alternative:

map(-> $k, $v { $cfg.param("%config{'short_name'}.$k", $v) }, %config.kv);

It's less readable (at least to my untrained eye), but it works.

My hunch is there is some good way of making this code both more concise and readable. Interested in seeing if I might be right.

1 Answers
  • rewritten (IMHO, for is more suitable than map, if a variable is changed)

        use Config::Simple:from<Perl5>;
    
        my $cfg = Config::Simple.new: syntax => 'ini';
        my %config := short_name => 'blah';
    
        $cfg.param: "%config<short_name>\.{.key}", .value  for %config;
    
        print $cfg.as_string();
    
  • by set_block

        use Config::Simple:from<Perl5>;
    
        my $cfg = Config::Simple.new: syntax => 'ini';
        my %config = short_name => 'blah';
    
        $cfg.set_block: %config<short_name>, %config;
    
        print $cfg.as_string();
    
Related