The Q lang§

Strings are usually represented in Raku code using some form of quoting construct. The most minimalistic of these is Q, usable via the shortcut 「…」, or via Q followed by any pair of delimiters surrounding your text, including many Unicode pairs. Most of the time, though, the most you'll need is '…' or "…", described in more detail in the following sections.

For information about quoting as applied in regexes, see the regular expression documentation.

Literal strings: Q§

Q[A literal string]
More plainly.
Q^Almost any non-word character can be a delimiter!^
QDelimiters can be repeated/nested if they are adjacent.
QQuoting with fancy unicode pairs

Delimiters can be nested, but in the plain Q form, backslash escapes aren't allowed. In other words, basic Q strings are as literal as possible.

Some delimiters are not allowed immediately after Q, q, or qq. Any characters that are allowed in identifiers are not allowed to be used, since in such a case, the quoting construct together with such characters are interpreted as an identifier. In addition, ( ) is not allowed because that is interpreted as a function call. If you still wish to use those characters as delimiters, separate them from Q, q, or qq with a space. Please note that some natural languages use a left delimiting quote on the right side of a string. Q will not support those as it relies on unicode properties to tell left and right delimiters apart.

Q'this will not work!'
Q(this won't work either!)

The examples above will produce an error. However, this will work

Q (this is fine, because of space after Q)
Q 'and so is this'
Q<Make sure you <match> opening and closing delimiters>
Q{This is still a closing curly brace → \}

These examples produce:

this is finebecause of space after Q
and so is this
Make sure you <match> opening and closing delimiters
This is still a closing curly brace → \

The behavior of quoting constructs can be modified with adverbs, as explained in detail in later sections.

ShortLongMeaning
:x:execExecute as command and return results
:w:wordsSplit result on words (no quote protection)
:ww:quotewordsSplit result on words (with quote protection)
:q:singleInterpolate \\, \qq[...] and escaping the delimiter with \
:qq:doubleInterpolate with :s, :a, :h, :f, :c, :b
:s:scalarInterpolate $ vars
:a:arrayInterpolate @ vars (when followed by postcircumfix)
:h:hashInterpolate % vars (when followed by postcircumfix)
:f:functionInterpolate & calls
:c:closureInterpolate {...} expressions
:b:backslashEnable backslash escapes (\n, \qq, \$foo, etc)
:to:heredocParse result as heredoc terminator
:v:valConvert to allomorph if possible

These adverbs can be used together with Q, so that it will interpolate even if the quoting operator does not:

my %þ = :is-mighty;
say Q "Þor %þ<>";                         # OUTPUT: «Þor %þ<>␤» 
say Q:h"Þor %þ<>";                        # OUTPUT: «Þor is-mighty   True␤» 
%þ = :42foo, :33bar;
say Q:h:c "Þor %þ<> →  { [+] %þ.values}"# OUTPUT: «Þor bar 33␤foo  42 →  75␤» 
my @þ= <33 44>say Q:a "Array contains @þ[]"# OUTPUT: «Array contains 33 44␤» 
say Q:v<33> + 3;                          # OUTPUT: «36␤» 

By default, and as shown, Q quotes directly without any kind of transformation of the quoted string. The adverbs will modify its behavior, converting, for instance, the string into an allomorph (with the :v adverb) or allowing interpolation of hashes (via :h) or {} code sections (via :c). Arrays and hashes must be followed by a postcircumfix; that is, the sigiled identifier will not interpolate, but followed by an indexing, decont operator or a method call with parentheses, it will:

my @þ= <33 44>;
say Q:a "Array contains @þ.elems()"# OUTPUT: «Array contains 2␤» 

The same code without the parentheses will simply not interpolate, absent the post-circumfix operator.

Escaping: q§

'Very plain';
q[This back\slash stays];
q[This back\\slash stays]# Identical output 
q{This is not a closing curly brace → \}, but this is → };
Q :q $There are no backslashes here, only lots of \$\$\$!$;
'(Just kidding. There\'s no money in that string)';
'No $interpolation {here}!';
Q:q!Just a literal "\n" here!;

