Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.trans with keys longer than one symbol in Perl 6

Tags:

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

E.g. I still don't understand this phrase from the docs:

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

What's the algorithm if keys and values are longer than one symbol?

The following test code explores how .trans works with 'conflicting' keys. Why does the 1st pair work differently depending on whether it is alone or accompanied by the 2nd 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 produces 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 sequence, but in the first example with the list it's the 1st pair, which isn't fully used if the 2nd pair is present)

like image 346
Eugene Barsky Avatar asked Nov 08 '17 07:11

Eugene Barsky


1 Answers

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

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

Translation of a single pair whose key is a single string

P6 maps the Nth character of the pair's key string to the Nth character of the pair's value string.

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

Translation of a single pair whose key is a list of strings

P6 maps the Nth string of the pair's key list to the Nth string of the pair's value list.

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

Translation of a list of pairs

Translation of a single pair proceeds in one or other of the two forms explained above depending on whether the key contains one string or a list of them.

Translation of a list of pairs just repeats the process for each pair, doing either the Nth character or Nth string mapping as per that pair's key.

how .trans works with 'conflicting' keys

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


I'll need to explore what lizmat now thinks and what she then meant when she said the following in her earlier answer about .trans:

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.


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

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

It means that the (single) .key attribute of a pair passed to .trans stores a list of strings rather than a single string, and likewise for the pair's single .value attribute.

like image 128
raiph Avatar answered Sep 22 '22 14:09

raiph