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

一世执手 提交于 2019-12-23 19:39:44

问题


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)

回答1:


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.

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.

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)



来源:https://stackoverflow.com/questions/46704407/perl-6-transh-vs-transh-keys-h-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!