The q form allows for escaping characters that would otherwise end the string using a backslash. The backslash itself can be escaped, too, as in the third example above. The usual form is '…' or q followed by a delimiter, but it's also available as an adverb on Q, as in the fifth and last example above.

These examples produce:

Very plain
This back\slash stays
This back\slash stays
This is not a closing curly brace → } but this is →
There are no backslashes here, only lots of $$$!
(Just kidding. There's no money in that string)
No $interpolation {here}!
Just a literal "\n" here

The \qq[...] escape sequence enables qq interpolation for a portion of the string. Using this escape sequence is handy when you have HTML markup in your strings, to avoid interpretation of angle brackets as hash keys:

my $var = 'foo';
say '<code>$var</code> is <var>\qq[$var.uc()]</var>';
# OUTPUT: «<code>$var</code> is <var>FOO</var>␤»

Interpolation: qq§

my $color = 'blue';
say "My favorite color is $color!"# OUTPUT: «My favorite color is blue!␤» 

The qq form – usually written using double quotes – allows for interpolation of backslash escape sequences (like q:backslash), all sigiled variables (like q:scalar:array:hash:function), and any code inside {...} (like q:closure).

Interpolating variables§

Inside a qq-quoted string, you can use variables with a sigil to trigger interpolation of the variable's value. Variables with the $ sigil are interpolated whenever the occur (unless escaped); that's why, in the example above, "$color" became blue.

Variables with other sigils, however, only trigger interpolation when you follow the variable with the appropriate postfix ([] for Arrays, <>, for Hashes, & for Subs). This allows you to write expressions like "documentation@raku.org" without interpolating the @raku variable.

To interpolate an Array (or other Positional variable), append a [] to the variable name:

my @neighbors = "Felix""Danielle""Lucinda";
say "@neighbors[] and I try our best to coexist peacefully."
# OUTPUT: «Felix Danielle Lucinda and I try our best to coexist peacefully.␤» 

Alternatively, rather than using [], you can interpolate the Array by following it with a method call with parentheses after the method name. Thus the following code will work:

say "@neighbors.join('') and I try our best to coexist peacefully."
# OUTPUT: «Felix, Danielle, Lucinda and I try our best to coexist peacefully.␤» 

However, "@example.com" produces @example.com.

To call a subroutine, use the &-sigil and follow the subroutine name with parentheses.

say "uc  'word'";  # OUTPUT: «uc  'word'»␤ 
say "&uc 'word'";  # OUTPUT: «&uc 'word'»␤ 
say "&uc('word')"# OUTPUT: «WORD»␤ 
# OUTPUT: «abcDEFghi␤»

To interpolate a Hash (or other Associative variable), use the <> postcircumfix operator.

my %h = :1st; say "abc%h<st>ghi";
# OUTPUT: «abc1ghi␤»

The way qq interpolates variables is the same as q:scalar:array:hash:function. You can use these adverbs (or their short forms, q:s:a:h:f) to interpolate variables without enabling other qq interpolations.

Interpolating closures§

Another feature of qq is the ability to interpolate Raku code from within the string, using curly braces:

my ($x$y$z= 43.53;
say "This room is {$x}m by {$y}m by {$z}m.";               # OUTPUT: «This room is 4m by 3.5m by 3m.␤» 
say "Therefore its volume should be { $x * $y * $z }m³!";  # OUTPUT: «Therefore its volume should be 42m³!␤» 

This provides the same functionality as the q:closure/q:c quoting form.

Interpolating escape codes§

The qq quoting form also interpolates backslash escape sequences. Several of these print invisible/whitespace ASCII control codes or whitespace characters:

SequenceHex ValueCharacterReference URL
\0\x0000Nulhttps://util.unicode.org/UnicodeJsps/character.jsp?a=0000
\a\x0007Belhttps://util.unicode.org/UnicodeJsps/character.jsp?a=0007
\b\x0008Backspacehttps://util.unicode.org/UnicodeJsps/character.jsp?a=0008
\e\x001BEschttps://util.unicode.org/UnicodeJsps/character.jsp?a=001B
\f\x000CForm Feedhttps://util.unicode.org/UnicodeJsps/character.jsp?a=000C
\n\x000ANewlinehttps://util.unicode.org/UnicodeJsps/character.jsp?a=000A
\r\x000DCarriage Returnhttps://util.unicode.org/UnicodeJsps/character.jsp?a=000D
\t\x0009Tabhttps://util.unicode.org/UnicodeJsps/character.jsp?a=0009

qq also supports two multi-character escape sequences: \x and \c. You can use \x or \x[] with the hex-code of a Unicode character or a list of characters:

my $s = "I \x2665 Raku!";
say $s;
# OUTPUT: «I ♥ Raku!␤» 
 
$s = "I really \x[2661,2665,2764,1f495] Raku!";
say $s;
# OUTPUT: «I really ♡♥❤💕 Raku!␤»

You can also create a Unicode character with \c and that character's unicode name , named sequences or name alias:

my $s = "Camelia \c[BROKEN HEART] my \c[HEAVY BLACK HEART]!";
say $s;
# OUTPUT: «Camelia 💔 my ❤!␤»

See the description of \c[] on the Unicode documentation page for more details.

qq provides the same interpolation of escape sequences as that provided by q:backslash/q:b.

preventing interpolation and handling missing values§

You can prevent any undesired interpolation in a qq-quoted string by escaping the sigil or other initial character:

say "The \$color variable contains the value '$color'"# OUTPUT: «The $color variable contains the value 'blue'␤» 

Interpolation of undefined values will raise a control exception that can be caught in the current block with CONTROL.

sub niler {Nil};
my Str $a = niler;
say("$a.html""sometext");
say "alive"# this line is dead code 
CONTROL { .die };

Word quoting: qw §

qw|! @ # $ % ^ & * \| < > | eqv '! @ # $ % ^ & * | < >'.words.list; 
q:w { [ ] \{ \} }           eqv ('['']''{''}');
Q:w | [ ] { } |             eqv ('['']''{''}');

The :w form, usually written as qw, splits the string into "words". In this context, words are defined as sequences of non-whitespace characters separated by whitespace. The q:w and qw forms inherit the interpolation and escape semantics of the q and single quote string delimiters, whereas Qw and Q:w inherit the non-escaping semantics of the Q quoter.

This form is used in preference to using many quotation marks and commas for lists of strings. For example, where you could write:

my @directions = 'left''right,''up''down';

It's easier to write and to read this:

my @directions = qw|left right up down|;

Word quoting: < > §

say <a b c> eqv ('a''b''c');   # OUTPUT: «True␤» 
say <a b 42> eqv ('a''b''42'); # OUTPUT: «False␤», the 42 became an IntStr allomorph 
say < 42 > ~~ Int# OUTPUT: «True␤» 
say < 42 > ~~ Str# OUTPUT: «True␤» 

The angle brackets quoting is like qw, but with extra feature that lets you construct allomorphs or literals of certain numbers:

say <42 4/2 1e6 1+1i abc>.raku;
# OUTPUT: «(IntStr.new(42, "42"), RatStr.new(2.0, "4/2"), NumStr.new(1000000e0, "1e6"), ComplexStr.new(<1+1i>, "1+1i"), "abc")␤»

To construct a Rat or Complex literal, use angle brackets around the number, without any extra spaces:

say <42/10>.^name;   # OUTPUT: «Rat␤» 
say <1+42i>.^name;   # OUTPUT: «Complex␤» 
say < 42/10 >.^name# OUTPUT: «RatStr␤» 
say < 1+42i >.^name# OUTPUT: «ComplexStr␤»

Compared to 42/10 and 1+42i, there's no division (or addition) operation involved. This is useful for literals in routine signatures, for example:

sub close-enough-π (<355/113>{
    say "Your π is close enough!"
}
close-enough-π 710/226# OUTPUT: «Your π is close enough!␤» 
# WRONG: can't do this, since it's a division operation 
sub compilation-failure (355/113{}

Word quoting with quote protection: qww§

The qw form of word quoting will treat quote characters literally, leaving them in the resulting words:

say qw{"a b" c}.raku# OUTPUT: «("\"a", "b\"", "c")␤»

Using the qww variant allows you to use quote characters for embedding strings in the word quoting structure:

say qww{"a b" c}.raku# OUTPUT: «("a b", "c")␤»

Other kinds of quotes are also supported with their usual semantics:

my $one = 'here';
my $other = 'there';
say qww{ ’this and that’ “$one or $other” 「infinity and beyond」 }.raku;
# OUTPUT: «("this and that", "here or there", "infinity and beyond")␤»

The delimiters of embedded strings are always considered word splitters:

say qww{'alpha'beta'gamma' 'delta'"epsilon"}.raku# OUTPUT: «("alpha", "beta", "gamma", "delta", "epsilon")␤»

Word quoting with interpolation: qqw§

The qw form of word quoting doesn't interpolate variables:

my $a = 42say qw{$a b c};  # OUTPUT: «$a b c␤»

Thus, if you wish for variables to be interpolated within the quoted string, you need to use the qqw variant:

my $a = 42;
my @list = qqw{$a b c};
say @list;                # OUTPUT: «[42 b c]␤»

Note that variable interpolation happens before word splitting:

my $a = "a b";
my @list = qqw{$a c};
.say for @list# OUTPUT: «a␤b␤c␤»

Word quoting with interpolation and quote protection: qqww§

The qqw form of word quoting will treat quote characters literally, leaving them in the resulting words:

my $a = 42say qqw{"$a b" c}.raku;  # OUTPUT: «("\"42", "b\"", "c")␤»

Using the qqww variant allows you to use quote characters for embedding strings in the word quoting structure:

my $a = 42say qqww{"$a b" c}.raku# OUTPUT: «("42 b", "c")␤»

The delimiters of embedded strings are always considered word splitters:

say qqww{'alpha'beta'gamma' 'delta'"epsilon"}.raku# OUTPUT: «("alpha", "beta", "gamma", "delta", "epsilon")␤»

Unlike the qqw form, interpolation also always splits (except for interpolation that takes place in an embedded string):

my $time = "now";
$_ = 'ni';
my @list = qqww<$time$time {6*7}{7*6} "$_$_">;
.say for @list# OUTPUT: «now␤now␤42␤42␤nini␤»

Quote protection happens before interpolation, and interpolation happens before word splitting, so quotes coming from inside interpolated variables are just literal quote characters:

my $a = "1 2";
say qqww{"$a$a}.raku# OUTPUT: «("1 2", "1", "2")␤» 
my $b = "\"2 3\"";
say qqww{"$b$b}.raku# OUTPUT: «("1 \"2 3\"", "1", "\"2", "3\"")␤»

Word quoting with interpolation and quote protection: « »§

This style of quoting is like qqww, but with the added benefit of constructing allomorphs (making it functionally equivalent to qq:ww:v). The ASCII equivalent to « » are double angle brackets << >>.

# Allomorph Construction 
my $a = 42say «  $a b c    ».raku;  # OUTPUT: «(IntStr.new(42, "42"), "b", "c")␤» 
my $a = 42say << $a b c   >>.raku;  # OUTPUT: «(IntStr.new(42, "42"), "b", "c")␤» 
 
# Quote Protection 
my $a = 42say «  "$a b" c  ».raku;  # OUTPUT: «("42 b", "c")␤» 
my $a = 42say << "$a b" c >>.raku;  # OUTPUT: «("42 b", "c")␤»

Shell quoting: qx§

To run a string as an external program, not only is it possible to pass the string to the shell or run functions but one can also perform shell quoting. There are some subtleties to consider, however. qx quotes don't interpolate variables. Thus

my $world = "there";
say qx{echo "hello $world"}

prints simply hello. Nevertheless, if you have declared an environment variable before calling raku, this will be available within qx, for instance

WORLD="there" raku
> say qx{echo "hello $WORLD"}

will now print hello there.

The result of calling qx is returned, so this information can be assigned to a variable for later use:

my $output = qx{echo "hello!"};
say $output;    # OUTPUT: «hello!␤»

See also shell, run and Proc::Async for other ways to execute external commands.

Shell quoting with interpolation: qqx§

If one wishes to use the content of a Raku variable within an external command, then the qqx shell quoting construct should be used:

my $world = "there";
say qqx{echo "hello $world"};  # OUTPUT: «hello there␤»

Again, the output of the external command can be kept in a variable:

my $word = "cool";
my $option = "-i";
my $file = "/usr/share/dict/words";
my $output = qqx{grep $option $word $file};
# runs the command: grep -i cool /usr/share/dict/words 
say $output;      # OUTPUT: «Cooley␤Cooley's␤Coolidge␤Coolidge's␤cool␤...»

Be aware of the content of the Raku variable used within an external command; malicious content can be used to execute arbitrary code. See qqx traps

See also run and Proc::Async for better ways to execute external commands.

Heredocs: :to§

A convenient way to write a multi-line string literal is by using a heredoc, which lets you choose the delimiter yourself:

say q:to/END/; 
Here is
some multi-line
string
END

The contents of the heredoc always begin on the next line, so you can (and should) finish the line.

my $escaped = my-escaping-function(q:to/TERMINATOR/language => 'html'); 
Here are the contents of the heredoc.
Potentially multiple lines.
TERMINATOR

If the terminator is indented, that amount of indention is removed from the string literals. Therefore this heredoc

say q:to/END/; 
    Here is
    some multi line
        string
    END

produces this output:

Here is
some multi line
    string

Heredocs include the newline from before the terminator.

To allow interpolation of variables use the qq form, but you will then have to escape metacharacters \{ as well as $ if it is not the sigil for a defined variable. For example:

my $f = 'db.7.3.8';
my $s = qq:to/END/; 
option \{
    file "$f";
};
END
say $s;

would produce:

option {
    file "db.7.3.8";
};

Some other situations to pay attention to are innocent-looking ones where the text looks like a Raku expression. For example, the following generates an error:

my $title = 'USAFA Class of 1965';
say qq:to/HERE/;
<a href='https://usafa-1965.org'>$title</a>
HERE
# Output:
Type Str does not support associative indexing.
  in block <unit> at here.raku line 2

The angle bracket to the right of '$title' makes it look like a hash index to Raku when it is actually a Str variable, hence the error message. One solution is to enclose the scalar with curly braces which is one way to enter an expression in any interpolating quoting construct:

say qq:to/HERE/;
<a href='https://usafa-1965.org'>{$title}</a>
HERE

Another option is to escape the `<` character to avoid it being parsed as the beginning of an indexing operator:

say qq:to/HERE/;
<a href='https://usafa-1965.org'>$title\</a>
HERE

Because a heredoc can be very long but is still interpreted by Raku as a single line, finding the source of an error can sometimes be difficult. One crude way to debug the error is by starting with the first visible line in the code and treating is as a heredoc with that line only. Then, until you get an error, add each line in turn. (Creating a Raku program to do that is left as an exercise for the reader.)

You can begin multiple Heredocs in the same line. If you do so, the second heredoc will not start until after the first heredoc has ended.

my ($first$second= qq:to/END1/qq:to/END2/; 
  FIRST
  MULTILINE
  STRING
  END1
   SECOND
   MULTILINE
   STRING
   END2 
say $first;  # OUTPUT: «FIRST␤MULTILINE␤STRING␤»
say $second; # OUTPUT: «SECOND␤MULTILINE␤STRING␤»

Unquoting§

Literal strings permit interpolation of embedded quoting constructs by using the escape sequences such as these:

my $animal="quaggas";
say 'These animals look like \qq[$animal]'# OUTPUT: «These animals look like quaggas␤» 
say 'These animals are \qqw[$animal or zebras]'# OUTPUT: «These animals are quaggas or zebras␤»

In this example, \qq will do double-quoting interpolation, and \qqw word quoting with interpolation. Escaping any other quoting construct as above will act in the same way, allowing interpolation in literal strings.