这个循环还有哪些其他方法可以重写?

发布于 2025-01-14 01:01:18 字数 575 浏览 1 评论 0原文

得到这个简单的循环:

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

工作正常。但我想更熟悉实现相同目标的其他方法,即使只是为了轻松地阅读其他人的代码。另外,循环似乎是“旧”学校的做事方式,而不是很“像 Raku”,我需要更舒适地以更高级的方式使用函数。

不管怎样,为了伸展我的新 Raku 肌肉,我想出了这个单行作为替代方案:

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

它的可读性较差(至少对于我未经训练的眼睛来说),但它有效。

我的预感是有一些好方法可以使这段代码更加简洁和可读。有兴趣看看我是否是对的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

堇年纸鸢 2025-01-21 01:01:18
  • 重写(恕我直言,如果变量发生更改,formap 更合适)

     使用 Config::Simple:from;
    
        我的 $cfg = Config::Simple.new: 语法 => '伊尼';
        我的 %config := 短名称 => '废话';
    
        $cfg.param: "%config\.{.key}", %config 的 .value;
    
        打印 $cfg.as_string();
    
  • by set_block

     使用 Config::Simple:from;
    
        我的 $cfg = Config::Simple.new: 语法 => '伊尼';
        我的 %config = Short_name => '废话';
    
        $cfg.set_block: %config, %config;
    
        打印 $cfg.as_string();
    
  • 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();
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文