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

One more question about hash as an argument for trans . In the following code, just hash gives the wrong result, but it is replaced with keys and values , which makes it correct. What's 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) 
+3
source share
1 answer

I think you misunderstood what .trans does. You specify the range of characters that you want to change to other characters. You do NOT specify a string to be changed to another string.

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

Perhaps we should introduce a .subst version that takes Hash for comparisons and replacements. Meanwhile, you probably have to create a loop that will work on the hash keys / values ​​and call .subst with this. ( https://docs.perl6.org/routine/subst )

+5
source

Source: https://habr.com/ru/post/1273201/


All Articles