.trans with keys longer than one character in Perl 6

trans is a very useful and powerful tool, but it remains a bit of a mystery to me.

eg. I still do not understand this phrase from the docs:

In the case of using a list of keys and values, substrings can be replaced as well.

What is an algorithm if keys and values ​​are longer than one character?

The following test code explores how .trans works with conflicting keys. Why does the first pair work differently depending on whether it is one or is accompanied by a second pair?

 my Pair @trans = ab => '12', bc => '34', ; my $str = 'ab'; say "both trans: $str.trans(@trans)"; # 13 say "1st trans: $str.trans(@trans[0])"; # 12 

Using a hash instead of a list of pairs leads to a different result:

 my %trans = ab => '12', bc => '34', ; my $str = 'ab'; say "both trans: $str.trans(%trans)"; # 12 

(I understand that in hash pairs can go in any order, but in the first example with list this is the first pair that is not fully used if the 2nd pair is present)

+5
source share
1 answer

(I'm not 100% sure of the following, but I need to run.)

.trans requires one or more paired arguments that together describe the desired translation.

Translation of one pair whose key is one line

P6 maps the Nth character of a string of a key pair to the Nth character of a string of value pairs.

So .trans: "ab" => "12" maps "a" to "1" and "b" to "2" .

Translation of one pair whose key is a list of strings

P6 maps the Nth line of the key list of the pair to the Nth line of the list of values ​​of the pair.

Thus .trans: ("ab", "bc") => ("12", "13") maps "ab" to "12" and "bc" to "13" .

Pair List Translation

The translation of one pair occurs in one form or another described above, depending on whether the key contains one line or a list of them.

Translation of the list of pairs simply repeats the process for each pair, making either the Nth character or the Nth string matching in accordance with this pairing key.

how .trans works with conflicting keys

Given a list of pairs, P6 first tries first, and if that doesn't match, then the second pair, etc.


I need to study what lezmat now thinks and what she had in mind when she said the following in her earlier answer about .trans :

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.


I think the sentence you quoted from the document is a bit ambiguous:

When using a list of keys and values, substrings can also be replaced.

This means that the (single) .key pair passed in .trans stores a list of strings, not one line, and also for one single .value attribute.

+4
source

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


All Articles