ozzy
ozzy

Reputation: 785

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).

Upvotes: 5

Views: 320

Answers (2)

Brad Gilbert
Brad Gilbert

Reputation: 34120

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'

Upvotes: 5

jjmerelo
jjmerelo

Reputation: 23517

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.

Upvotes: 6

Related Questions