7

I can't find a way to translate using trans a single quote to a escaped single quote:

say ($ = "'well done'").=trans("'" => "\\\'" ) ;# OUTPUT: «\well done\␤»
say ($ = "'well done'").=trans(<'> => Q [\'] ) ;# OUTPUT: «\well done\␤»
say ($ = "'well done'").=trans("'" => q"\\\'" );# OUTPUT: «\well done\␤»

There's probably a workaround using split or any number of other things, including subst. In principle, the first one actually produces \', which is what I've been looking for. Maybe doubling up the scapes will help?

Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105
jjmerelo
  • 22,578
  • 8
  • 40
  • 86
  • 2
    Hmm. An opportunity to try out [a doc I wrote on trans about a month ago](https://gist.github.com/raiph/a9d58825662b5cf2da2cc550cb3c6989). I'll post this comment then go read it and see if I understand it and if it provides insight into your question... :) – raiph Oct 06 '18 at 20:31
  • 1
    OK. I see a natural solution. (Make matcher and replacer be lists.) And now I see Liz has suggested that. Nice to know I could get to the answer fairly quickly. :) – raiph Oct 06 '18 at 20:40
  • You might be better off using a global `subst` instead – Jo King Oct 08 '18 at 04:55

1 Answers1

5

I guess this is a gotcha with trans, but you actually need to specify a "from" list and a "to" list, otherwise it will just interpret the left side as a range of graphemes to be translated into the other range of graphemes:

say "'well done'".trans("abcde" => "vwxyz" );  # OUTPUT: 'wzll yonz'

If you create a list of strings to convert from one to the other, you get the desired result:

say "'well done'".trans(["'"] => ["\\'"] )  # OUTPUT: \'well done\'
Elizabeth Mattijsen
  • 25,654
  • 3
  • 75
  • 105