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)
(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.
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"
.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With