Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl 6: Backslashes in transliteration (tr///)

I noticed while experimenting with tr///, that it doesn't seem to translate backslashes, even when escaped. For example,

say TR"\^/v"." given 'v^/\\';
say TR"\\^/v"." given 'v^/\\';
say TR"\ ^/v"." given 'v^/\\';

All of them output ...\ rather than what I expected, ....

There's some other weird behaviour too, like \ seemingly only escaping lowercase letters, but the docs page doesn't have much information... What exactly is the behaviour of backslashes (\) in transliteration (tr///)?

like image 267
Jo King Avatar asked Oct 26 '18 11:10

Jo King


2 Answers

There is a bug caused by backslashes getting swallowed instead of correctly escaping things in the grammar for tr///.

say TR/\\// given '\\'
===SORRY!=== Error while compiling:
Malformed replacement part; couldn't find final /
at line 2
------> <BOL>⏏<EOL>

I have raised https://github.com/rakudo/rakudo/issues/2456 and submitted https://github.com/rakudo/rakudo/pull/2457 which fixes it.

The second part of the answer is that Perl 6 tries quite hard in some quoting constructs to only interpret \ as an escape for valid escape sequences, i.e. \n, \r, \s, \', etc. Otherwise it is left as a literal \.

like image 82
donaldh Avatar answered Oct 22 '22 06:10

donaldh


I do not have an explanation for the observed problem. However, when you use the Perl 6 Str.trans method it looks like it's working as expected:

say 'v^/\\'.trans( "\\^/v" => "." );

Outputs:

....

Reference:

  • https://perl6advent.wordpress.com/2010/12/21/day-21-transliteration-and-beyond/
like image 3
wp78de Avatar answered Oct 22 '22 04:10

wp78de