Perl 6: trans(%h) vs trans(%h.keys => %h.values) [英] Perl 6: trans(%h) vs trans(%h.keys => %h.values)

查看:31
本文介绍了Perl 6: trans(%h) vs trans(%h.keys => %h.values)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 hash 作为 trans 参数的另一个问题.在下面的代码中,简单地取 hash 给出了不正确的结果,但是用 keysvalues 替换它使它正确.怎么了?

Yet another question about hash as argument for trans. In the following code taking simply hash gives an incorrect result, but replacing it with keys and values makes it correct. What is wrong?

my @alph1 = <a+ b+ c+ d+ e+ f+>;
my @alph2 = <A_ B_ C_ D_ E_ F_>;
my %h;
%h{ @alph1 } = @alph2;

my $str = 'a+bc de+f';

my $text = $str.trans(%h);
say $text;    # A_BC DE_F (incorrect)

$text = $str.trans(%h.keys => %h.values);
say $text;    # A_bc dE_f (correct)

推荐答案

我想你误解了 .trans 的作用.您指定要更改为其他 字符字符 范围.您没有指定要更改为另一个 stringstring.

I think you misunderstand what .trans does. You specify a range of characters to be changed into other characters. You are NOT specifying a string to be changed to another string.

所以答案A_BC DE_F 正确答案,因为aA代替,+ 替换为 _b 替换为 Bc 替换为替换为C

So the answer A_BC DE_F is the correct answer, because a is replaced by A, the + is replaced by _, the b is replaced by B, the c is replaced by C, etc. etc.

也许我们应该引入一个 .subst 版本,它采用匹配器和替换的 Hash.同时,您可能需要创建一个循环来运行散列的键/值,并使用它调用 .subst.(https://docs.raku.org/routine/subst)

Perhaps we should introduce a version of .subst that takes a Hash of matchers and replacements. Meanwhile, you will probably have to create a loop that runs over the keys/values of the hash and call .subst with that. (https://docs.raku.org/routine/subst)

这篇关于Perl 6: trans(%h) vs trans(%h.keys => %h.values)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