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