Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in Perl6

I have difficulty figuring out why the statement

say "\c500";

produces the character 'Ǵ' on my screen as expected, while the following statements give me an error message at compile time ("Unrecognized \c character"):

my $i = 500;
say "\c$i";

even though

say "$i"; # or 'say $i.Str;' for that matter

produces "500" (with "$i".WHAT indicating type Str).

like image 912
ozzy Avatar asked Apr 21 '18 17:04

ozzy


2 Answers

You'll have to use $i.chr, which is documented here. \c is handled specially within strings, and does not seem to admit anything that is not a literal.

like image 150
jjmerelo Avatar answered Nov 08 '22 01:11

jjmerelo


The string literal parser in Perl 6 is a type of domain specific language.

Basically what you write gets compiled similarly to the rest of the language.

"abc$_"
&infix:«~»('abc',$_.Str)

In the case of \c500, you could view it as a compile-time constant.

"\c500"
(BEGIN 500.chr)

Actually it is more like:

(BEGIN 500.HOW.find_method_qualified(Int,500,'chr').(500))

Except that the compiler for string literals actually tries to compile it to an abstract syntax tree, but is unable to because there hasn't been code added to handle this case of \c.
Even if there was, \c is effectively compiled to run at BEGIN time, which is before $_ has a value.


Also \c is used for more than .chr

"\c9" eq "\c[TAB]" eq "\cI" eq "\t"

(Note that \cI represents the character you would get by typing Cntrl+Alt+i on a posix platform)

So which of these should \c$_ compile to?

$_.chr
$_.parse-names
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.index($_).succ.chr

If you want .chr you can write it as one of the following. (spaces added where they are allowed)

"abc$_.chr( )def"
"abc{ $_.chr }def"
"abc{ .chr }def"
'abc' ~ $_.chr ~ 'def'
like image 29
Brad Gilbert Avatar answered Nov 08 '22 03:11

Brad Gilbert