Chars 7
Welcome to the official documentation of the Perl 6 programming language! Besides online browsing and searching, you can also view everything in one file or contribute by reporting mistakes or sending patches.
Language Reference & Tutorials
A collection of documents describing, in detail, the various conceptual parts of the language.
Type Reference
Index of built-in classes and roles.
Routine Reference
Index of built-in subroutines and methods.
Perl 6 Programs
A collection of documents describing how to run the Perl 6 executable program and other utilities, how to debug Perl 6 programs, and how to hack on Perl 6 source code.

The Perl 6 homepage offers a comprehensive list of Perl 6 resources, including tutorials, how-tos and FAQs (Frequently Asked Questions).

Perl 6 compiler developers may also be interested in The Perl 6 Specification. Documentation for the different but related Perl 5 language can be found on the Perl 5 documentation website.

~

2 Brief Introduction

Using Perl 6 official documentation

Documenting a large language like Perl 6 has to balance several contradictory goals, such as being brief whilst being comprehensive, catering to professional developers with wide experience whilst also being accessible to newcomers to the language.

For a quick hands-on introduction, there is a short annotated programming example.

For programmers with experience in other languages, there are a number of Migration guides that compare and contrast the features of Perl6 with other languages.

A number of Tutorials cover several areas in which Perl6 is particularly innovative. The section headers should help navigate the remaining documents.

There are a number of useful resources listed elsewhere on the perl6.org site. These include articles, books, slide presentations, and videos.

It has been found that newcommers to Perl 6 often ask questions that indicate assumptions carried over from other programming paradigms. It is suggested that the following sections in the Fundamental topics section should be reviewed first.

• Signatures - each routine, which includes subroutines and methods, has a signature. Understanding the information given in the signature of a sub or method provides a quick way to grasp the operation and effect of the routine.

• Containers - variables, which are like the nouns of a computer language, are containers in which information is stored. The first letter in the formal name of a container, such as the '$' of$my-variable, or '@' of @an-array-of-things, or '%' of %the-scores-in-the-competition, conveys information about the container. However, Perl6 is more abstract than other languages about what can be stored in a container. So, for example, a $scalar container can contain an object that is in fact an array. • Classes and Roles - Perl 6 is fundamentally based on objects, which are described in terms of classes and roles. Perl 6, unlike some languages, does not impose object-oriented programming practices, and useful programs can be written as if Perl 6 was purely procedural in nature. However, complex software, such as the Rakudo compiler of Perl 6, is made much simpler by writing in object-oriented idioms, which is why the Perl 6 documentation is more easily understood by reviewing what a class is and what a role is. Without understanding about Classes and Roles, it would be difficult to understand Types, to which a whole section of the documentation is devoted. • Traps to Avoid - Several common assumptions lead to code that does not work as the programmer intended. This section identifies some. It is worth reviewing when something doesn't quite work out. 3 Perl 6 by example P6-101 A basic introductory example of a Perl 6 program Suppose that you host a table tennis tournament. The referees tell you the results of each game in the format Player1 Player2 | 3:2, which means that Player1 won against Player2 by 3 to 2 sets. You need a script that sums up how many matches and sets each player has won to determine the overall winner. The input data (stored in a file called scores.txt) looks like this:  Beth Ana Charlie Dave Ana Dave | 3:0 Charlie Beth | 3:1 Ana Beth | 2:3 Dave Charlie | 3:0 Ana Charlie | 3:1 Beth Dave | 0:3  The first line is the list of players. Every subsequent line records a result of a match. Here's one way to solve that problem in Perl 6:  use v6; my$file  = open 'scores.txt';
my @names = $file.get.words; my %matches; my %sets; for$file.lines -> $line { next unless$line; # ignore any empty lines

my ($pairing,$result) = $line.split(' | '); my ($p1, $p2) =$pairing.words;
my ($r1,$r2)          = $result.split(':'); %sets{$p1} += $r1; %sets{$p2} += $r2; if$r1 > $r2 { %matches{$p1}++;
} else {
%matches{$p2}++; } } my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse; for @sorted ->$n {


lexical and block

my declares a lexical variable, which are visible only in the current block from the point of declaration to the end of the block. If there's no enclosing block, it's visible throughout the remainder of the file (which would effectively be the enclosing block). A block is any part of the code enclosed between curly braces { }.

string literal

'scores.txt' is a string literal. A string is a piece of text, and a string literal is a string which appears directly in the program. In this line, it's the argument provided to open.

    my @names = $file.get.words;  array, method and invocant The right-hand side calls a method --a named group of behavior-- named get on the filehandle stored in$file. The get method reads and returns one line from the file, removing the line ending. If you print the contents of $file after calling get, you will see that the first line is no longer in there. words is also a method, called on the string returned from get. words decomposes its invocant--the string on which it operates--into a list of words, which here means strings separated by whitespace. It turns the single string 'Beth Ana Charlie Dave' into the list of strings 'Beth', 'Ana', 'Charlie', 'Dave'. Finally, this list gets stored in the Array @names. The @ sigil marks the declared variable as an Array. Arrays store ordered lists.  my %matches; my %sets;  hash These two lines of code declare two hashes. The % sigil marks each variable as a Hash. A Hash is an unordered collection of key-value pairs. Other programming languages call that a hash table, dictionary, or map. You can query a hash table for the value that corresponds to a certain$key with %hash{$key}. In the score counting program, %matches stores the number of matches each player has won. %sets stores the number of sets each player has won. Both of these hashes are indexed by the player's name.  for$file.lines -> $line { ... }  for and block for produces a loop that runs the block delimited by curly brackets once for each item of the list, setting the variable$line to the current value of each iteration. $file.lines produces a list of the lines read from the file scores.txt, starting with the second line of the file since we already called$file.get once, and going all the way to the end of the file.

During the first iteration, $line will contain the string Ana Dave | 3:0; during the second, Charlie Beth | 3:1, and so on.  my ($pairing, $result) =$line.split(' | ');


my can declare multiple variables simultaneously. The right-hand side of the assignment is a call to a method named split, passing along the string ' | ' as an argument.

split decomposes its invocant into a list of strings, so that joining the list items with the separator ' | ' produces the original string.

$pairing gets the first item of the returned list, and$result the second.

After processing the first line, $pairing will hold the string Ana Dave and$result 3:0.

The next two lines follow the same pattern:

    my ($p1,$p2) = $pairing.words; my ($r1, $r2) =$result.split(':');


The first extracts and stores the names of the two players in the variables $p1 and$p2. The second extracts the results for each player and stores them in $r1 and$r2.

After processing the first line of the file, the variables contain the values: cell '0'

 Variable Contents $line 'Ana Dave | 3:0'$pairing 'Ana Dave' $result '3:0'$p1 'Ana' $p2 'Dave'$r1 '3' $r2 '0' The program then counts the number of sets each player has won:  %sets{$p1} += $r1; %sets{$p2} += $r2;  The += assignment operator is a shortcut for:  %sets{$p1} = %sets{$p1} +$r1;

fat arrow, pair and autovivification

Before these two lines execute, %sets is empty. Adding to an entry that is not in the hash yet will cause that entry to spring into existence just-in-time, with a value starting at zero. (This is autovivification). After these two lines have run for the first time, %sets contains 'Ana' => 3, 'Dave' => 0 . (The fat arrow => separates key and value in a Pair.)

    if $r1 >$r2 {
%matches{$p1}++; } else { %matches{$p2}++;
}


If $r1 is numerically larger than$r2, %matches{$p1} increments by one. If$r1 is not larger than $r2, %matches{$p2} increments. Just as in the case of +=, if either hash value did not exist previously, it is autovivified by the increment operation.

stable sort

When two array items have the same value, sort leaves them in the same order as it found them. Computer scientists call this a stable sort. The program takes advantage of this property of Perl 6's sort to achieve the goal by sorting twice: first by the number of sets won (the secondary criterion), then by the number of matches won.

After the first sorting step, the names are in the order Beth Charlie Dave Ana. After the second sorting step, it's still the same, because no one has won fewer matches but more sets than someone else. Such a situation is entirely possible, especially at larger tournaments.

sort sorts in ascending order, from smallest to largest. This is the opposite of the desired order. Therefore, the code calls the .reverse method on the result of the second sort, and stores the final list in @sorted.

    for @sorted -> $n { say "$n has won %matches{$n} matches and %sets{$n} sets";
}


say, print and put

To print out the players and their scores, the code loops over @sorted, setting $n to the name of each player in turn. Read this code as "For each element of sorted, set$n to the element, then execute the contents of the following block." say prints its arguments to the standard output (the screen, normally), followed by a newline. (Use print if you don't want the newline at the end.)

Note that say will truncate certain data structures by calling the .gist method so put is safer if you want exact output.

When you run the program, you'll see that say doesn't print the contents of that string verbatim. In place of $n it prints the contents of the variable$n-- the names of players stored in $n. This automatic substitution of code with its contents is interpolation. This interpolation happens only in strings delimited by double quotes "...". Single quoted strings '...' do not interpolate: double-quoted strings and single-quoted strings  my$names = 'things';
say 'Do not call me $names'; # OUTPUT: «Do not call me$names␤»
say "Do not call me $names"; # OUTPUT: «Do not call me things␤»  Double quoted strings in Perl 6 can interpolate variables with the$ sigil as well as blocks of code in curly braces. Since any arbitrary Perl code can appear within curly braces, Arrays and Hashes may be interpolated by placing them within curly braces.

Arrays within curly braces are interpolated with a single space character between each item. Hashes within curly braces are interpolated as a series of lines. Each line will contain a key, followed by a tab character, then the value associated with that key, and finally a newline.

Let's see an example of this now.

In this example, you will see some special syntax that makes it easier to make a list of strings. This is the <...> quote-words construct. When you put words in between the < and > they are all assumed to be strings, so you do not need to wrap them each in double quotes "..." .

    say "Math: { 1 + 2 }";                  # OUTPUT: «Math: 3␤»
my @people = <Luke Matthew Mark>;
say "The synoptics are: {@people}";     # OUTPUT: «The synoptics are: Luke Matthew Mark␤»

say "{%sets}␤";                         # From the table tennis tournament

# Charlie 4
# Dave    6
# Ana     8
# Beth    4


When array and hash variables appear directly in a double-quoted string (and not inside curly brackets), they are only interpolated if their name is followed by a postcircumfix -- a bracketing pair that follows a statement. It's also ok to have a method call between the variable name and the postcircumfix.

Zen slice

    my @flavours = <vanilla peach>;

say "we have @flavours";           # OUTPUT: «we have @flavours␤»
say "we have @flavours[0]";        # OUTPUT: «we have vanilla␤»
# so-called "Zen slice"
say "we have @flavours[]";         # OUTPUT: «we have vanilla peach␤»

# method calls ending in postcircumfix
say "we have @flavours.sort()";    # OUTPUT: «we have peach vanilla␤»

# chained method calls:
say "we have @flavours.sort.join(', ')";
# OUTPUT: «we have peach, vanilla␤»


Exercises

1. The input format of the example program is redundant: the first line containing the name of all players is not necessary, because you can find out which players participated in the tournament by looking at their names in the subsequent rows.

How can you make the program run if you do not use the @names variable? Hint: %hash.keys returns a list of all keys stored in %hash.

Answer: Remove the line my @names = $file.get.words;, and change:  my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;  ... into:  my @sorted = %sets.keys.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;  2. Instead of deleting the redundant @names variable, you can also use it to warn if a player appears that wasn't mentioned in the first line, for example due to a typo. How would you modify your program to achieve that? Hint: Try using membership operators. Answer: Change @names to @valid-players. When looping through the lines of the file, check to see that$p1 and $p2 are in @valid-players. Note that for membership operators you can also use (elem) and !(elem).  ...; my @valid-players =$file.get.words;
...;

for $file.lines ->$line {
my ($pairing,$result) = $line.split(' | '); my ($p1, $p2) =$pairing.split(' ');
if $p1 ∉ @valid-players { say "Warning: '$p1' is not on our list!";
}
if $p2 ∉ @valid-players { say "Warning: '$p2' is not on our list!";
}
...
}


~

5 Perl 5 to Perl 6 guide - in a nutshell

How do I do what I used to do? (Perl 6 in a nutshell)

This page attempts to provide a fast-path to the changes in syntax and semantics from Perl 5 to Perl 6. Whatever worked in Perl 5 and must be written differently in Perl 6, should be listed here (whereas many new Perl 6 features and idioms need not).

Hence this should not be mistaken for a beginner tutorial or a promotional overview of Perl 6; it is intended as a technical reference for Perl 6 learners with a strong Perl 5 background and for anyone porting Perl 5 code to Perl 6 (though note that #Automated translation might be more convenient).

A note on semantics; when we say "now" in this document, we mostly just mean "now that you are trying out Perl 6." We don't mean to imply that Perl 5 is now suddenly obsolete. Quite the contrary, most of us love Perl 5, and we expect Perl 5 to continue in use for a good many years. Indeed, one of our more important goals has been to make interaction between Perl 5 and Perl 6 run smoothly. However, we do also like the design decisions in Perl 6, which are certainly newer and arguably better integrated than many of the historical design decisions in Perl 5. So many of us do hope that over the next decade or two, Perl 6 will become the more dominant language. If you want to take "now" in that future sense, that's okay too. But we're not at all interested in the either/or thinking that leads to fights.

CPAN

If the module that you were using has not been converted to Perl 6, and no alternative is listed in this document, then its use under Perl 6 may not have been addressed yet.

The Inline::Perl5 project makes it possible to use Perl 5 modules directly from Perl 6 code by using an embedded instance of the perl interpreter to run Perl 5 code.

This is as simple as:

# the :from<Perl5> makes Perl 6 load Inline::Perl5 first (if installed)
# and then load the Scalar::Util module from Perl 5
use Scalar::Util:from<Perl5> <looks_like_number>;
say looks_like_number "foo";   # 0
say looks_like_number "42";    # 1


A number of Perl 5 modules have been ported to Perl 6, trying to maintain the API of these modules as much as possible, as part of the CPAN Butterfly Plan. These can be found at https://modules.perl6.org/t/CPAN5.

Many Perl 5 built-in functions (about a 100 so far) have been ported to Perl 6 with the same semantics. Think about the shift function in Perl 5 having magic shifting from @_ or @ARGV by default, depending on context. These can be found at https://modules.perl6.org/t/Perl5 as separately loadable modules, and in the P5built-ins bundle to get them all at once.

Syntax

There are a few differences in syntax between the two languages, starting with how identifiers are defined.

Identifiers

Perl 6 allows the use of dashes (-), underscores (_), apostrophes ('), and alphanumerics in identifiers, :

sub test-doesn't-hang { ... }
my $ความสงบ = 42; my \Δ = 72; say 72 - Δ; -> Method calls If you've read any Perl 6 code at all, it's immediately obvious that method call syntax now uses a dot instead of an arrow: $person->name  # Perl 5

$person.name # Perl 6  The dot notation is both easier to type and more of an industry standard. But we also wanted to steal the arrow for something else. (Concatenation is now done with the ~ operator, if you were wondering.) To call a method whose name is not known until runtime: $object->$methodname(@args); # Perl 5  $object."$methodname"(@args); # Perl 6  If you leave out the quotes, then Perl 6 expects$methodname to contain a Method object, rather than the simple string name of the method. Yes, everything in Perl 6 can be considered an object.

Whitespace

Perl 5 allows a surprising amount of flexibility in the use of whitespace, even with strict mode and warnings turned on:

# unidiomatic but valid Perl 5
say"Hello ".ucfirst  ($people [$ i]
->
name)."!"if$greeted[$i]<1;


Perl 6 also endorses programmer freedom and creativity, but balanced syntactic flexibility against its design goal of having a consistent, deterministic, extensible grammar that supports single-pass parsing and helpful error messages, integrates features like custom operators cleanly, and doesn't lead programmers to accidentally misstate their intent. Also, the practice of "code golf" is slightly de-emphasized; Perl 6 is designed to be more concise in concepts than in keystrokes.

As a result, there are various places in the syntax where whitespace is optional in Perl 5, but is either mandatory or forbidden in Perl 6. Many of those restrictions are unlikely to concern much real-life Perl code (e.g., whitespace being disallowed between the sigil and name of a variable), but there are a few that will unfortunately conflict with some Perl hackers' habitual coding styles:

• No space allowed before the opening parenthesis of an argument list.

substr ($s, 4, 1); # Perl 5 (in Perl 6 this would try to pass a single # argument of type List to substr)  substr($s, 4, 1);  # Perl 6
substr $s, 4, 1; # Perl 6 - alternative parentheses-less style  Should this really be a problem for you, then you might want to have a look at the Slang::Tuxic module in the Perl 6 ecosystem: it changes the grammar of Perl 6 in such a way that you can have a space before the opening parenthesis of an argument list. • Space is required immediately after keywords my($alpha, $beta); # Perl 5, tries to call my() sub in Perl 6  my ($alpha, $beta); # Perl 6  if($a < 0) { ... }          # Perl 5, dies in Perl 6

if ($a < 0) { ... } # Perl 6 if$a < 0 { ... }           # Perl 6, more idiomatic

while($x-- > 5) { ... } # Perl 5, dies in Perl 6  while ($x-- > 5) { ... }    # Perl 6
while $x-- > 5 { ... } # Perl 6, more idiomatic  • No space allowed after a prefix operator, or before a postfix/postcircumfix operator (including array/hash subscripts). $seen {$_} ++; # Perl 5  %seen{$_}++;   # Perl 6

• Space required before an infix operator if it would conflict with an existing postfix/postcircumfix operator.

$n<1; # Perl 5 (in Perl 6 this would conflict with postcircumfix < >)  $n < 1; # Perl 6

• However, whitespace is allowed before the period of a method call!

# Perl 5
my @books = $xml ->parse_file($file)          # some comment
->findnodes("/library/book");

# Perl 6
my @books = $xml .parse-file($file)           # some comment
.findnodes("/library/book");


However, note that you can use unspace to add whitespace in Perl 6 code in places where it is otherwise not allowed.

Sigils

In Perl 5, arrays and hashes use changing sigils depending on how they are being accessed. In Perl 6 the sigils are invariant, no matter how the variable is being used - you can think of them as part of the variable's name.

@ Array

The @ sigil is now always used with "array" variables (e.g. @months, @months[2], @months[2, 4]), and no longer for value-slicing hashes.

% Hash

The % sigil is now always used with "hash" variables (e.g. %calories, %calories<apple>, %calories<pear plum>), and no longer for key/value-slicing arrays.

& Sub

The & sigil is now used consistently (and without the help of a backslash) to refer to the function object of a named subroutine/operator without invoking it, i.e. to use the name as a "noun" instead of a "verb":

my $sub = \&foo; # Perl 5  my$sub = &foo;  # Perl 6

callback => sub { say @_ }  # Perl 5 - can't pass built-in sub directly

callback => &say            # Perl 6 - & gives "noun" form of any sub


Since Perl 6 does not allow adding/removing symbols in a lexical scope once it has finished compiling, there is no equivalent to Perl 5's undef &foo;, and the closest equivalent to Perl 5's defined &foo would be defined ::('&foo') (which uses the "dynamic symbol lookup" syntax). However, you can declare a mutable named subroutine with my &foo; and then change its meaning at runtime by assigning to &foo.

In Perl 5, the ampersand sigil can additionally be used to call subroutines in special ways with subtly different behavior compared to normal sub calls. In Perl 6 those special forms are no longer available:

• &foo(...) for circumventing a function prototype

In Perl 6 there are no prototypes, and it no longer makes a difference whether you, say, pass a literal code block or a variable holding a code object as an argument:

# Perl 5:
first_index { $_ > 5 } @values; &first_index($coderef, @values); # (disabling the prototype that parses a
# literal block as the first argument)

# Perl 6:
first { $_ > 5 }, @values, :k; # the :k makes first return an index first$coderef, @values, :k;

• &foo; and goto &foo; for re-using the caller's argument list / replacing the caller in the call stack. Perl 6 can use either callsame for re-dispatching or nextsame and nextwith, which have no exact equivalent in Perl 5.

sub foo { say "before"; &bar;     say "after" } # Perl 5

sub foo { say "before"; bar(|@_); say "after" } # Perl 6 - have to be explicit

sub foo { say "before"; goto &bar } # Perl 5

proto foo (|) {*};
multi foo ( Any $n ) { say "Any"; say$n;
};
multi foo ( Int $n ) { say "Int"; callsame; }; foo(3); # /language/functions#index-entry-dispatch_callsame  * Glob TODO: Research what exact use-cases still need typeglobs in Perl 5 today, and refactor this section to list them (with translations). In Perl 5, the * sigil referred to the GLOB structure that Perl uses to store non-lexical variables, filehandles, subs, and formats. This should not be confused with the Perl 5 built-in glob() function, which reads filenames from a directory. You are most likely to encounter a GLOB in code written on a early Perl version that does not support lexical filehandles, when a filehandle needed to be passed into a sub. # Perl 5 - ancient method sub read_2 { local (*H) = @_; return scalar(<H>), scalar(<H>); } open FILE, '<',$path or die;
my ($line1,$line2) = read_2(*FILE);


You should refactor your Perl 5 code to remove the need for the GLOB, before translating into Perl 6.

# Perl 5 - modern use of lexical filehandles
my ($fh) = @_; return scalar(<$fh>), scalar(<$fh>); } open my$in_file, '<', $path or die; my ($line1, $line2) = read_2($in_file);


And here's just one possible Perl 6 translation:

# Perl 6
sub read-n($fh,$n) {
return $fh.get xx$n;
}
my $in-file = open$path or die;

say @months[2]; # Perl 6 - @ instead of $ • Value-slicing say join ',', @months[6, 8..11]; # Perl 5 and Perl 6  • Key/value-slicing say join ',', %months[6, 8..11]; # Perl 5  say join ',', @months[6, 8..11]:kv; # Perl 6 - @ instead of %; use :kv adverb  Also note that the subscripting brackets are now a normal postcircumfix operator rather than a special syntactic form, and thus checking for existence of elements and unsetting elements is done with adverbs. {} Hash indexing/slicing Index and slice operations on hashes no longer inflect the variable's sigil, and adverbs can be used to control the type of slice. Also, single-word subscripts are no longer magically autoquoted inside the curly braces; instead, the new angle-brackets version is available which always autoquotes its contents (using the same rules as the qw// quoting construct): • Indexing say$calories{"apple"}; # Perl 5

say %calories{"apple"}; # Perl 6 - % instead of $ say$calories{apple};   # Perl 5

say %calories<apple>;   # Perl 6 - angle brackets; % instead of $say %calories«"$key"»;  # Perl 6 - double angles interpolate as a list of Str

• Value-slicing

say join ',', @calories{'pear', 'plum'}; # Perl 5

say join ',', %calories{'pear', 'plum'}; # Perl 6 - % instead of @
say join ',', %calories<pear plum>;      # Perl 6 (prettier version)
my $keys = 'pear plum'; say join ',', %calories«$keys»;          # Perl 6 the split is done after interpolation

• Key/value-slicing

say join ',', %calories{'pear', 'plum'};    # Perl 5

say join ',', %calories{'pear', 'plum'}:kv; # Perl 6 - use :kv adverb
say join ',', %calories<pear plum>:kv;      # Perl 6 (prettier version)


Also note that the subscripting curly braces are now a normal postcircumfix operator rather than a special syntactic form, and thus checking for existence of keys and removing keys is done with adverbs.

Creating references and using them

In Perl 5, references to anonymous arrays and hashes and subs are returned during their creation. References to existing named variables and subs were generated with the \ operator. the "referencing/dereferencing" metaphor does not map cleanly to the actual Perl 6 container system, so we will have to focus on the intent of the reference operators instead of the actual syntax.

my $aref = \@aaa ; # Perl 5  This might be used for passing a reference to a routine, for instance. But in Perl 6, the (single) underlying object is passed (which you could consider to be a sort of pass by reference). my @array = 4,8,15; {$_[0] = 66 }(@array);   # run the block with @array aliased to $_ say @array; # OUTPUT: «[66 8 15]␤»  The underlying Array object of @array is passed, and its first value modified inside the declared routine. In Perl 5, the syntax for dereferencing an entire reference is the type-sigil and curly braces, with the reference inside the curly braces. In Perl 6, this concept simply does not apply, since the reference metaphor does not really apply. In Perl 5, the arrow operator, -> , is used for single access to a composite's reference or to call a sub through its reference. In Perl 6, the dot operator . is always used for object methods, but the rest does not really apply. # Perl 5 say$arrayref->[7];
say $hashref->{'fire bad'}; say$subref->($foo,$bar);


In relatively recent versions of Perl 5 (5.20 and later), a new feature allows the use of the arrow operator for dereferencing: see Postfix Dereferencing. This can be used to create an array from a scalar. This operation is usually called decont, as in decontainerization, and in Perl 6 methods such as .list and .hash are used:

# Perl 5.20
use experimental qw< postderef >;
my @a = $arrayref->@*; my %h =$hashref->%*;
my @slice = $arrayref->@[3..7];  # Perl 6 my @a =$contains-an-array.list;        # or @($arrayref) my %h =$contains-a-hash.hash;          # or %($hashref)  The "Zen" slice does the same thing: # Perl 6 my @a =$contains-an-array[];
my %h = $contains-a-hash{};  See the "Containers" section of the documentation for more information. Operators See the documentation for operators for full details on all operators. Unchanged: • + Numeric Addition • - Numeric Subtraction • * Numeric Multiplication • / Numeric Division • % Numeric Modulus • ** Numeric Exponentiation • ++ Numeric Increment • -- Numeric Decrement • ! && || ^ Booleans, high-precedence • not and or xor Booleans, low-precedence • == != < > <= >= Numeric comparisons • eq ne lt gt le ge String comparisons , (Comma) List separator Unchanged, but note that in order to flatten an array variable to a list (in order to append or prefix more items) one should use the | operator (see also Slip). For instance: my @numbers = 100, 200, 300; my @more_numbers = 500, 600, 700; my @all_numbers = |@numbers, 400, |@more_numbers;  That way one can concatenate arrays. Note that one does not need to have any parentheses on the right-hand side: the List Separator takes care of creating the list, not the parentheses! <=> cmp Three-way comparisons In Perl 5, these operators returned -1, 0, or 1. In Perl 6, they return Order::Less, Order::Same, or Order::More. cmp is now named leg; it forces string context for the comparison. <=> still forces numeric context. cmp in Perl 6 does either <=> or leg, depending on the existing type of its arguments. ~~ Smartmatch operator While the operator has not changed, the rules for what exactly is matched depend on the types of both arguments, and those rules are far from identical in Perl 5 and Perl 6. See ~~ and the smartmatch operator & | ^ String bitwise ops & | ^ Numeric bitwise ops & | ^ Boolean ops In Perl 5, & | ^ were invoked according to the contents of their arguments. For example, 31 | 33 returns a different result than "31" | "33". In Perl 6, those single-character ops have been removed, and replaced by two-character ops which coerce their arguments to the needed context. # Infix ops (two arguments; one on each side of the op) +& +| +^ And Or Xor: Numeric ~& ~| ~^ And Or Xor: String ?& ?| ?^ And Or Xor: Boolean # Prefix ops (one argument, after the op) +^ Not: Numeric ~^ Not: String ?^ Not: Boolean (same as the ! op)  << >> Numeric shift left|right ops Replaced by +< and +> . say 42 << 3; # Perl 5  say 42 +< 3; # Perl 6  => Fat comma In Perl 5, => acted just like a comma, but also quoted its left-hand side. In Perl 6, => is the Pair operator, which is quite different in principle, but works the same in many situations. If you were using => in hash initialization, or in passing arguments to a sub that expects a hashref, then the usage is likely identical. sub get_the_loot { ... }; # Perl 6 stub # Works in Perl 5 and Perl 6 my %hash = ( AAA => 1, BBB => 2 ); get_the_loot( 'diamonds', { quiet_level => 'very', quantity => 9 }); # Note the curly braces If you were using => as a convenient shortcut to not have to quote part of a list, or in passing arguments to a sub that expects a flat list of KEY, VALUE, KEY, VALUE, then continuing to use => may break your code. The easiest workaround is to change the fat comma to a regular comma, and manually add quotes to its left-hand side. Or, you can change the sub's API to slurp a hash. A better long-term solution is to change the sub's API to expect Pairs; however, this requires you to change all sub calls at once. # Perl 5 sub get_the_loot { my$loot = shift;
my %options = @_;
# ...
}
# Note: no curly braces in this sub call
get_the_loot( 'diamonds', quiet_level => 'very', quantity => 9 );

# Perl 6, original API
sub get_the_loot( $loot, *%options ) { # The * means to slurp everything ... } get_the_loot( 'diamonds', quiet_level => 'very', quantity => 9 ); # Note: no curly braces in this API # Perl 6, API changed to specify valid options # The colon before the sigils means to expect a named variable, # with the key having the same name as the variable. sub get_the_loot($loot, :$quiet_level?, :$quantity = 1 ) {
# This version will check for unexpected arguments!
...
}
get_the_loot( 'diamonds', quietlevel => 'very' ); # Throws error for misspelled parameter name


? : Ternary operator

The conditional operator ? : has been replaced by ?? !!:

my $result =$score > 60 ?  'Pass' :  'Fail'; # Perl 5

my $result =$score > 60 ?? 'Pass' !! 'Fail'; # Perl 6


. (Dot) String concatenation

Replaced by the tilde.

Mnemonic: think of "stitching" together the two strings with needle and thread.

$food = 'grape' . 'fruit'; # Perl 5  $food = 'grape' ~ 'fruit'; # Perl 6


x List repetition or string repetition operator

In Perl 5, x is the Repetition operator, which behaves differently in scalar or list contexts:

• in scalar context x repeats a string;

• in list context x repeats a list, but only if the left argument is parenthesized!

Perl 6 uses two different Repetition operators to achieve the above:

• x for string repetitions (in any context);

• xx for list repetitions (in any context).

Mnemonic: x is short and xx is long, so xx is the one used for lists.

# Perl 5
print '-' x 80;             # Print row of dashes
@ones = (1) x 80;           # A list of 80 1's
@ones = (5) x @ones;        # Set all elements to 5

# Perl 6
print '-' x 80;             # Unchanged
@ones = 1 xx 80;            # Parentheses no longer needed
@ones = 5 xx @ones;         # Parentheses no longer needed


..... Two dots or three dots, range op or flipflop op

In Perl 5, .. was one of two completely different operators, depending on context.

In list context, .. is the familiar range operator. Ranges from Perl 5 code should not require translation.

In scalar context, .. and ... were the little-known Flipflop operators. They have been replaced by ff and fff.

String interpolation

In Perl 5, "${foo}s" deliminates a variable name from regular text next to it. In Perl 6, simply extend the curly braces to include the sigil too: "{$foo}s". This is in fact a very simple case of interpolating an expression.

Compound statements

These statements include conditionals and loops.

Conditionals

ifelsifelseunless

Mostly unchanged; parentheses around the conditions are now optional, but if used, must not immediately follow the keyword, or it will be taken as a function call instead. Binding the conditional expression to a variable is also a little different:

if (my $x = dostuff()) {...} # Perl 5  if dostuff() ->$x {...}      # Perl 6


(You can still use the my form in Perl 6, but it will scope to the outer block, not the inner.)

The unless conditional only allows for a single block in Perl 6; it does not allow for an elsif or else clause.

given-when

The given-when construct is like a chain of if-elsif-else statements or like the switch-case construct in e.g. C. It has the general structure:

given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}


In its simplest form, the construct is as follows:

given $value { # assigns$_
when "a match" {             # if $_ ~~ "a match" # do-something(); } when "another match" { # elsif$_ ~~ "another match"
# do-something-else();
}
default {                    # else
# do-default-thing();
}
}


This is simple in the sense that a scalar value is matched in the when statements against $_, which was set by the given. More generally, the matches are actually smartmatches on$_ such that lookups using more complex entities such as regexps can be used instead of scalar values.

Loops

whileuntil

Mostly unchanged; parentheses around the conditions are now optional, but if used, must not immediately follow the keyword, or it will be taken as a function call instead. Binding the conditional expression to a variable is also a little different:

while (my $x = dostuff()) {...} # Perl 5  while dostuff() ->$x {...}      # Perl 6


(You can still use the my form in Perl 6, but it will scope to the outer block, not the inner.)

Note that reading line-by-line from a filehandle has changed.

In Perl 5, it was done in a while loop using the diamond operator. Using for instead of while was a common bug, because the for causes the whole file to be sucked in at once, swamping the program's memory usage.

In Perl 6, for statement is lazy, so we read line-by-line in a for loop using the .lines method.

while (<IN_FH>)  { } # Perl 5

for $IN_FH.lines { } # Perl 6  Also note that in Perl 6, lines are chomped by default. dowhile/until # Perl 5 do { ... } while$x < 10;

do {
...
} until $x >= 10;  The construct is still present, but do was renamed to repeat, to better represent what the construct does: # Perl 6 repeat { ... } while$x < 10;

repeat {
...
} until $x >= 10;  forforeach Note first this common misunderstanding about the for and foreach keywords: Many programmers think that they distinguish between the C-style three-expression form and the list-iterator form; they do not! In fact, the keywords are interchangeable; the Perl 5 compiler looks for the semicolons within the parentheses to determine which type of loop to parse. The C-style three-factor form now uses the loop keyword, and is otherwise unchanged. The parentheses are still required. for ( my$i = 1; $i <= 10;$i++ ) { ... } # Perl 5

loop ( my $i = 1;$i <= 10; $i++ ) { ... } # Perl 6  The loop-iterator form is named for in Perl 6 and foreach is no longer a keyword. The for loop has the following rules: • parentheses are optional; • the iteration variable, if any, has been moved from appearing before the list, to appearing after the list and an added arrow operator; • the iteration variable is now always lexical: my is neither needed nor allowed; • the iteration variable is a read-only alias to the current list element (in Perl 5 it is a read-write alias!). If a read-write alias is required, change the -> before the iteration variable to a <->. When translating from Perl 5, inspect the use of the loop variable to decide if read-write is needed. for my$car (@cars)  {...} # Perl 5; read-write

for @cars  -> $car {...} # Perl 6; read-only for @cars <->$car   {...} # Perl 6; read-write


If the default topic $_ is being used, it is also read-write. for (@cars) {...} # Perl 5;$_ is read-write

for @cars        {...} # Perl 6; $_ is read-write for @cars <->$_ {...} # Perl 6; $_ is also read-write  It is possible to consume more than one element of the list in each iteration simply specifying more than one variable after the arrow operator: my @array = 1..10; for @array ->$first, $second { say "First is$first, second is $second"; }  each Here is the equivalent to Perl 5’s while…each(%hash) or while…each(@array) (i.e., iterating over both the keys/indices and values of a data structure) in Perl 6: while (my ($i, $v) = each(@array)) { ... } # Perl 5  for @array.kv ->$i, $v { ... } # Perl 6  while (my ($k, $v) = each(%hash)) { ... } # Perl 5  for %hash.kv ->$k, $v { ... } # Perl 6  Flow control statements Unchanged: • next • last • redo continue There is no longer a continue block. Instead, use a NEXT block (phaser) within the body of the loop. # Perl 5 my$str = '';
for (1..5) {
next if $_ % 2 == 1;$str .= $_; } continue {$str .= ':'
}

# Perl 6
my $str = ''; for 1..5 { next if$_ % 2 == 1;
$str ~=$_;
NEXT {
$str ~= ':' } }  Please note that phasers don't really need a block. This can be very handy when you don't want another scope: # Perl 6 my$str = '';
for 1..5 {
next if $_ % 2 == 1;$str ~= $_; NEXT$str ~= ':';
}


Functions

NOTE FOR EDITORS: When adding functions, please place them in alphabetical order.

Built-ins with bare blocks

Builtins that previously accepted a bare block followed, without a comma, by the remainder of the arguments will now require a comma between the block and the arguments e.g. map, grep, etc.

my @results = grep { $_ eq "bars" } @foo; # Perl 5  my @results = grep {$_ eq "bars" }, @foo; # Perl 6


delete

Turned into an adverb of the {} hash subscripting and [] array subscripting operators.

my $deleted_value = delete$hash{$key}; # Perl 5  my$deleted_value = %hash{$key}:delete; # Perl 6 - use :delete adverb  my$deleted_value = delete $array[$i];  # Perl 5

my $deleted_value = @array[$i]:delete;  # Perl 6 - use :delete adverb


exists

Turned into an adverb of the {} hash subscripting and [] array subscripting operators.

say "element exists" if exists $hash{$key};  # Perl 5

say "element exists" if %hash{$key}:exists; # Perl 6 - use :exists adverb  say "element exists" if exists$array[$i]; # Perl 5  say "element exists" if @array[$i]:exists;  # Perl 6 - use :exists adverb


Regular expressions ( regex / regexp )

Change =~ and !~ to ~~ and !~~ .

In Perl 5, matches and substitutions are done against a variable using the =~ regexp-binding op.

In Perl 6, the ~~ smartmatch op is used instead.

next if $line =~ /static/ ; # Perl 5  next if$line  ~~ /static/  ; # Perl 6

next if $line !~ /dynamic/ ; # Perl 5  next if$line !~~ /dynamic/ ; # Perl 6

$line =~ s/abc/123/; # Perl 5  $line ~~ s/abc/123/;          # Perl 6


Alternately, the new .match and .subst methods can be used. Note that .subst is non-mutating.

/(.+)/ and print $1; # Perl 5  /(.+)/ and print$0; # Perl 6


Move modifiers

Move any modifiers from the end of the regex to the beginning. This may require you to add the optional m on a plain match like /abc/.

next if $line =~ /static/i ; # Perl 5  next if$line ~~ m:i/static/  ; # Perl 6


If the actual regex is complex, you may want to use it as-is, by adding the P5 modifier.

next if $line =~ m/[aeiou]/ ; # Perl 5  next if$line ~~ m:P5/[aeiou]/   ; # Perl 6, using P5 modifier
next if $line ~~ m/ <[aeiou]> / ; # Perl 6, native new syntax  Please note that the Perl 5 regular expression syntax dates from many years ago and may lack features that have been added since the beginning of the Perl 6 project. Special matchers generally fall under the <> syntax There are many cases of special matching syntax that Perl 5 regexes support. They won't all be listed here, but often instead of being surrounded by (), the assertions will be surrounded by <>. For character classes, this means that: • [abc] becomes <[abc]> • [^abc] becomes <-[abc]> • [a-zA-Z] becomes <[a..zA..Z]> • [[:upper:]] becomes <:Upper> • [abc[:upper:]] becomes <[abc]+:Upper> For lookaround assertions: • (?=[abc]) becomes <?[abc]> • (?=ar?bitrary* pattern) becomes <before ar?bitrary* pattern> • (?!=[abc]) becomes <![abc]> • (?!=ar?bitrary* pattern) becomes <!before ar?bitrary* pattern> • (?<=ar?bitrary* pattern) becomes <after ar?bitrary* pattern> • (?<!ar?bitrary* pattern) becomes <!after ar?bitrary* pattern> For more info see lookahead assertions. (Unrelated to <> syntax, the "lookaround" /foo\Kbar/ becomes /foo <( bar )> / • (?(?{condition))yes-pattern|no-pattern) becomes [ <?{condition}> yes-pattern | no-pattern ] Longest token matching (LTM) displaces alternation In Perl 6 regexes, | does LTM, which decides which alternation wins an ambiguous match based off of a set of rules, rather than about which was written first. The simplest way to deal with this is just to change any | in your Perl 5 regex to a ||. However, if a regex written with || is inherited or composed into a grammar that uses | either by design or typo, the result may not work as expected. So when the matching process becomes complex, you finally need to have some understanding of both, especially how LTM strategy works. Besides, | may be a better choice for grammar reuse. TODO more rules. Use translate_regex.pl from Blue Tiger in the meantime. Comments As with Perl 5, comments work as usual in regexes. / word #(match lexical "word") / BEGIN, UNITCHECK, CHECK, INIT and END Except for UNITCHECK, all of these special blocks exist in Perl 6 as well. In Perl 6, these are called Phasers. But there are some differences! UNITCHECK becomes CHECK There is currently no direct equivalent of CHECK blocks in Perl 6. The CHECK phaser in Perl 6 has the same semantics as the UNITCHECK block in Perl 5: it gets run whenever the compilation unit in which it occurs, has finished parsing. This is considered a much saner semantic than the current semantics of CHECK blocks in Perl 5. But for compatibility reasons, it was impossible to change the semantics of CHECK blocks in Perl 5, so a UNITCHECK block was introduced in 5.10. So it was decided that the Perl 6 CHECK phaser would follow the saner Perl 5 UNITCHECK semantics. No block necessary In Perl 5, these special blocks must have curly braces, which implies a separate scope. In Perl 6 this is not necessary, allowing these special blocks to share their scope with the surrounding lexical scope. my$foo;             # Perl 5
BEGIN { $foo = 42 }  BEGIN my$foo = 42;  # Perl 6


Changed semantics with regards to precompilation

If you put BEGIN and CHECK phasers in a module that is being precompiled, then these phasers will only be executed during precompilation and not when a precompiled module is being loaded. So when porting module code from Perl 5, you may need to change BEGIN and CHECK blocks to INIT blocks to ensure that they're run when loading that module.

Pragmas

strict

Strict mode is now on by default.

warnings

Warnings are now on by default.

no warnings is currently NYI, but putting things in a quietly {} block will silence.

autodie

The functions which were altered by autodie to throw exceptions on error, now generally return Failures by default. You can test a Failure for definedness / truthiness without any problem. If you use the Failure in any other way, then the Exception that was encapsulated by the Failure will be thrown.

# Perl 5
open my $i_fh, '<',$input_path;  # Fails silently on error
use autodie;
open my $o_fh, '>',$output_path; # Throws exception on error

# Perl 6
my $i_fh = open$input_path,  :r; # Returns Failure on error
my $o_fh = open$output_path, :w; # Returns Failure on error


Because you can check for truthiness without any problem, you can use the result of an open in an if statement:

# Perl 6
if open($input_path,:r) ->$handle {
my int $bar = 666; say$foo * $bar; # uses native integer multiplication  lib Manipulate where modules are looked up at compile time. The underlying logic is very different from Perl 5, but in the case you are using a equivalent syntax, use lib in Perl 6 works the same as in Perl 5. mro No longer relevant. In Perl 6, method calls now always use the C3 method resolution order. If you need to find out parent classes of a given class, you can invoke the mro meta-method thusly: say Animal.^mro; # .^ indicates calling a meta-method on the object  utf8 No longer relevant: in Perl 6, source code is expected to be in utf8 encoding. vars Discouraged in Perl 5. See https://perldoc.perl.org/vars.html. You should refactor your Perl 5 code to remove the need for use vars, before translating into Perl 6. Command-line flags Unchanged: -c -e -h -I -n -p -v -V -a Change your code to use .split manually. -F Change your code to use .split manually. -l This is now the default behavior. -M-m Only -M remains. And, as you can no longer use the "no Module" syntax, the use of - with -M to "no" a module is no longer available. -E Since all features are already enabled, just use lowercase -e . -d, -dt, -d:foo, -D, etc. Replaced with the ++BUG metasyntactic option. -s Switch parsing is now done by the parameter list of the MAIN subroutine. # Perl 5 #!/usr/bin/perl -s if ($xyz) { print "$xyz\n" } ./example.pl -xyz=5 5  # Perl 6 sub MAIN( Int :$xyz ) {
say $xyz if$xyz.defined;
}

perl6 example.p6 --xyz=5
5
perl6 example.p6 -xyz=5
5

• -t

Removed.

• -P -u -U -W -X

Removed. See S19#Removed Syntactic Features.

• -w

This is now the default behavior.

• -S, -T.

This has been eliminated. Several ways to replicate "taint" mode are discussed in Reddit.

File-related operations

Reading the lines of a text file into an array

In Perl 5, a common idiom for reading the lines of a text file goes something like this:

open my $fh, "<", "file" or die "$!";
my @lines = <$fh>; # lines are NOT chomped close$fh;


In Perl 6, this has been simplified to

my @lines = "file".IO.lines;  # auto-chomped

Do not be tempted to try slurping in a file and splitting the resulting string on newlines as this will give an array with a trailing empty element, which is one more than you probably expect (it's also more complicated), e.g.:

# initialize the file to read
spurt "test-file", q:to/END/;
first line
second line
third line
END
my @lines = "test-file".IO.slurp.split(/\n/);
say @lines.elems;    #-> 4

If for some reason you do want to slurp the file first, then you can call the lines method on the result of slurp instead:

my @lines = "test-file".IO.slurp.lines;  # also auto-chomps

Capturing the standard output of executables.

Whereas in Perl 5 you would do:

my $arg = 'Hello'; my$captured = echo \Q$arg\E; my$captured = qx(echo \Q$arg\E);  Or using String::ShellQuote (because \Q…\E is not completely right): my$arg = shell_quote 'Hello';
my $captured = echo$arg;
my $captured = qx(echo$arg);


In Perl 6, you will probably want to run commands without using the shell:

my $arg = 'Hello'; my$captured = run('echo', $arg, :out).out.slurp-rest; my$captured = run(«echo "$arg"», :out).out.slurp-rest; You can also use the shell if you really want to: my$arg = 'Hello';
my $captured = shell("echo$arg", :out).out.slurp-rest;
my $captured = qqx{echo$arg};

But beware that in this case there is no protection at all! run does not use the shell, so there is no need to escape the arguments (arguments are passed directly). If you are using shell or qqx, then everything ends up being one long string which is then passed to the shell. Unless you validate your arguments very carefully, there is a high chance to introduce shell injection vulnerabilities with such code.

Environment variables

Perl module library path

In Perl 5 one of the environment variables to specify extra search paths for Perl modules is PERL5LIB.

$PERL5LIB="/some/module/lib" perl program.pl  In Perl 6 this is similar, one merely needs to change a number! As you probably guessed, you just need to use PERL6LIB: $ PERL6LIB="/some/module/lib" perl6 program.p6


In Perl 5 one uses the ':' (colon) as a directory separator for PERL5LIB, but in Perl 6 one uses the ',' (comma). For example:

$export PERL5LIB=/module/dir1:/module/dir2;  but $ export PERL6LIB=/module/dir1,/module/dir2;


(Perl 6 does not recognize either the PERL5LIB or the older Perl environment variable PERLLIB.)

As with Perl 5, if you don't specify PERL6LIB, you need to specify the library path within the program via the use lib pragma:

use lib '/some/module/lib'


Note that PERL6LIB is more of a developer convenience in Perl 6 (as opposed to the equivalent usage of PERL5LIB in Perl5) and shouldn't be used by module consumers as it could be removed in the future. This is because Perl 6's module loading isn't directly compatible with operating system paths.

Misc.

'0' is True

Unlike Perl 5, a string containing nothing but zero ('0') is True. As Perl 6 has types in core, that makes more sense. This also means the common pattern:

... if defined $x and length$x; # or just length() in modern perls


In Perl 6 becomes a simple

... if $x;  dump Gone. The Perl 6 design allows for automatic transparent saving-and-loading of compiled bytecode. Rakudo supports this only for modules so far. AUTOLOAD The FALLBACK method provides similar functionality. Importing specific functions from a module In Perl 5 it is possible to selectively import functions from a given module like so: use ModuleName qw{foo bar baz};  In Perl 6 one specifies the functions which are to be exported by using the is export role on the relevant subs and all subs with this role are then exported. Hence, the following module Bar exports the subs foo and bar but not baz: unit module Bar; sub foo($a) is export { say "foo $a" } sub bar($b) is export { say "bar $b" } sub baz($z) { say "baz $z" }  To use this module, simply use Bar and the functions foo and bar will be available use Bar; foo(1); #=> "foo 1" bar(2); #=> "bar 2"  If one tries to use baz an "Undeclared routine" error is raised at compile time. So, how does one recreate the Perl 5 behaviour of being able to selectively import functions? For this one needs to define an EXPORT sub inside the module which specifies the functions to be exported and remove the module Bar statement. The module Bar now is merely a file called Bar.pm6 with the following contents: sub EXPORT(*@import-list) { my %exportable-subs = '&foo' => &foo, '&bar' => &bar, ; my %subs-to-export; for @import-list ->$import {
if grep $sub-name, %exportable-subs.keys { %subs-to-export{$sub-name} = %exportable-subs{$sub-name}; } } return %subs-to-export; } sub foo($a, $b,$c) { say "foo, $a,$b, $c" } sub bar($a) { say "bar, $a" } sub baz($z) { say "baz, $z" }  Note that the subs are no longer explicitly exported via the is export role. We are defining an EXPORT sub which specifies the subs in the module we want to be available for export and then we are populating a hash containing the subs which will actually be exported. The @import-list is set by the use statement in the calling code thus allowing us to selectively import the subs made available by the module. So, to import only the foo routine, we do the following in the calling code: use Bar <foo>; foo(1); #=> "foo 1"  Here we see that even though bar is able to be exported, if we don't explicitly import it, it's not available for use. Hence this causes an "Undeclared routine" error at compile time: use Bar <foo>; foo(1); bar(5); #!> "Undeclared routine: bar used at line 3"  however, this will work use Bar <foo bar>; foo(1); #=> "foo 1" bar(5); #=> "bar 5"  Note also that baz remains unimportable even if specified in the use statement: use Bar <foo bar baz>; baz(3); #!> "Undeclared routine: baz used at line 2"  In order to get this to work, one obviously has to jump through many hoops. In the standard use-case where one specifies the functions to be exported via the is export role, Perl 6 automatically creates the EXPORT sub in the correct manner for you, so one should consider very carefully whether or not writing one's own EXPORT routine is worthwhile. Importing groups of specific functions from a module If you would like to export groups of functions from a module, you just need to assign names to the groups, and the rest will work automagically. When you specify is export in a sub declaration, you are in fact adding this subroutine to the :DEFAULT export group. But you can add a subroutine to another group, or to multiple groups: unit module Bar; sub foo() is export { } # added by default to :DEFAULT sub bar() is export(:FNORBL) { } # added to the FNORBL export group sub baz() is export(:DEFAULT:FNORBL) { } # added to both  So now you can use the Bar module like this: use Bar; # imports foo / baz use Bar :FNORBL; # imports bar / baz use Bar :ALL; # imports foo / bar / baz  Note that :ALL is an auto-generated group that encompasses all subroutines that have an is export trait. Core modules Data::Dumper In Perl 5, the Data::Dumper module was used for serialization, and for debugging views of program data structures by the programmer. In Perl 6, these tasks are accomplished with the .perl method, which every object has. # Given: my @array_of_hashes = ( { NAME => 'apple', type => 'fruit' }, { NAME => 'cabbage', type => 'no, please no' }, ); # Perl 5 use Data::Dumper;$Data::Dumper::Useqq = 1;
print Dumper \@array_of_hashes; # Note the backslash.

# Perl 6
say @array_of_hashes.perl; # .perl on the array, not on its reference.


In Perl 5, Data::Dumper has a more complex optional calling convention, which allows for naming the VARs.

In Perl 6, placing a colon in front of the variable's sigil turns it into a Pair, with a key of the var name, and a value of the var value.

# Given:
my ( $foo,$bar ) = ( 42, 44 );
my @baz = ( 16, 32, 64, 'Hike!' );
# Perl 5
use Data::Dumper;
print Data::Dumper->Dump(
[     $foo,$bar, \@baz   ],
[ qw(  foo   bar   *baz ) ],
);
# Output
#    $foo = 42; #$bar = 44;
#    @baz = (
#             16,
#             32,
#             64,
#             'Hike!'
#           );

# Perl 6
say [ :$foo, :$bar, :@baz ].perl;
# OUTPUT: «["foo" => 42, "bar" => 44, "baz" => [16, 32, 64, "Hike!"]]␤»


There is also a Rakudo-specific debugging aid for developers called dd (Tiny Data Dumper, so tiny it lost the "t"). This will print the .perl representation plus some extra information that could be introspected, of the given variables on STDERR:

# Perl 6
dd $foo,$bar, @baz;
# OUTPUT: «Int $foo = 42␤Int$bar = 44␤Array @baz = [16, 32, 64, "Hike!"]␤»


Getopt::Long

Switch parsing is now done by the parameter list of the MAIN subroutine.

# Perl 5
use 5.010;
use Getopt::Long;
GetOptions(

Spesh

A functionality of the #MoarVM platform that uses runtime gathered data to improve commonly used pieces of #bytecode. It is much like a JIT compiler, except that those usually output machine code rather than bytecode.

STD

STD.pm is the "standard" Perl 6 grammar definition (see https://github.com/perl6/std/) that was used to implement Perl 6. STD.pm is no longer really a "specification" in a proscriptive sense: it's more of a guideline or model for Perl 6 implementations to follow.

Stub

Stubs define name and signature of methods whose implementation is deferred to other classes.

role Canine {
method bark { ... }          # the ... indicates a stub
}

Classes with stubs are Abstract classes.

Symbol

Fancy alternative way to denote a name. Generally used in the context of modules linking, be it in the OS level, or at the Perl 6 #Virtual_machine level for modules generated from languages targeting these VMs. The set of imported or exported symbols is called the symbol table.

Synopsis

The current human-readable description of the Perl 6 language. Still in development. Much more a community effort than the Apocalypses and Exegeses were. The current state of the language is reflected by #roast, its #test suite, not the synopses where speculative material is not always so flagged or more recent additions have not been documented. This is even more true of material that has not been yet implemented.

Syntax analysis

A syntax or syntactic analysis is equivalent to parsing a string to generate its Parse Tree.

Test suite

The Perl 6 test suite is #roast.

TheDamian

#IRC screen name for #Damian Conway, writer of the original Exegeses.

#IRC screen name for #Larry Wall, creator of Perl. The name comes from the pronunciation of #TIMTOWTDI as a word.

token

In this context, a token is a regex that does not backtrack. In general, tokens are extracted from the source program while #Lexing.

Thunk

A piece of code that isn't immediately executed, but doesn't have an independent scope.

Tight and loose precedence

In this context, tight or tighter refers to precedence rules and is the opposite of looser. Precedence rules for new terms are always expressed in relationship with other terms, so is tighter implies that operands with that operator will be grouped before operands with the looser operator. Operators with tight precedence are grouped with priority to others and are generally tighter than most others; loose exactly the opposite, so it is always convenient to be aware of the exact precedence of all operators used in an expression.

twine

A data structure used to hold a POD string with embedded formatting codes. For example:

# THIS FILE IS AUTO-GENERATED--ALL EDITS WILL BE LOST
C<foo>
=end pod
say $=pod[0].contents[0].contents.perl;  The output will be: ["", Pod::FormattingCode.new(type => "C", meta => [], config => {}, contents => ["foo"]),""]  The twine is an array with an odd number of elements beginning with a simple string, alternating with formatting code objects and simple strings, and ending with a simple string; the formatting code objects are inter twine d with the strings. The strings may be empty (as shown in the example). A twine with no formatting code will contain one simple string. Type objects A type object is an object that is used to represent a type or a class. Since in object oriented programming everything is an object, classes are objects too, which inherit from the ur-class which, in our case, is Mu. value A value is what is actually contained in a container such as a variable. Used in expressions such as lvalue, to indicate that that particular container can be assigned to. UB Stands for "Undefined Behaviour". In other words, it is something that is not explicitly specified by the language specification. Value type A type is known as a value type if it is immutable and any instance of that type is interchangeable with any other instance "of the same value"—that is, any instance constructed in the same way. An instance of a value type is often called a value (but should not be confused with #lvalues or #rvalues). For example, numbers are value types, so a number constructed one place in your program with, for instance, the literal 3 can't be changed in any way—it simply is 3—and any later use of the literal 3 can safely be pointed at the same place in memory as the first with no ill consequences. Classes doing the roles Numeric and Stringy are among a few examples of built-in value types. A value type is created by ensuring that an instance of the value type is immutable (i.e., its attributes cannot be modified after construction) and that its WHICH method returns the same thing every time an instance with the same value is constructed (and conversely returns a different thing every time an instance with a different value is constructed). The language is free to optimize based on the assumption that equivalent instances of value types are interchangeable, but you should not depend on any such optimization. For instance, if you want clone to return an instance of self, or you want instance construction to be memoized so that re-construction of a previously-constructed value always returns the same instance, you currently must override this behavior yourself. (The same would hold true of object finalization, but if your instances need special destruction behavior, you almost certainly do not actually have a value type. Values should be thought of as "timeless" and existing in some ideal form outside of your program's memory, like natural values are.) Variable A variable is a name for a container. Variable interpolation The value of variables is interpolated into strings by simply inserting that variable into the string: my$polation="polation";
say "inter$polation";# OUTPUT: «interpolation␤» This might need curly braces in case it precedes some alphanumeric characters my$inter="inter";
say "{$inter}polation"; # OUTPUT: «interpolation␤» Interpolation occurs in string context, so a valid stringification method must exist for the class. More general interpolation can be achieved using the double q quoting constructs. Virtual machine A virtual machine is the Perl compiler entity that executes the bytecode. It can optimize the bytecode or generate machine code Just in Time. Examples are #MoarVM, #Parrot (who are intended to run Perl 6) and more generic virtual machines such as JVM and Javascript. whitespace A character or group of blank characters, used to separate words. An example is the space character « ». 6model 6model is used in the MoarVM, and provides primitives used to create an object system. It is described in this presentation by Jonathan Worthington and implemented here in MoarVM. 36 Perl 6 pod An easy-to-use markup language Perl 6 pod is an easy-to-use markup language. Pod can be used for writing language documentation, for documenting programs and modules, as well as for other types of document composition. Every Pod document has to begin with =begin pod and end with =end pod. Everything between these two delimiters will be processed and used to generate documentation. # THIS FILE IS AUTO-GENERATED--ALL EDITS WILL BE LOST =begin pod :link<pod> A very simple Perl 6 Pod document =end pod  Block structure A Pod document may consist of multiple Pod blocks. There are four ways to define a block: delimited, paragraph, abbreviated, and declarator; the first three yield the same result but the fourth differs. You can use whichever form is most convenient for your particular documentation task. Delimited blocks Delimited blocks are bounded by =begin and =end markers, both of which are followed by a valid Perl 6 identifier, which is the typename of the block. Typenames that are entirely lowercase (for example: =begin head1) or entirely uppercase (for example: =begin SYNOPSIS) are reserved. =begin head1 Top Level Heading =end head1  Configuration information After the typename, the rest of the =begin marker line is treated as configuration information for the block. This information is used in different ways by different types of blocks, but is always specified using Perl6-ish option pairs. That is, any of: Value is... Specify with... Or with... Or with... List :key[$e1, $e2, ...] :key($e1, $e2, ...) :key<$e1 $e2 ...> Hash :key{$k1=>$v1,$k2=>$v2} Boolean (true) :key :key(True) :key[True] Boolean (false) :!key :key(False) :key[False] String :key<str> :key('str') :key("str") Int :key(42) :key[42] Number :key(2.3) :key[2.3] Where '$e1, $e2, ...' are list elements of type String, Int, Number, or Boolean. Lists may have mixed element types. Note that one-element lists are converted to the type of their element (String, Int, Number, or Boolean). Also note that "bigints" can be used if required. For hashes, '$k1, $k2, ...' are keys of type Str and '$v1, $v2, ...' are values of type String, Int, Number, or Boolean. Strings are delimited by single or double quotes. Whitespace is not significant outside of strings. Hash keys need not be quote-delimited unless they contain significant whitespace. Strings entered inside angle brackets become lists when whitespace is used inside the brackets. All option keys and values must, of course, be constants since Pod is a specification language, not a programming language. Specifically, option values cannot be closures. See Synopsis 2 for details of the various Perl 6 pair notations. The configuration section may be extended over subsequent lines by starting those lines with an = in the first (virtual) column followed by a whitespace character. This feature is not yet completely implemented. All configuration information currently must be provided on the same line as the =begin marker line or =for name for paragraph blocks. Paragraph blocks Paragraph blocks begin by a =for marker and end by the next Pod directive or the first blank line. The =for marker is followed by the typename of the block plus, optionally, any configuration data as in the delimited blocks described above. =for head1 Top Level Heading  Abbreviated blocks Abbreviated blocks begin by an '=' sign, which is followed immediately by the typename of the block. All following data are part of the contents of the block, thus configuration data cannot be specified for an abbreviated block. The block ends at the next Pod directive or the first blank line. =head1 Top level heading  Declarator blocks Declarator blocks differ from the others by not having a specific type, instead they are attached to some source code. Declarator blocks are introduced by a special comment: either #| or #=, which must be immediately followed by either a space or an opening bracket. If followed by a space, the block is terminated by the end of line; if followed by one or more opening brackets, the block is terminated by the matching sequence of closing brackets. Blocks starting with #| are attached to the code after them, and blocks starting with #= are attached to the code before them. Since declarator blocks are attached to source code, they can be used to document classes, roles, subroutines and in general any statement or block. The WHY method can be used on these classes, roles, subroutines etc. to return the attached Pod value. #| Base class for magicians class Magician { has Int$.level;
has Str @.spells;
}

#| Fight mechanics
sub duel(Magician $a, Magician$b) {
}
#= Magicians only, no mortals.

say Magician.WHY; # OUTPUT: «Base class for magicians␤»
say &duel.WHY.leading; # OUTPUT: «Fight mechanics␤»
say &duel.WHY.trailing; # OUTPUT: «Magicians only, no mortals.␤»


These declarations can extend multiple blocks:

#|( This is an example of stringification:
* Numbers turn into strings
* Regexes operate on said strings
* C<with> topicalizes and places result into $_ ) sub search-in-seq( Int$end, Int $number ) { with (^$end).grep( /^$number/ ) { .say for$_<>;
}
}
#=« Uses
* topic
* decont operator
»


By using a matched pair of parenthesis constructs such as () or «» the comments can extend multiple lines. This format, however, will not translate to a multi-line display by perl6 -doc.

Block types

Pod offers a wide range of standard block types.

=head1 A top level heading



Ordinary paragraphs

An ordinary paragraph consists of text that is to be formatted into a document at the current level of nesting, with whitespace squeezed, lines filled, and any special inline mark-up applied.

Ordinary paragraphs consist of one or more consecutive lines of text, each of which starts with a non-whitespace character. The paragraph is terminated by the first blank line or block directive.

For example:

=head1 This is a heading block

This is an ordinary paragraph.
Its text  will   be     squeezed     and
short lines filled. It is terminated by
the first blank line.

This is another ordinary paragraph.
Its     text    will  also be squeezed and
short lines filled. It is terminated by
the trailing directive on the next line.

This is yet another ordinary paragraph,
at the first virtual column set by the
previous directive


Ordinary paragraphs do not require an explicit marker or delimiters.

Alternatively, there is also an explicit =para marker that can be used to explicitly mark a paragraph.

=para
This is an ordinary paragraph.
Its text  will   be     squeezed     and
short lines filled.


In addition, the longer =begin para and =end para form can be used.

For example:

=begin para
This is an ordinary paragraph.
Its text  will   be     squeezed     and
short lines filled.

This is still part of the same paragraph,
which continues until an...
=end para


As demonstrated by the previous example, within a delimited =begin para and =end para block, any blank lines are preserved.

Code blocks

Code blocks are used to specify source code, which should be rendered without re-justification, without whitespace-squeezing, and without recognizing any inline formatting codes. Typically these blocks are used to show examples of code, mark-up, or other textual specifications, and are rendered using a fixed-width font.

A code block may be implicitly specified as one or more lines of text, each of which starts with a whitespace character. The implicit code block is then terminated by a blank line.

For example:

This ordinary paragraph introduces a code block:

my $name = 'John Doe'; say$name;


Code blocks can also be explicitly defined by enclosing them in =begin code and =end code

    =begin code
my $name = 'John Doe'; say$name;
=end code


I/O blocks

Pod provides blocks for specifying the input and output of programs.

The =input block is used to specify pre-formatted keyboard input, which should be rendered without re-justification or squeezing of whitespace.

The =output block is used to specify pre-formatted terminal or file output, which should also be rendered without re-justification or whitespace-squeezing.

Lists

Unordered lists

Lists in Pod are specified as a series of =item blocks.

For example:

The three suspects are:

=item  Happy
=item  Sleepy
=item  Grumpy


The three suspects are:

• Happy

• Sleepy

• Grumpy

Definition lists

Lists that define terms or commands use =defn, equivalent to the DL lists in HTML

=defn Happy
When you're not blue.

=defn Blue
When you're not happy.


will be rendered with Pod::To::HTML this way:

Happy When you're not blue.

Blue When you're not happy.

Which, for the time being, is a simple HTML paragraph, but the format might change in the future.

Multi-level lists

Lists may be multi-level, with items at each level specified using the =item1, =item2, =item3, etc. blocks.

Note that =item is just an abbreviation for =item1.

For example:

=item1  Animal
=item2     Vertebrate
=item2     Invertebrate

=item1  Phase
=item2     Solid
=item2     Liquid
=item2     Gas

• Animal

• Vertebrate

• Invertebrate

• Phase

• Solid

• Liquid

• Gas

Multi-paragraph lists

Using the delimited form of the =item block (=begin item and =end item), we can specify items that contain multiple paragraphs.

For example:

Let's consider two common proverbs:

=begin item
I<The rain in Spain falls mainly on the plain.>

This is a common myth and an unconscionable slur on the Spanish
people, the majority of whom are extremely attractive.
=end item

=begin item
I<The early bird gets the worm.>

In deciding whether to become an early riser, it is worth
considering whether you would actually enjoy annelids
for breakfast.
=end item

As you can see, folk wisdom is often of dubious value.


Let's consider two common proverbs:

• The rain in Spain falls mainly on the plain.

This is a common myth and an unconscionable slur on the Spanish people, the majority of whom are extremely attractive.

• The early bird gets the worm.

In deciding whether to become an early riser, it is worth considering whether you would actually enjoy annelids for breakfast.

As you can see, folk wisdom is often of dubious value.

Tables

Comments are useful for meta-documentation (documenting the documentation). Single-line comments use the comment keyword:

=comment Add more here about the algorithm


For multi-line comments use a delimited comment block:

=begin comment
This comment is
multi-line.
=end comment


Semantic blocks

All uppercase block typenames are reserved for specifying standard documentation, publishing, source components, or meta-information.

=NAME
=AUTHOR
=VERSION
=TITLE
=SUBTITLE


Formatting codes

Formatting codes provide a way to add inline mark-up to a piece of text.

All Pod formatting codes consist of a single capital letter followed immediately by a set of single or double angle brackets; Unicode double angle brackets may be used.

Formatting codes may nest other formatting codes.

Bold

To format a text in bold enclose it in B< >

Perl 6 is B<awesome>


Perl 6 is awesome

Italic

To format a text in italic enclose it in I< >

Perl 6 is I<awesome>


Perl 6 is awesome

Underlined

To underline a text enclose it in U< >

Perl 6 is U<awesome>


Code

To flag text as Code and treat it verbatim enclose it in C< >

C<my $var = 1; say$var;>


my $var = 1; say$var;

To create a link enclose it in L< >

A vertical bar (optional) separates label and target.

The target location can be an URL (first example) or a local POD document (second example). Local file names are relative to the base of the project, not the current document.

Perl 6 homepage L<https://perl6.org>
L<Perl 6 homepage|https://perl6.org>


Perl 6 homepage https://perl6.org

Perl 6 homepage

Structure L</language/about#Structure>


Structure

To create a link to a section in the same document:

Comments L<#Comments>


A comment is text that is never rendered.

To create a comment enclose it in Z< >

Perl 6 is awesome Z<Of course it is!>


Perl 6 is awesome

Notes

Notes are rendered as footnotes.

To create a note enclose it in N< >

Perl 6 is multi-paradigmatic N<Supporting Procedural, Object Oriented, and Functional programming>


Keyboard input

To flag text as keyboard input enclose it in K< >

Enter your name K<John Doe>


Terminal output

To flag text as terminal output enclose it in T< >

Hello T<John Doe>


Unicode

To include Unicode code points or HTML5 character references in a Pod document, enclose them in E< >

E< > can enclose a number, that number is treated as the decimal Unicode value for the desired code point. It can also enclose explicit binary, octal, decimal, or hexadecimal numbers using the Perl 6 notations for explicitly based numbers.

Perl 6 makes considerable use of the E<171> and E<187> characters.

Perl 6 makes considerable use of the E<laquo> and E<raquo> characters.

Perl 6 makes considerable use of the E<0b10101011> and E<0b10111011> characters.

Perl 6 makes considerable use of the E<0o253> and E<0o273> characters.

Perl 6 makes considerable use of the E<0d171> and E<0d187> characters.

Perl 6 makes considerable use of the E<0xAB> and E<0xBB> characters.


Perl 6 makes considerable use of the « and » characters.

Rendering Pod

HTML

In order to generate HTML from Pod, you need the Pod::To::HTML module.

If it is not already installed, install it by running the following command: zef install Pod::To::HTML

Using the terminal run the following command:

perl6 --doc=HTML input.pod6 > output.html


Markdown

In order to generate Markdown from Pod, you need the Pod::To::Markdown module.

If it is not already installed, install it by running the following command: zef install Pod::To::Markdown

Using the terminal run the following command:

perl6 --doc=Markdown input.pod6 > output.md


Text

In order to generate Text from Pod, you can use the default Pod::To::Text module.

Using the terminal, run the following command:

perl6 --doc=Text input.pod6 > output.txt


You can omit the =Text portion:

perl6 --doc input.pod6 > output.txt


You can even embed Pod directly in your program and add the traditional Unix command line "--man" option to your program with a multi MAIN subroutine like this:

multi MAIN(Bool :$man) { run$*EXECUTABLE, '--doc', $*PROGRAM; }  Now myprogram --man will output your Pod rendered as a man page. Accessing Pod In order to access Pod documentation from within a Perl 6 program it is required to use the special = twigil, as documented in the variables section. The = twigil provides the introspection over the Pod structure, providing a Pod::Block tree root from which it is possible to access the whole structure of the Pod document. As an example, the following piece of code introspects its own Pod documentation: # THIS FILE IS AUTO-GENERATED--ALL EDITS WILL BE LOST =begin pod :link<pod> =head1 This is an head1 title This is a paragraph. =head2 Subsection Here some text for the subsection. =end pod for$=pod -> $pod-item { for$pod-item.contents -> $pod-block {$pod-block.perl.say;
}
}


producing the following output:

Pod::Heading.new(level => 1, config => {}, contents => [Pod::Block::Para.new(config => {}, contents => ["This is an head1 title"])]);
Pod::Block::Para.new(config => {}, contents => ["This is a paragraph."]);
Pod::Heading.new(level => 2, config => {}, contents => [Pod::Block::Para.new(config => {}, contents => ["Subsection"])]);
Pod::Block::Para.new(config => {}, contents => ["Here some text for the subsection."]);


37 Pod 6 tables

The good, the bad and the ugly

The official specification for Perl 6 POD tables is located in the Documentation specification here: Tables. Although Pod 6 specifications are not completely handled properly yet, several projects are ongoing to correct the situation; one such project is ensuring the proper handling of Pod 6 tables.

As part of that effort, this document explains the current state of Pod 6 tables by example: valid tables, invalid tables, and ugly tables (i.e., valid tables that, because of sloppy construction, may result in something different than the user expects).

Restrictions

1. The only valid column separators are either visible (' | ' or ' + ') (note at least one space is required before and after the visible column separators) or invisible [two or more contiguous whitespace (WS) characters (e.g., '  ')]. Column separators are not normally recognized as such at the left or right side of a table, but one on the right side may result in one or more empty cells depending upon the number of the cells in other rows. (Note that a pipe or plus character meant as part of cell data will result in an unintended extra column unless the character is escaped with a backslash, e.g., '\|' or '\+'.)

2. Mixing visible and invisible column separators in the same table is illegal.

3. The only valid row separator characters are '_', '-', '+', ' ', '|', and '='.

4. Consecutive interior row-separator lines are illegal.

5. Leading and trailing row-separator lines generate a warning.

6. Formatting blocks in table cells currently are ignored and treated as plain text.

HINT: During development, use of the environment variable RAKUDO_POD6_TABLE_DEBUG will show you how Rakudo interprets your pod tables before they are passed to renderers such as Pod::To::HTML, Pod::To::Text, and Pod::To::Markdown.

Best practices

HINT: Not adhering to the following best practices may require more table processing due to additional looping over table rows.

1. Use of WS for column separators is fragile, and they should only be used for simple tables. The Ugly Tables section below illustrates the problem.

2. Align table columns and rows carefully. See the examples in later best practices.

3. Don't use visual borders on the table.

4. For tables with a heading and single- or multi-line content, use one or more contiguous equal signs ('=') as the row separator after the heading, and use one or more contiguous hyphens ('-') as the row separator in the content portion of the table. For example,

• Heading and single- or multi-line content

=begin table
hdr col 0 | hdr col 1
======================
row 0     | row 0
col 0     | col 1
----------------------
row 1     | row 1
col 0     | col 1
----------------------
=end table


=begin table
hdr col 0   | hdr col 1
======================
row 0 col 0 | row 0 col 1
row 1 col 0 | row 1 col 1
=end table


5. For tables with no header and multi-line content, use one or more contiguous hyphens ('-') as the row separator in the content portion of the table. For example,

=begin table
row 0       | row 0
col 0       | col 1
----------------------
row 1 col 0 | row 1 col 1
=end table


6. For tables with many rows and no multi-line content, using no row separators is fine. However, with one or more rows with multi-line content, it is easier to ensure proper results by using a row separator line (visible or invisible) between every content row.

7. Ensure intentionally empty cells have column separators, otherwise expect a warning about short rows being filled with empty cells. (Tables rows will always have the same number of cells as the row with the most cells. Short rows are padded on the right with empty cells and generate a warning.)

8. Adding a caption to a table is possible using the =begin table line as in this example:

=begin table :caption<My Tasks>
mow lawn
take out trash
=end table


Although not a good practice, currently there is in use an alternate method of defining a caption as shown in this example:

=begin table :config{caption => "My Tasks"}
mow lawn
take out trash
=end table


Note the alternative method of putting the caption in the config hash was necessary before the :caption method was implemented, but that method is now considered to be deprecated. The practice will generate a warning in the upcoming version 6.d, and it will raise an exception in version 6.e.

Good tables

Following are examples of valid (Good) tables (taken from the current Specification Tests).

=begin table
The Shoveller   Eddie Stevens     King Arthur's singing shovel
Blue Raja       Geoffrey Smith    Master of cutlery
Mr Furious      Roy Orson         Ticking time bomb of fury
The Bowler      Carol Pinnsler    Haunted bowling ball
=end table

=table
Constants           1
Variables           10
Subroutines         33
Everything else     57


=for table
mouse    | mice
horse    | horses
elephant | elephants


=table
Animal | Legs |    Eats
=======================
Human  +   2  +   Pizza
Shark  +   0  +    Fish


=table
Superhero     | Secret          |
| Identity        | Superpower
==============|=================|================================
The Shoveller | Eddie Stevens   | King Arthur's singing shovel


=begin table

Secret
Superhero       Identity          Superpower
=============   ===============   ===================
The Shoveller   Eddie Stevens     King Arthur's
singing shovel

Blue Raja       Geoffrey Smith    Master of cutlery

Mr Furious      Roy Orson         Ticking time bomb
of fury

The Bowler      Carol Pinnsler    Haunted bowling ball

=end table

=table
X | O |
---+---+---
| X | O
---+---+---
|   | X


=table
X   O
===========
X   O
===========
X


=begin table

foo
bar

=end table


Following are examples of invalid (Bad) tables, and they should trigger an unhandled exception during parsing.

• Mixed column separator types in the same row are not allowed:

=begin table
r0c0 +  r0c1 | r0c3
=end table

• Mixed visual and whitespace column separator types in the same table are not allowed:

=begin table
r0c0 +  r0c1 | r0c3
r1c0    r0c1   r0c3
=end table

• Two consecutive interior row separators are not allowed:

=begin table
r0c0 |  r0c1
============
============
r1c0 |  r1c1
=end table


Ugly tables

Following are examples of valid tables that are probably intended to be two columns, but the columns are not aligned well so each will parse as a single-column table.

• Unaligned columns with WS column separators:

Notice the second row has the two words separated by only one WS character, while it takes at least two adjacent WS characters to define a column separation. This is a valid table but will be parsed as a single-column table.

=begin table
r0c0    r0c1
r1c0 r0c1
=end table

• Unaligned columns with visual column separators:

Notice the second row has the two words separated by a visible character ('|') but the character is not recognized as a column separator because it doesn't have an adjacent WS character on both sides of it. Although this is a legal table, the result will not be what the user intended because the first row has two columns while the second row has only one column, and it will thus have an empty second column.

=begin table
r0c0  |  r0c1
r1c0 |r0c1
=end table


38 Terms

Perl 6 terms

Most syntactic constructs in Perl 6 can be categorized in terms and operators.

Here you can find an overview of different kinds of terms.

Literals

Int

42
12_300_00


Int literals consist of digits and can contain underscores between any two digits.

To specify a base other than ten, use the colonpair form :radix<number> .

Rat

12.34
1_200.345_678


Rat literals (rational numbers) contain two integer parts joined by a dot.

Note that trailing dots are not allowed, so you have to write 1.0 instead of 1. (this rule is important because there are infix operators starting with a dot, for example the .. Range operator).

Num

12.3e-32
3e8


Num literals (floating point numbers) consist of Rat or Int literals followed by an e and a (possibly negative) exponent. 3e8 constructs a Num with value 3 * 10**8.

Str

'a string'
'I\'m escaped!'
"I don't need to be"
"\"But I still can be,\" he said."
q|Other delimiters can be used too!|


String literals are most often created with ' or ", however strings are actually a powerful sub-language of Perl 6. See Quoting Constructs.

Regex

/ match some text /
rx/slurp \s rest (.*) $/  These forms produce regex literals. See Quoting Constructs. Pair a => 1 'a' => 'b' :identifier :!identifier :identifier<value> :identifier<value1 value2> :identifier($value)
:identifier['val1', 'val2']
:identifier{key1 => 'val1', key2 => 'value2'}
:valueidentifier
:$item :@array :%hash :&callable  Pair objects can be created either with infix:«=>» (which auto-quotes the left-hand side if it is an identifier), or with the various colon-pair forms. Those almost always start with a colon and then are followed either by an identifier or the name of an already existing variable (whose name without the sigil is used as the key and value of the variable is used as the value of the pair). There is a special form where an integer value is immediately after the colon and the key is immediately after the value. In the identifier form of a colon-pair, the optional value can be any circumfix. If it is left blank, the value is Bool::True. The value of the :!identifier form is Bool::False. If used in an argument list, all of these forms count as named arguments, with the exception of 'quoted string' =>$value .

List

()
1, 2, 3
<a b c>
«a b c»
qw/a b c/


List literals are: the empty pair of parentheses (), a comma-separated list, or several quoting constructs.

term *

Creates an object of type Whatever. See Whatever documentation for more details.

Identifier terms

There are built-in identifier terms in Perl 6, which are listed below. In addition one can add new identifier terms with the syntax:

sub term:<forty-two> { 42 };
say forty-two

or as constants:

constant forty-two = 42;
say forty-two;

term self

Inside a method, self refers to the invocant (i.e. the object the method was called on). If used in a context where it doesn't make sense, a compile-time exception of type X::Syntax::NoSelf is thrown.

term now

Returns an Instant object representing the current time. It includes leap seconds and as such a few dozen seconds larger than time:

say (now - time).Int; # OUTPUT: «37␤»

term time

Returns the current POSIX time as an Int. See now for high-resolution timestamp that includes leap seconds.

term rand

Returns a pseudo-random Num in the range 0..^1.

term π

Returns the number π, i.e., the ratio between circumference and diameter of a circle. The ASCII equivalent of π is pi.

term pi

Returns the number π, i.e., the ratio between circumference and diameter of a circle. pi is the ASCII equivalent of π.

term τ

Returns the number τ, i.e., the ratio between circumference and radius of a circle. The ASCII equivalent of τ is tau.

term tau

Returns the number τ, i.e., the ratio between circumference and radius of a circle. tau is the ASCII equivalent of τ.

term 𝑒

Returns Euler's number. The ASCII equivalent of 𝑒 is e.

term e

Returns Euler's number. e is the ASCII equivalent of 𝑒.

term i

Returns the imaginary unit (for Complex numbers).

Variables

Variables are discussed in the variable language docs.

Constants

Constants are similar to variables without a container, and thus cannot be rebound. However, their initializers are evaluated at BEGIN time:

constant speed-of-light = 299792458; # m/s
constant @foo  = 1, 2, 3;
constant &talk = &say;
talk speed-of-light²; # OUTPUT: «89875517873681764␤»
talk @foo;            # OUTPUT: «(1 2 3)␤»

Compile-time evaluation means you should be careful with using contants inside modules, which get automatically pre-compiled, and so the value of the constant would not change even between multiple executions of the program:

# Foo.pm6
unit module Foo;
constant comp-time = DateTime.now;

# The value of the constant remains the same eventhough our script
# is executed multiple times:
$perl6 -I. -MFoo -e 'say Foo::comp-time' 2018-06-17T18:18:50.021484-04:00$ perl6 -I. -MFoo -e 'say Foo::comp-time'
2018-06-17T18:18:50.021484-04:00


Constants are declared with keyword constant followed by an identifier with an optional sigil. Constants are our scoped by default.

    constant foo  = 42;
my  constant $baz = rand; our constant @foo = 1, 2, 3; constant %bar = %(:42foo, :100bar);  NOTE: if you're using the Rakudo compiler, you need version 2018.08 or newer for type constraints and auto-coercion on constants to be available. Auto-coercion on %-sigilled constants requires 6.d language, preview version of which can be enabled with the use v6.d.PREVIEW pragma An optional type constraint can be used, in which case the use of scope declarator is required: # !!WRONG!! missing scope declarator before type: Int constant bar = 42; # RIGHT: our Int constant bar = 42;  Unlike variables, you cannot parameterize @-, %-, and &-sigilled constants by specifying the parameterization type in the declarator itself: # !!WRONG!! cannot parameterize @-sigilled constant with Int our Int constant @foo = 42; # OK: parameterized types as values are fine constant @foo = Array[Int].new: 42;  The reason for the restriction is that constants with @ and % sigils default to List and Map types, which cannot be parameterized. To keep things simple and consistent, parameterization was simply disallowed in these constructs. The @-, %-, and &-sigilled constants specify implied typecheck of the given value for Positional, Associative, and Callable roles respectively. The @-sigilled constants—and as of 6.d language version, the %-sigilled constants as well—perform auto-coercion of the value if it does not pass the implied typecheck. The @-sigilled constants will coerce using method cache and %-sigilled constants coerce using method Map. constant @foo = 42; @foo.perl.say; # OUTPUT: «(42,)» constant @bar = [<a b c>]; @bar.perl.say; # OUTPUT: «["a", "b", "c"]»  use v6.d.PREVIEW; constant %foo = <foo bar>; %foo.perl.say; # OUTPUT: «Map.new((:foo("bar")))» constant %bar = {:10foo, :72bar}; %bar.perl.say; # OUTPUT: «{:bar(72), :foo(10)}» # Pair is already Associative, so it remains a Pair constant %baz = :72baz; %baz.perl.say; # OUTPUT: «:baz(72)»  For convenience and consistency reasons, you can use the binding operator ( := ) instead of the assignment operator, use backslash before sigilless name of the constant variable (same as with sigilless variables), and even omit the name of the constant entirely to have an anonymous constant. Since you can't refer to anonymous entities, you may be better off using a BEGIN phaser instead, for clarity. constant %foo := :{:42foo}; constant \foo = 42; constant = 'anon'; 39 Testing Writing and running tests in Perl 6 Testing code is an integral part of software development. Tests provide automated, repeatable verifications of code behaviour, and ensures your code works as expected. In Perl 6, the Test module provides a testing framework, used also by Perl 6's official spectest suite. The testing functions emit output conforming to the Test Anything Protocol. In general, they are used in sink context: ok check-name($meta, :$relaxed-name), "name has a hyphen rather than '::'"  but all functions also return as a Boolean if the test has been successful or not, which can be used to print a message if the test fails: ok check-name($meta, :$relaxed-name), "name has a hyphen rather than '::'" \ or diag "\nTo use hyphen in name, pass :relaxed-name to meta-ok\n";  Writing tests As with any Perl project, the tests live under the t directory in the project's base directory. A typical test file looks something like this: use v6.c; use Test; # a Standard module included with Rakudo use lib 'lib'; plan$num-tests;

# .... tests

done-testing;  # optional with 'plan'


We ensure that we're using Perl 6, via the use v6.c pragma, then we load the Test module and specify where our libraries are. We then specify how many tests we plan to run (such that the testing framework can tell us if more or fewer tests were run than we expected) and when finished with the tests, we use done-testing to tell the framework we are done.

Note that routines in Test module are not thread-safe. This means you should not attempt to use the testing routines in multiple threads simultaneously, as the TAP output might come out of order and confuse the program interpreting it.

There are no current plans to make it thread safe. If threaded-testing is crucial to you, you may find some suitable ecosystem modules to use instead of Test for your testing needs.

Running tests

Tests can be run individually by specifying the test filename on the command line:

$perl6 t/test-filename.t  Or via the prove command from Perl 5, where using --exec to specify the executable that runs the tests: $ prove --exec perl6 -r t


To abort the test suite upon first failure, set the PERL6_TEST_DIE_ON_FAIL environmental variable:

$PERL6_TEST_DIE_ON_FAIL=1 perl6 t/test-filename.t  The same variable can be used within the test file. Set it before loading the Test module: BEGIN %*ENV<PERL6_TEST_DIE_ON_FAIL> = 1; use Test; ... Test plans Tests plans use plan for declaring how many plans are going to be done or, as might be the case, skipped. If no plan is declared, done-testing is used to declare the end of the tests. Testing return values The Test module exports various functions that check the return value of a given expression and produce standardized test output. In practice, the expression will often be a call to a function or method that you want to unit-test. ok and nok will match True and False. However, where possible it's better to use one of the specialized comparison test functions below, because they can print more helpful diagnostics output in case the comparison fails. By string comparison is and nok test for equality using the proper operator, depending on the object (or class) it's handled. By approximate numeric comparison is-approx compares numbers with a certain precision, which can be absolute or relative. It can be useful for numeric values whose precision will depend on the internal representation. By structural comparison Structures can be also compared using is-deeply, which will check that internal structures of the objects compared is the same. By arbitrary comparison You can use any kind of comparison with cmp-ok, which takes as an argument the function or operator that you want to be used for comparing. By object type isa-ok tests whether an object is of a certain type. By method name can-ok is used on objects to check whether they have that particular method. By role • does-ok($variable, $role,$description?)

does-ok checks whether the given variable can do a certain Role.

By regex

like and unlike check using regular expressions; in the first case passes if a match exists, in the second case when it does not.

Testing modules

Modules are temptatively loaded with use-ok, which fails if they fail to load.

Testing exceptions

dies-ok and lives-ok are opposites ways of testing code; the first checks that it throws an exception, the second that it does not; throws-like checks that the code throws the specific exception it gets handed as an argument; fails-like, similarly, checks if the code returns a specific type of Failure. eval-dies-ok and eval-lives-ok work similarly on strings that are evaluated prior to testing.

Grouping tests

The result of a group of subtests is only ok if all subtests are ok; they are grouped using subtest.

Skipping tests

Sometimes tests just aren't ready to be run, for instance a feature might not yet be implemented, in which case tests can be marked as todo. Or it could be the case that a given feature only works on a particular platform - in which case one would skip the test on other platforms; skip-rest will skip the remaining tests instead of a particular number given as argument; bail-out will simply exit the tests with a message.

Manual control

If the convenience functionality documented above does not suit your needs, you can use the following functions to manually direct the test harness output; pass will say a test has passed, and diag will print a (possibly) informative message.

40 Traps to avoid

Traps to avoid when getting started with Perl 6

When learning a programming language, possibly with the background of being familiar with another programming language, there are always some things that can surprise you and might cost valuable time in debugging and discovery.

This document aims to show common misconceptions in order to avoid them.

During the making of Perl 6 great pains were taken to get rid of warts in the syntax. When you whack one wart, though, sometimes another pops up. So a lot of time was spent finding the minimum number of warts or trying to put them where they would rarely be seen. Because of this, Perl 6's warts are in different places than you may expect them to be when coming from another language.

Variables and constants

Constants are computed at compile time

Constants are computed at compile time, so if you use them in modules keep in mind that their values will be frozen due to pre-compilation of the module itself:

# WRONG (most likely):
unit module Something::Or::Other;
constant $config-file = "config.txt".IO.slurp;  The$config-file will be slurped during pre-compilation and changes to config.txt file won't be re-loaded when you start the script again; only when the module is re-compiled.

Avoid using a container and prefer binding a value to a variable that offers a behaviour similar to a constant, but allowing the value to get updated:

# Good; file gets updated from 'config.txt' file on each script run:
unit module Something::Or::Other;
my $config-file := "config.txt".IO.slurp;  Assigning to Nil produces a different value, usually Any Actually, assigning to Nil reverts the variable to its default value. So: my @a = 4, 8, 15, 16; @a[2] = Nil; say @a; # OUTPUT: «[4 8 (Any) 16]␤»  In this case, Any is the default value of an Array element. You can purposefully assign Nil as a default value: my %h is default(Nil) = a => Nil; say %h; # OUTPUT: «Hash %h = {:a(Nil)}␤»  Or bind a value to Nil if that is the result you want: @a[3] := Nil; say @a; # OUTPUT: «[4 8 (Any) Nil]␤»  This trap might be hidden in the result of functions, such as matches: my$result2 = 'abcdef' ~~ / dex /;
say "Result2 is { $result2.^name }"; # OUTPUT: «Result2 is Any␤»  A Match will be Nil if it finds nothing; however it assigning Nil to$result2 above will result in its default value, which is Any as shown.

Using a block to interpolate anon state vars

The programmer intended for the code to count the number of times the routine is called, but the counter is not increasing:

sub count-it { say "Count is {$++}" } count-it; count-it; # OUTPUT: # Count is 0 # Count is 0  When it comes to state variables, the block in which the vars are declared gets cloned —and vars get initialized anew— whenever that block's block is re-entered. This lets constructs like the one below behave appropriately; the state variable inside the loop gets initialized anew each time the sub is called: sub count-it { for ^3 { state$count = 0;
say "Count is $count";$count++;
}
}

count-it;
say "…and again…";
count-it;

# OUTPUT:
# Count is 0
# Count is 1
# Count is 2
# …and again…
# Count is 0
# Count is 1
# Count is 2


The same layout exists in our buggy program. The { } inside a double-quoted string isn't merely an interpolation to execute a piece of code. It's actually its own block, which is just as in the example above gets cloned each time the sub is entered, re-initializing our state variable. To get the right count, we need to get rid of that inner block, using a scalar contextualizer to interpolate our piece of code instead:

sub count-it { say "Count is $($++)" }
count-it;
count-it;

# OUTPUT:
# Count is 0
# Count is 1


Alternatively, you can also use the concatenation operator instead:

sub count-it { say "Count is " ~ $++ }  Blocks Beware of empty "blocks" Curly braces are used to declare blocks. However, empty curly braces will declare a hash. $ = {say 42;} # Block
$= {;} # Block$ = {…}       # Block
$= { } # Hash  You can use the second form if you effectively want to declare an empty block: my &does-nothing = {;}; say does-nothing(33); # OUTPUT: «Nil␤» Objects Assigning to attributes Newcomers often think that, because attributes with accessors are declared as has$.x, they can assign to $.x inside the class. That's not the case. For example class Point { has$.x;
has $.y; method double {$.x *= 2;   # WRONG
$.y *= 2; # WRONG self; } } say Point.new(x => 1, y => -2).double.x # OUTPUT: «Cannot assign to an immutable value␤»  the first line inside the method double is marked with # WRONG because$.x, short for $( self.x ), is a call to a read-only accessor. The syntax has$.x is short for something like has $!x; method x() {$!x }, so the actual attribute is called $!x, and a read-only accessor method is automatically generated. Thus the correct way to write the method double is method double {$!x *= 2;
$!y *= 2; self; }  which operates on the attributes directly. BUILD prevents automatic attribute initialization from constructor arguments When you define your own BUILD submethod, you must take care of initializing all attributes by yourself. For example class A { has$.x;
has $.y; submethod BUILD {$!y = 18;
}
}

say A.new(x => 42).x;       # OUTPUT: «Any␤»


leaves $!x uninitialized, because the custom BUILD doesn't initialize it. Note: Consider using TWEAK instead. Rakudo supports TWEAK method since release 2016.11. One possible remedy is to explicitly initialize the attribute in BUILD: submethod BUILD(:$x) {
$!y = 18;$!x := $x; }  which can be shortened to: submethod BUILD(:$!x) {
$!y = 18; }  Whitespace Whitespace in regexes does not match literally say 'a b' ~~ /a b/; # OUTPUT: «False␤»  Whitespace in regexes is, by default, considered an optional filler without semantics, just like in the rest of the Perl 6 language. Ways to match whitespace: • \s to match any one whitespace, \s+ to match at least one • ' ' (a blank in quotes) to match a single blank • \t, \n for specific whitespace (tab, newline) • \h, \v for horizontal, vertical whitespace • .ws, a built-in rule for whitespace that oftentimes does what you actually want it to do • with m:s/a b/ or m:sigspace/a b/, the blank in the regexes matches arbitrary whitespace Ambiguities in parsing While some languages will let you get away with removing as much whitespace between tokens as possible, Perl 6 is less forgiving. The overarching mantra is we discourage code golf, so don't scrimp on whitespace (the more serious underlying reason behind these restrictions is single-pass parsing and ability to parse Perl 6 programs with virtually no backtracking). The common areas you should watch out for are: Block vs. Hash slice ambiguity # WRONG; trying to hash-slice a Bool: while ($++ > 5){ .say }

# RIGHT:
while ($++ > 5) { .say } # EVEN BETTER; Perl 6 does not require parentheses there: while$++ > 5 { .say }


Reduction vs. Array constructor ambiguity

# WRONG; ambiguity with [<] meta op:
my @a = [[<foo>],];

# RIGHT; reductions cannot have spaces in them, so put one in:
my @a = [[ <foo>],];

# No ambiguity here, natural spaces between items suffice to resolve it:
my @a = [[<foo bar ber>],];


Less than vs. Word quoting/Associative indexing

# WRONG; trying to index 3 associatively:
say 3<5>4

# RIGHT; prefer some extra whitespace around infix operators:
say 3 < 5 > 4


Captures

Containers versus values in a capture

Beginners might expect a variable in a Capture to supply its current value when that Capture is later used. For example:

my $a = 2; say join ",", ($a, ++$a); # OUTPUT: «3,3␤»  Here the Capture contained the container pointed to by$a and the value of the result of the expression ++$a. Since the Capture must be reified before &say can use it, the ++$a may happen before &say looks inside the container in $a (and before the List is created with the two terms) and so it may already be incremented. Instead, use an expression that produces a value when you want a value. my$a = 2; say join ",", (+$a, ++$a); # OUTPUT: «2,3␤»


Or even simpler

my $a = 2; say "$a, {++$a}"; # OUTPUT: «2, 3␤»  The same happens in this case: my @arr; my ($a, $b) = (1,1); for ^5 { ($a,$b) = ($b, $a+$b);
@arr.push: ($a,$b);
say @arr
};


Outputs «[(1 2)]␤[(2 3) (2 3)]␤[(3 5) (3 5) (3 5)]␤.... $a and$b are not reified until say is called, the value that they have in that precise moment is the one printed. To avoid that, decontainerize values or take them out of the variable in some way before using them.

my @arr;
my ($a,$b) = (1,1);
for ^5 {
($a,$b) = ($b,$a+$b); @arr.push: ($a.item, $b.item); say @arr };  With item, the container will be evaluated in item context, its value extracted, and the desired outcome achieved. Cool tricks Perl 6 includes a Cool class, which provides some of the DWIM behaviors we got used to by coercing arguments when necessary. However, DWIM is never perfect. Especially with Lists, which are Cool, there are many methods that will not do what you probably think they do, including contains, starts-with or index. Please see some examples in the section below. Strings are not Lists, so beware indexing In Perl 6, strings are not lists of characters. One cannot iterate over them or index into them as you can with lists, despite the name of the .index routine. Lists become strings, so beware .index()ing List inherits from Cool, which provides access to .index. Because of the way .index coerces a List into a Str, this can sometimes appear to be returning the index of an element in the list, but that is not how the behavior is defined. my @a = <a b c d>; say @a.index(‘a’); # 0 say @a.index('c'); # 4 -- not 2! say @a.index('b c'); # 2 -- not undefined! say @a.index(<a b>); # 0 -- not undefined!  These same caveats apply to .rindex. Lists become strings, so beware .contains() Similarly, .contains does not look for elements in the list. my @menu = <hamburger fries milkshake>; say @menu.contains('hamburger'); # True say @menu.contains('hot dog'); # False say @menu.contains('milk'); # True! say @menu.contains('er fr'); # True! say @menu.contains(<es mi>); # True!  If you actually want to check for the presence of an element, use the (cont) operator for single elements, and the superset and strict superset operators for multiple elements. my @menu = <hamburger fries milkshake>; say @menu (cont) 'fries'; # True say @menu (cont) 'milk'; # False say @menu (>) <hamburger fries>; # True say @menu (>) <milkshake fries>; # True (! NB: order doesn't matter)  If you are doing a lot of element testing, you may be better off using a Set. Numeric literals are parsed before coercion Experienced programmers will probably not be surprised by this, but Numeric literals will be parsed into their numeric value before being coerced into a string, which may create nonintuitive results. say 0xff.contains(55); # True say 0xff.contains(0xf); # False say 12_345.contains("23"); # True say 12_345.contains("2_"); # False  Getting a random item from a List A common task is to retrieve one or more random elements from a collection, but List.rand isn't the way to do that. Cool provides rand, but that first coerces the List into the number of items in the list, and returns a random real number between 0 and that value. To get random elements, see pick and roll. my @colors = <red orange yellow green blue indigo violet>; say @colors.rand; # 2.21921955680514 say @colors.pick; # orange say @colors.roll; # blue say @colors.pick(2); # yellow violet (cannot repeat) say @colors.roll(3); # red green red (can repeat)  List numify to their number of elements in numeric context You want to check whether a number is divisible by any of a set of numbers: say 42 %% <11 33 88 55 111 20325>; # OUTPUT: «True␤» What? There's no single number 42 should be divisible by. However, that list has 6 elements, and 42 is divisible by 6. That's why the output is true. In this case, you should turn the List into a Junction: say 42 %% <11 33 88 55 111 20325>.any; # OUTPUT: «any(False, False, False, False, False, False)␤» which will clearly reveal the falsehood of the divisiveness of all the numbers in the list, which will be numified separately. Arrays Referencing the last element of an array In some languages one could reference the last element of an array by asking for the "-1th" element of the array, e.g.: my @array = qw{victor alice bob charlie eve}; say @array[-1]; # OUTPUT: «eve␤»  In Perl 6 it is not possible to use negative subscripts, however the same is achieved by actually using a function, namely *-1. Thus accessing the last element of an array becomes: my @array = qw{victor alice bob charlie eve}; say @array[*-1]; # OUTPUT: «eve␤»  Yet another way is to utilize the array's tail method: my @array = qw{victor alice bob charlie eve}; say @array.tail; # OUTPUT: «eve␤» say @array.tail(2); # OUTPUT: «(charlie eve)␤»  Typed array parameters Quite often new users will happen to write something like: sub foo(Array @a) { ... }  ...before they have gotten far enough in the documentation to realize that this is asking for an Array of Arrays. To say that @a should only accept Arrays, use instead: sub foo(@a where Array) { ... }  It is also common to expect this to work, when it does not: sub bar(Int @a) { 42.say }; bar([1, 2, 3]); # expected Positional[Int] but got Array  The problem here is that [1, 2, 3] is not an Array[Int], it is a plain old Array that just happens to have Ints in it. To get it to work, the argument must also be an Array[Int]. my Int @b = 1, 2, 3; bar(@b); # OUTPUT: «42␤» bar(Array[Int].new(1, 2, 3));  This may seem inconvenient, but on the upside it moves the type-check on what is assigned to @b to where the assignment happens, rather than requiring every element to be checked on every call. Using «» quoting when you don't need it This trap can be seen in different varieties. Here are some of them: my$x = ‘hello’;
my $y = ‘foo bar’; my %h =$x => 42, $y => 99; say %h«$x»;   # ← WRONG; assumption that $x has no whitespace say %h«$y»;   # ← WRONG; splits ‘foo bar’ by whitespace
say %h«"$y"»; # ← KINDA OK; it works but there is no good reason to do that say %h{$y};   # ← RIGHT; this is what should be used

run «touch $x»; # ← WRONG; assumption that only one file will be created run «touch$y»;        # ← WRONG; will touch file ‘foo’ and ‘bar’
run «touch "$y"»; # ← WRONG; better, but has a different issue if$y starts with -
run «touch -- "$y"»; # ← KINDA OK; it works but there is no good enough reason to do that run ‘touch’, ‘--’,$y; # ← RIGHT; explicit and *always* correct
run <touch -->, $y; # ← RIGHT; < > are OK, this is short and correct  Basically, «» quoting is only safe to use if you remember to always quote your variables. The problem is that it inverts the default behavior to unsafe variant, so just by forgetting some quotes you are risking to introduce either a bug or maybe even a security hole. To stay on the safe side, refrain from using «». Strings Quotes and interpolation Interpolation in string literals can be too clever for your own good. "$foo<html></html>" # Perl 6 understands that as:
"$foo{'html'}{'/html'}"  "$foo(" ~ @args ~ ")" # Perl 6 understands that as:
"$foo(' ~ @args ~ ')"  You can avoid those problems using non-interpolating single quotes and switching to more liberal interpolation with \qq[] escape sequence: my$a = 1;
say '\qq[$a]()$b()';
# OUTPUT: «1()$b()␤»  Another alternative is to use Q:c quoter, and use code blocks {} for all interpolation: my$a = 1;
say Q:c«{$a}()$b()»;
# OUTPUT: «1()$b()␤»  Strings are not iterable There are methods that Str inherits from Any that work on iterables like lists. Iterators on strings contain one element that is the whole string. To use list-based methods like sort, reverse, you need to convert the string into a list first. say "cba".sort; # OUTPUT: «(cba)␤» say "cba".comb.sort.join; # OUTPUT: «abc␤»  .chars gets the number of graphemes, not Codepoints In Perl 6, .chars returns the number of graphemes, or user visible characters. These graphemes could be made up of a letter plus an accent for example. If you need the number of codepoints, you should use .codes. If you need the number of bytes when encoded as UTF8, you should use .encode.bytes to encode the string as UTF8 and then get the number of bytes. say "\c[LATIN SMALL LETTER J WITH CARON, COMBINING DOT BELOW]"; # OUTPUT: «ǰ̣» say 'ǰ̣'.codes; # OUTPUT: «2» say 'ǰ̣'.chars; # OUTPUT: «1» say 'ǰ̣'.encode.bytes; # OUTPUT: «4» For more information on how strings work in Perl 6, see the Unicode page. All text is normalized by default Perl 6 normalizes all text into Unicode NFC form (Normalization Form Canonical). Filenames are the only text not normalized by default. If you are expecting your strings to maintain a byte for byte representation as the original, you need to use UTF8-C8 when reading or writing to any filehandles. Allomorphs generally follow numeric semantics Str "0" is True, while Numeric is False. So what's the Bool value of allomorph <0>? In general, allomorphs follow Numeric semantics, so the ones that numerically evaluate to zero are False: say so <0>; # OUTPUT: «False␤» say so <0e0>; # OUTPUT: «False␤» say so <0.0>; # OUTPUT: «False␤» To force comparison being done for the Stringy part of the allomorph, use prefix ~ operator or the Str method to coerce the allomorph to Str, or use the chars routine to test whether the allomorph has any length: say so ~<0>; # OUTPUT: «True␤» say so <0>.Str; # OUTPUT: «True␤» say so chars <0>; # OUTPUT: «True␤» Case-insensitive comparison of strings In order to do case-insensitive comparison, you can use .fc (fold-case). The problem is that people tend to use .lc or .uc, and it does seem to work within the ASCII range, but fails on other characters. This is not just a Perl 6 trap, the same applies to other languages. say ‘groß’.lc eq ‘GROSS’.lc; # ← WRONG; False say ‘groß’.uc eq ‘GROSS’.uc; # ← WRONG; True, but that's just luck say ‘groß’.fc eq ‘GROSS’.fc; # ← RIGHT; True  If you are working with regexes, then there is no need to use .fc and you can use :i (:ignorecase) adverb instead. Pairs Constants on the left-hand side of pair notation Consider this code: enum Animals <Dog Cat>; my %h := :{ Dog => 42 }; say %h{Dog}; # OUTPUT: «(Any)␤»  The :{ … } syntax is used to create object hashes. The intentions of someone who wrote that code were to create a hash with Enum objects as keys (and say %h{Dog} attempts to get a value using the Enum object to perform the lookup). However, that's not how pair notation works. For example, in Dog => 42 the key will be a Str. That is, it doesn't matter if there is a constant, or an enumeration with the same name. The pair notation will always use the left-hand side as a string literal, as long as it looks like an identifier. To avoid this, use (Dog) => 42 or ::Dog => 42. Scalar values within Pair When dealing with Scalar values, the Pair holds the container to the value. This means that it is possible to reflect changes to the Scalar value from outside the Pair: my$v = 'value A';
my $pair = Pair.new( 'a',$v );
$pair.say; # OUTPUT: a => value A$v = 'value B';
$pair.say; # OUTPUT: a => value B  Use the method freeze to force the removal of the Scalar container from the Pair. For more details see the documentation about Pair. Sets, bags and mixes Sets, bags and mixes do not have a fixed order When iterating over this kind of objects, an order is not defined. my$set = <a b c>.Set;
.say for $set.list; # OUTPUT: «a => True␤c => True␤b => True␤» # OUTPUT: «a => True␤c => True␤b => True␤» # OUTPUT: «c => True␤b => True␤a => True␤»  Every iteration might (and will) yield a different order, so you cannot trust on a particular sequence of the elements of a set. If order does not matter, just use them that way. If it does, use sort my$set = <a b c>.Set;
.say for $set.list.sort;# OUTPUT: «a => True␤b => True␤c => True␤» In general, sets, bags and mixes are unordered, so you should not depend on them having a particular order. Operators Some operators commonly shared among other languages were repurposed in Perl 6 for other, more common, things: Junctions The ^, |, and & are not bitwise operators, they create Junctions. The corresponding bitwise operators in Perl 6 are: +^, +|, +& for integers and ?^, ?|, ?& for booleans. Exclusive sequence operator Lavish use of whitespace helps readability, but keep in mind infix operators cannot have any whitespace in them. One such operator is the sequence operator that excludes right point: ...^ (or its Unicode equivalent …^). say 1... ^5; # OUTPUT: «(1 0 1 2 3 4)␤» say 1...^5; # OUTPUT: «(1 2 3 4)␤» If you place whitespace between the ellipsis () and the caret (^), it's no longer a single infix operator, but an infix inclusive sequence operator () and a prefix Range operator (^). Iterables are valid endpoints for the sequence operator, so the result you'll get might not be what you expected. String ranges/Sequences In some languages, using strings as range end points, considers the entire string when figuring out what the next string should be; loosely treating the strings as numbers in a large base. Here's Perl 5 version: say join ", ", "az".."bc"; # OUTPUT: «az, ba, bb, bc␤»  Such a range in Perl 6 will produce a different result, where each letter will be ranged to a corresponding letter in the end point, producing more complex sequences: say join ", ", "az".."bc"; #{ OUTPUT: « az, ay, ax, aw, av, au, at, as, ar, aq, ap, ao, an, am, al, ak, aj, ai, ah, ag, af, ae, ad, ac, bz, by, bx, bw, bv, bu, bt, bs, br, bq, bp, bo, bn, bm, bl, bk, bj, bi, bh, bg, bf, be, bd, bc ␤»}  say join ", ", "r2".."t3"; # OUTPUT: «r2, r3, s2, s3, t2, t3␤»  To achieve simpler behaviour, similar to the Perl 5 example above, use a sequence operator that calls .succ method on the starting string: say join ", ", ("az", *.succ ... "bc"); # OUTPUT: «az, ba, bb, bc␤»  Topicalizing operators The smartmatch operator ~~ and andthen set the topic$_ to their left-hand-side. In conjunction with implicit method calls on the topic this can lead to surprising results.

my &method = { note $_;$_ };
$_ = 'object'; say .&method; # OUTPUT: «object␤object␤» say 'topic' ~~ .&method; # OUTPUT: «topic␤True␤»  In many cases flipping the method call to the LHS will work. my &method = { note$_; $_ };$_ = 'object';
say .&method;
# OUTPUT: «object␤object␤»
say .&method ~~ 'topic';
# OUTPUT: «object␤False␤»


Fat arrow and constants

The fat arrow operator => will turn words on its left-hand side to Str without checking the scope for constants or \-sigiled variables. Use explicit scoping to get what you mean.

constant V = 'x';
my %h = V => 'oi‽', ::V => 42;
say %h.perl
# OUTPUT: «{:V("oi‽"), :x(42)}␤»


Infix operator assignment

Infix operators, both built in and user defined, can be combined with the assignment operator as this addition example demonstrates:

my $x = 10;$x += 20;
say $x; # OUTPUT: «30␤» For any given infix operator op, L op= R is equivalent to L = L op R (where L and R are the left and right arguments, respectively). This means that the following code may not behave as expected: my @a = 1, 2, 3; @a += 10; say @a; # OUTPUT: «[13]␤» Coming from a language like C++, this might seem odd. It is important to bear in mind that += isn't defined as method on the left hand argument (here the @a array) but is simply shorthand for: my @a = 1, 2, 3; @a = @a + 10; say @a; # OUTPUT: «[13]␤» Here @a is assigned the result of adding @a (which has three elements) and 10; 13 is therefore placed in @a. Use the hyper form of the assignment operators instead: my @a = 1, 2, 3; @a »+=» 10; say @a; # OUTPUT: «[11 12 13]␤» Regexes <{$x}> vs $($x): Implicit EVAL

Sometimes you may need to match a generated string in a regex. This can be done using $(…) or <{…}> syntax: my$x = ‘ailemac’;
say ‘I ♥ camelia’ ~~ / $($x.flip) /; # OUTPUT: «｢camelia｣␤»
say ‘I ♥ camelia’ ~~ / <{$x.flip}> /; # OUTPUT: «｢camelia｣␤»  However, the latter only works sometimes. Internally <{…}> EVAL-s the given string inside an anonymous regex, while$(…) lexically interpolates the given string. So <{…}> immediately breaks with more complicated inputs. For example:

my $x = ‘ailemac#’; say ‘I ♥ #camelia’ ~~ /$($x.flip) /; # OUTPUT: «｢#camelia｣␤» # ⚠ ↓↓ WRONG ↓↓ ⚠ say ‘I ♥ #camelia’ ~~ / <{$x.flip}> /;
# OUTPUT:
# ===SORRY!===
# Regex not terminated.
# at EVAL_0:1
# ------> anon regex { #camelia}⏏<EOL>
# Malformed regex
# at EVAL_0:1
# ------> anon regex { #camelia}⏏<EOL>
#     expecting any of:
#         infix stopper


Therefore, try not to use <{}> unless you really need EVAL.

Note that even though EVAL is normally considered unsafe, in this case it is restricted to a set of safe operations (which is why it works without MONKEY-SEE-NO-EVAL pragma). In theory, careless use of <{}> will only result in an exception being thrown, and should not introduce security issues.

| vs ||: which branch will win

To match one of several possible alternatives, || or | will be used. But they are so different.

When there are multiple matching alternations, for those separated by ||, the first matching alternation wins; for those separated by |, which to win is decided by LTM strategy. See also: documentation on || and documentation on |.

For simple regexes just using || instead of | will get you familiar semantics, but if writing grammars then it's useful to learn about LTM and declarative prefixes and prefer |. And keep yourself away from using them in one regex. When you have to do that, add parentheses and ensure that you know how LTM strategy works to make the code do what you want.

The trap typically arises when you try to mix both | and || in the same regex:

say 42 ~~ / [  0 || 42 ] | 4/; # OUTPUT: «｢4｣␤»
say 42 ~~ / [ 42 ||  0 ] | 4/; # OUTPUT: «｢42｣␤»


The code above may seem like it is producing a wrong result, but the implementation is actually right.

bar ($a); # okay: one arg: 1  Now declare a function of two parameters: sub foo($a, $b) { say "two args:$a, $b" }  Execute it with and without the space after the name: foo($a, $b); # okay: two args: 1, 2 foo ($a, $b); # FAIL: Too few positionals passed; expected 2 arguments but got 1  The lesson is: "be careful with spaces following sub and method names when using the function call format." As a general rule, good practice might be to avoid the space after a function name when using the function call format. Note that there are clever ways to eliminate the error with the function call format and the space, but that is bordering on hackery and will not be mentioned here. For more information, consult Functions. Finally, note that, currently, when declaring the functions whitespace may be used between a function or method name and the parentheses surrounding the parameter list without problems. Named parameters Many built-in subroutines and method calls accept named parameters and your own code may accept them as well, but be sure the arguments you pass when calling your routines are actually named parameters: sub foo($a, :$b) { ... } foo(1, 'b' => 2); # FAIL: Too many positionals passed; expected 1 argument but got 2  What happened? That second argument is not a named parameter argument, but a Pair passed as a positional argument. If you want a named parameter it has to look like a name to Perl: foo(1, b => 2); # okay foo(1, :b(2)); # okay foo(1, :b<it>); # okay my$b = 2;
foo(1, :b($b)); # okay, but redundant foo(1, :$b);    # okay

# Or even...
my %arg = 'b' => 2;
foo(1, |%arg);  # okay too


That last one may be confusing, but since it uses the | prefix on a Hash, which is a special compiler construct indicating you want to use the contents of the variable as arguments, which for hashes means to treat them as named arguments.

If you really do want to pass them as pairs you should use a List or Capture instead:

my $list = ('b' => 2),; # this is a List containing a single Pair foo(|$list, :$b); # okay: we passed the pair 'b' => 2 to the first argument foo(1, |$list);         # FAIL: Too many positionals passed; expected 1 argument but got 2
foo(1, |$list.Capture); # OK: .Capture call converts all Pair objects to named args in a Capture  my$cap = \('b' => 2); # a Capture with a single positional value
foo(|$cap, :$b); # okay: we passed the pair 'b' => 2 to the first argument
foo(1, |$cap); # FAIL: Too many positionals passed; expected 1 argument but got 2  A Capture is usually the best option for this as it works exactly like the usual capturing of routine arguments during a regular call. The nice thing about the distinction here is that it gives the developer the option of passing pairs as either named or positional arguments, which can be handy in various instances. Argument count limit While it is typically unnoticeable, there is a backend-dependent argument count limit. Any code that does flattening of arbitrarily sized arrays into arguments won't work if there are too many elements. my @a = 1 xx 9999; my @b; @b.push: |@a; say @b.elems # OUTPUT: «9999␤»  my @a = 1 xx 999999; my @b; @b.push: |@a; # OUTPUT: «Too many arguments in flattening array.␤ in block <unit> at <tmp> line 1␤␤»  Avoid this trap by rewriting the code so that there is no flattening. In the example above, you can replace push with append. This way, no flattening is required because the array can be passed as is. my @a = 1 xx 999999; my @b; @b.append: @a; say @b.elems # OUTPUT: «999999␤»  Phasers and implicit return sub returns-ret () { CATCH { default {} } "ret"; } sub doesn't-return-ret () { "ret"; CATCH { default {} } } say returns-ret; # OUTPUT: «ret» say doesn't-return-ret; # BAD: outputs «Nil» and a warning «Useless use of constant string "ret" in sink context (line 13)»  Code for returns-ret and doesn't-return-ret might look exactly the same, since in principle it does not matter where the CATCH block goes. However, a block is an object and the last object in a sub will be returned, so the doesn't-return-ret will return Nil, and, besides, since "ret" will be now in sink context, it will issue a warning. In case you want to place phasers last for conventional reasons, use the explicit form of return. sub explicitly-return-ret () { return "ret"; CATCH { default {} } }  Input and output Closing open filehandles and pipes Unlike some other languages, Perl 6 does not use reference counting, and so the filehandles are NOT closed when they go out of scope. You have to explicitly close them either by using close routine or using the :close argument several of IO::Handle's methods accept. See IO::Handle.close for details. The same rules apply to IO::Handle's subclass IO::Pipe, which is what you operate on when reading from a Proc you get with routines run and shell. The caveat applies to IO::CatHandle type as well, though not as severely. See IO::CatHandle.close for details. IO::Path stringification Partly for historical reasons and partly by design, an IO::Path object stringifies without considering its CWD attribute, which means if you chdir and then stringify an IO::Path, or stringify an IO::Path with custom$!CWD attribute, the resultant string won't reference the original filesystem object:

with 'foo'.IO {
.Str.say;       # OUTPUT: «foo␤»
.relative.say;  # OUTPUT: «foo␤»

chdir "/tmp";
.Str.say;       # OUTPUT: «foo␤»
.relative.say   # OUTPUT: «../home/camelia/foo␤»
}

# Deletes ./foo, not /bar/foo


The easy way to avoid this issue is to not stringify an IO::Path object at all. Core routines that work with paths can take an IO::Path object, so you don't need to stringify the paths.

If you do have a case where you need a stringified version of an IO::Path, use absolute or relative methods to stringify it into an absolute or relative path, respectively.

If you are facing this issue because you use chdir in your code, consider rewriting it in a way that does not involve changing the current directory. For example, you can pass cwd named argument to run without having to use chdir around it.

Splitting the input data into lines

There is a difference between using .lines on IO::Handle and on a Str. The trap arises if you start assuming that both split data the same way.

say $_.perl for$*IN.lines # .lines called on IO::Handle
# OUTPUT:
# "foox"
# "fooy\rbar"
# "fooz"


As you can see in the example above, there was a line which contained \r (“carriage return” control character). However, the input is split strictly by \n, so \r was kept as part of the string.

On the other hand, Str.lines attempts to be “smart” about processing data from different operating systems. Therefore, it will split by all possible variations of a newline.

say $_.perl for$*IN.slurp(:bin).decode.lines # .lines called on a Str
# OUTPUT:
# "foox"
# "fooy"
# "bar"
# "fooz"


The rule is quite simple: use IO::Handle.lines when working with programmatically generated output, and Str.lines when working with user-written texts.

Use $data.split(“\n”) in cases where you need the behavior of IO::Handle.lines but the original IO::Handle is not available. RT#132154 Note that if you really want to slurp the data first, then you will have to use .IO.slurp(:bin).decode.split(“\n”). Notice how we use :bin to prevent it from doing the decoding, only to call .decode later anyway. All that is needed because .slurp is assuming that you are working with text and therefore it attempts to be smart about newlines. RT#131923 If you are using Proc::Async, then there is currently no easy way to make it split data the right way. You can try reading the whole output and then using Str.split (not viable if you are dealing with large data) or writing your own logic to split the incoming data the way you need. Same applies if your data is null-separated. Proc::Async and print When using Proc::Async you should not assume that .print (or any other similar method) is synchronous. The biggest issue of this trap is that you will likely not notice the problem by running the code once, so it may cause a hard-to-detect intermittent fail. Here is an example that demonstrates the issue: loop { my$proc = Proc::Async.new: :w, ‘head’, ‘-n’, ‘1’;
my $got-something; react { whenever$proc.stdout.lines { $got-something = True } whenever$proc.start        { die ‘FAIL!’ unless $got-something }$proc.print: “one\ntwo\nthree\nfour”;
$proc.close-stdin; } say$++;
}


And the output it may produce:

0
1
2
3
An operation first awaited:
in block <unit> at print.p6 line 4

Died with the exception:
FAIL!
in block  at print.p6 line 6


Resolving this is easy because .print returns a promise that you can await on. The solution is even more beautiful if you are working in a react block:

whenever $proc.print: “one\ntwo\nthree\nfour” {$proc.close-stdin;
}


Using .stdout without .lines

Method .stdout of Proc::Async returns a supply that emits chunks of data, not lines. The trap is that sometimes people assume it to give lines right away.

my $proc = Proc::Async.new(‘cat’, ‘/usr/share/dict/words’); react { whenever$proc.stdout.head(1) { .say } # ← WRONG (most likely)
whenever $proc.start { } }  The output is clearly not just 1 line: A A's AMD AMD's AOL AOL's Aachen Aachen's Aaliyah Aaliyah's Aaron Aaron's Abbas Abbas's Abbasid Abbasid's Abbott Abbott's Abby  If you want to work with lines, then use$proc.stdout.lines. If you're after the whole output, then something like this should do the trick: whenever $proc.stdout {$out ~= $_ }. Exception handling Sunk Proc Some methods return a Proc object. If it represents a failed process, Proc itself won't be exception-like, but sinking it will cause an X::Proc::Unsuccessful exception to be thrown. That means this construct will throw, despite the try in place: try run("perl6", "-e", "exit 42"); say "still alive"; # OUTPUT: «The spawned process exited unsuccessfully (exit code: 42)␤»  This is because try receives a Proc and returns it, at which point it sinks and throws. Explicitly sinking it inside the try avoids the issue and ensures the exception is thrown inside the try: try sink run("perl6", "-e", "exit 42"); say "still alive"; # OUTPUT: «still alive␤»  If you're not interested in catching any exceptions, then use an anonymous variable to keep the returned Proc in; this way it'll never sink: $ = run("perl6", "-e", "exit 42");
say "still alive";
# OUTPUT: «still alive␤»


Using shortcuts

The ^ twigil

Using the ^ twigil can save a fair amount of time and space when writing out small blocks of code. As an example:

for 1..8 -> $a,$b { say $a +$b; }


can be shortened to just

for 1..8 { say $^a +$^b; }


The trouble arises when a person wants to use more complex names for the variables, instead of just one letter. The ^ twigil is able to have the positional variables be out of order and named whatever you want, but assigns values based on the variable's Unicode ordering. In the above example, we can have $^a and$^b switch places, and those variables will keep their positional values. This is because the Unicode character 'a' comes before the character 'b'. For example:

# In order
sub f1 { say "$^first$^second"; }
f1 "Hello", "there";    # OUTPUT: «Hello there␤»

# Out of order
sub f2 { say "$^second$^first"; }
f2 "Hello", "there";    # OUTPUT: «there Hello␤»


Due to the variables allowed to be called anything, this can cause some problems if you are not accustomed to how Perl 6 handles these variables.

# BAD NAMING: alphabetically four comes first and gets value 1 in it:
for 1..4 { say "$^one$^two $^three$^four"; }    # OUTPUT: «2 4 3 1␤»

# GOOD NAMING: variables' naming makes it clear how they sort alphabetically:
for 1..4 { say "$^a$^b $^c$^d"; }               # OUTPUT: «1 2 3 4␤»


Using » and map interchangeably

While » may look like a shorter way to write map, they differ in some key aspects.

First, the » includes a hint to the compiler that it may autothread the execution, thus if you're using it to call a routine that produces side effects, those side effects may be produced out of order (the result of the operator is kept in order, however). Also if the routine being invoked accesses a resource, there's the possibility of a race condition, as multiple invocations may happen simultaneously, from different threads.

This is an actual output from Rakudo 2015.09
<a b c d>».say # OUTPUT: «d␤b␤c␤a␤»


Second, » checks the nodality of the routine being invoked and based on that will use either deepmap or nodemap to map over the list, which can be different from how a map call would map over it:

say ((1, 2, 3), [^4], '5')».Numeric;       # OUTPUT: «((1 2 3) [0 1 2 3] 5)␤»
say ((1, 2, 3), [^4], '5').map: *.Numeric; # OUTPUT: «(3 4 5)␤»


The bottom line is that map and » are not interchangeable, but using one instead of the other is OK as long as you understand the differences.

Word splitting in « »

Keep in mind that « » performs word splitting similarly to how shells do it, so many shell pitfalls apply here as well (especially when using in combination with run):

my $file = ‘--my arbitrary filename’; run ‘touch’, ‘--’,$file;  # RIGHT
run <touch -->, $file; # RIGHT run «touch -- "$file"»;    # RIGHT but WRONG if you forget quotes
run «touch -- $file»; # WRONG; touches ‘--my’, ‘arbitrary’ and ‘filename’ run ‘touch’,$file;        # WRONG; error from touch
run «touch "$file"»; # WRONG; error from touch Note that -- is required for many programs to disambiguate between command-line arguments and filenames that begin with hyphens. Scope Using an once block The once block is a block of code that will only run once when its parent block is run. As an example: my$var = 0;
for 1..10 {
once { $var++; } } say "Variable =$var";    # OUTPUT: «Variable = 1␤»


This functionality also applies to other code blocks like sub and while, not just for loops. Problems arise though, when trying to nest once blocks inside of other code blocks:

my $var = 0; for 1..10 { do { once {$var++; } }
}
say "Variable = $var"; # OUTPUT: «Variable = 10␤»  In the above example, the once block was nested inside of a code block which was inside of a for loop code block. This causes the once block to run multiple times, because the once block uses state variables to determine whether it has run previously. This means that if the parent code block goes out of scope, then the state variable the once block uses to keep track of if it has run previously, goes out of scope as well. This is why once blocks and state variables can cause some unwanted behaviour when buried within more than one code block. If you want to have something that will emulate the functionality of a once block, but still work when buried a few code blocks deep, we can manually build the functionality of a once block. Using the above example, we can change it so that it will only run once, even when inside the do block by changing the scope of the state variable. my$var = 0;
for 1..10 {
state $run-code = True; do { if ($run-code) { $run-code = False;$var++; } }
}
say "Variable = $var"; # OUTPUT: «Variable = 1␤»  In this example, we essentially manually build a once block by making a state variable called$run-code at the highest level that will be run more than once, then checking to see if $run-code is True using a regular if. If the variable$run-code is True, then make the variable False and continue with the code that should only be completed once.

The main difference between using a state variable like the above example and using a regular once block is what scope the state variable is in. The scope for the state variable created by the once block, is the same as where you put the block (imagine that the word 'once' is replaced with a state variable and an if to look at the variable). The example above using state variables works because the variable is at the highest scope that will be repeated; whereas the example that has a once block inside of a do, made the variable within the do block which is not the highest scope that is repeated.

Using a once block inside a class method will cause the once state to carry across all instances of that class. For example:

class A {
method sayit() { once say 'hi' }
}
my $a = A.new;$a.sayit;      # OUTPUT: «hi␤»
my $b = A.new;$b.sayit;      # nothing


LEAVE phaser and exit

Using LEAVE phaser to perform graceful resource termination is a common pattern, but it does not cover the case when the program is stopped with exit.

The following nondeterministic example should demonstrate the complications of this trap:

my $x = say ‘Opened some resource’; LEAVE say ‘Closing the resource gracefully’ with$x;

exit 42 if rand < ⅓; # ① ｢exit｣ is bad
die ‘Dying because of unhandled exception’ if rand < ½; # ② ｢die｣ is ok
# fallthru ③


There are three possible results:

①
Opened some resource

②
Opened some resource
Closing the resource gracefully
Dying because of unhandled exception
in block <unit> at print.p6 line 5

③
Opened some resource
Closing the resource gracefully


A call to exit is part of normal operation for many programs, so beware unintentional combination of LEAVE phasers and exit calls.

LEAVE phaser may run sooner than you think

Parameter binding is executed when we're "inside" the routine's block, which means LEAVE phaser would run when we leave that block if parameter binding fails when wrong arguments are given:

sub foo(Int) {
my $x = 42; LEAVE say$x.Int; # ← WRONG; assumes that $x is set } say foo rand; # OUTPUT: «No such method 'Int' for invocant of type 'Any'␤»  A simple way to avoid this issue is to declare your sub or method a multi, so the candidate is eliminated during dispatch and the code never gets to binding anything inside the sub, thus never entering the routine's body: multi foo(Int) { my$x = 42;
LEAVE say $x.Int; } say foo rand; # OUTPUT: «Cannot resolve caller foo(Num); none of these signatures match: (Int)␤»  Another alternative is placing the LEAVE into another block (assuming it's appropriate for it to be executed when that block is left, not the routine's body: sub foo(Int) { my$x = 42;
{ LEAVE say $x.Int; } } say foo rand; # OUTPUT: «Type check failed in binding to parameter '<anon>'; expected Int but got Num (0.7289418947969465e0)␤»  You can also ensure LEAVE can be executed even if the routine is left due to failed argument binding. In our example, we check$x is defined before doing anything with it.

sub foo(Int) {
my $x = 42; LEAVE$x andthen .Int.say;
}
say foo rand; # OUTPUT: «Type check failed in binding to parameter '<anon>'; expected Int but got Num (0.8517160389079508e0)␤»


Grammars

Using regexes within grammar's actions

grammar will-fail {
token TOP {^ <word> $} token word { \w+ } } class will-fail-actions { method TOP ($/) { my $foo = ~$/; say $foo ~~ /foo/; } }  Will fail with Cannot assign to a readonly variable ($/) or a value on method TOP. The problem here is that regular expressions also affect $/. Since it is in TOP's signature, it is a read-only variable, which is what produces the error. You can safely either use another variable in the signature or add is copy, this way: method TOP ($/ is copy) { my $foo = ~$/; my $v =$foo ~~ /foo/;  }


Using certain names for rules/token/regexes

Grammars are actually a type of classes.

grammar G {};
say G.^mro; # OUTPUT: «((G) (Grammar) (Match) (Capture) (Cool) (Any) (Mu))␤»

^mro prints the class hierarchy of this empty grammar, showing all the superclasses. And these superclasses have their very own methods. Defining a method in that grammar might clash with the ones inhabiting the class hierarchy:

grammar g {
token TOP { <item> };
token item { 'defined' }
};
say g.parse('defined');
# OUTPUT: «(exit code 1) Too many positionals passed; expected 1 argument but #
# got 2␤  in regex item at /tmp/dZ3evir0pb line 1␤  in regex TOP at
# /tmp/dZ3evir0pb line 1␤  in block <unit> at /tmp/dZ3evir0pb line 1␤␤»


item seems innocuous enough, but it is a sub defined in class Mu. The message is a bit cryptic and totally unrelated to that fact, but that is why this is listed as a trap. In general, all subs defined in any part of the hierarchy are going to cause problems; some methods will too. For instance, CREATE, take and defined (which are defined in Mu). In general, multi methods and simple methods will not have any problem, but it might not be a good practice to use them as rule names.

Also avoid phasers for rule/token/regex names: TWEAK, BUILD, BUILD-ALL will throw another kind of exception if you do that: Cannot find method 'match': no method cache and no .^find_method, once again only slightly related to what is actually going on.

Unfortunate generalization

:exists with more than one key

Let's say you have a hash and you want to use :exists on more than one element:

my %h = a => 1, b => 2;
say ‘a exists’ if %h<a>:exists;   # ← OK; True
say ‘y exists’ if %h<y>:exists;   # ← OK; False
say ‘Huh‽’     if %h<x y>:exists; # ← WRONG; returns a 2-item list


Did you mean “if any of them exists”, or did you mean that all of them should exist? Use any or all Junction to clarify:

my %h = a => 1, b => 2;
say ‘x or y’     if any %h<x y>:exists;   # ← RIGHT (any); False
say ‘a, x or y’  if any %h<a x y>:exists; # ← RIGHT (any); True
say ‘a, x and y’ if all %h<a x y>:exists; # ← RIGHT (all); False
say ‘a and b’    if all %h<a b>:exists;   # ← RIGHT (all); True


The reason why it is always True (without using a junction) is that it returns a list with Bool values for each requested lookup. Non-empty lists always give True when you Boolify them, so the check always succeeds no matter what keys you give it.

Using […] metaoperator with a list of lists

Every now and then, someone gets the idea that they can use [Z] to create the transpose of a list-of-lists:

my @matrix = <X Y>, <a b>, <1 2>;
my @transpose = [Z] @matrix; # ← WRONG; but so far so good ↙
say @transpose;              # [(X a 1) (Y b 2)]


And everything works fine, until you get an input @matrix with exactly one row (child list):

my @matrix = <X Y>,;
my @transpose = [Z] @matrix; # ← WRONG; ↙
say @transpose;              # [(X Y)] – not the expected transpose [(X) (Y)]


This happens partly because of the single argument rule, and there are other cases when this kind of a generalization may not work.

Using [~] for concatenating a list of blobs

The ~ infix operator can be used to concatenate Strs or Blobs. However, an empty list will always be reduced to an empty Str. This is due to the fact that, in the presence of a list with no elements, the reduction metaoperator returns the identity element for the given operator. Identity element for ~ is an empty string, regardless of the kind of elements the list could be populated with.

my Blob @chunks;
say ([~] @chunks).perl; # OUTPUT: «""␤»


This might cause a problem if you attempt to use the result while assuming that it is a Blob:

my Blob @chunks;
say ([~] @chunks).decode;
# OUTPUT: «No such method 'decode' for invocant of type 'Str'. Did you mean 'encode'?␤…»


There are many ways to cover that case. You can avoid [ ] metaoperator altogether:

my @chunks;
# …
say Blob.new: |«@chunks; # OUTPUT: «Blob:0x<>␤»


Alternatively, you can initialize the array with an empty Blob:

my @chunks = Blob.new;
# …
say [~] @chunks; # OUTPUT: «Blob:0x<>␤»


Or you can utilize || operator to make it use an empty Blob in case the list is empty:

my @chunks;
# …
say [~] @chunks || Blob.new; # OUTPUT: «Blob:0x<>␤»


Please note that a similar issue may arise when reducing lists with other operators.

Maps

Beware of nesting Maps in sink context

Maps apply an expression to every element of a List and return a Seq:

say <þor oðin loki>.map: *.codes; # OUTPUT: «(3 4 4)␤»

Maps are often used as a compact substitute for a loop, performing some kind of action in the map code block:

<þor oðin loki>.map: *.codes.say; # OUTPUT: «3␤4␤4␤»

The problem might arise when maps are nested and in a sink context.

<foo bar ber>.map: { $^a.comb.map: {$^b.say}}; # OUTPUT: «»

You might expect the innermost map to bubble the result up to the outermost map, but it simply does nothing. Maps return Seqs, and in sink context the innermost map will iterate and discard the produced values, which is why it yields nothing.

Simply using say at the beginning of the sentence will save the result from sink context:

say <foo bar ber>.map: *.comb.map: *.say ;
# OUTPUT: «f␤o␤o␤b␤a␤r␤b␤e␤r␤((True True True) (True True True) (True True True))␤»

However, it will not be working as intended; the first f␤o␤o␤b␤a␤r␤b␤e␤r␤ is the result of the innermost say, but then say returns a Bool, True in this case. Those Trues are what get printed by the outermost say, one for every letter. A much better option would be to flatten the outermost sequence:

<foo bar ber>.map({ $^a.comb.map: {$^b.say}}).flat
# OUTPUT: «f␤o␤o␤b␤a␤r␤b␤e␤r␤»

Of course, saving say for the result will also produce the intended result, as it will be saving the two nested sequences from void context:

say <foo bar ber>.map: { $^þ.comb }; # OUTPUT: « ((f o o) (b a r) (b e r))» Smartmatching The smartmatch operator shortcuts to the right hand side accepting the left hand side. This may cause some confusion. Smartmach and WhateverCode Using WhateverCode in the left hand side of a smartmatch does not work as expected, or at all: my @a = <1 2 3>; say @a.grep( *.Int ~~ 2 ); # OUTPUT: «Cannot use Bool as Matcher with '.grep'. Did you mean to # use$_ inside a block?␤␤␤»


The error message does not make a lot of sense. It does, however, if you put it in terms of the ACCEPTS method: that code is equivalent to 2.ACCEPTS( *.Int ), but *.Int cannot be coerced to Numeric, being as it is a Block.

Solution: don't use WhateverCode in the left hand side of a smartmatch:

my @a = <1 2 3>;
say @a.grep( 2 ~~ *.Int ); # OUTPUT: «(2)␤»


~

42 Containers

A low-level explanation of Perl 6 containers

This section explains the levels of indirection involved in dealing with variables and container elements. The difference types of containers used in Perl 6 are explained and the actions applicable to them like assigning, binding and flattening. More advanced topics like self-referencial data, type constraints and custom containers are discussed at the end.

What is a variable?

Some people like to say "everything is an object", but in fact a variable is not a user-exposed object in Perl 6.

When the compiler encounters a variable declaration like my $x, it registers it in some internal symbol table. This internal symbol table is used to detect undeclared variables and to tie the code generation for the variable to the correct scope. At runtime, a variable appears as an entry in a lexical pad, or lexpad for short. This is a per-scope data structure that stores a pointer for each variable. In the case of my$x, the lexpad entry for the variable $x is a pointer to an object of type Scalar, usually just called the container. Scalar containers Although objects of type Scalar are everywhere in Perl 6, you rarely see them directly as objects, because most operations decontainerize, which means they act on the Scalar container's contents instead of the container itself. In code like my$x = 42;
say $x; the assignment$x = 42 stores a pointer to the Int object 42 in the scalar container to which the lexpad entry for $x points. The assignment operator asks the container on the left to store the value on its right. What exactly that means is up to the container type. For Scalar it means "replace the previously stored value with the new one". Note that subroutine signatures allow passing around of containers: sub f($a is rw) {
$a = 23; } my$x = 42;
f($x); say$x;         # OUTPUT: «23␤»

Inside the subroutine, the lexpad entry for $a points to the same container that$x points to outside the subroutine. Which is why assignment to $a also modifies the contents of$x.

Likewise a routine can return a container if it is marked as is rw:

my $x = 23; sub f() is rw {$x };
f() = 42;
say $x; # OUTPUT: «42␤» For explicit returns, return-rw instead of return must be used. Returning a container is how is rw attribute accessors work. So class A { has$.attr is rw;
}

is equivalent to

class A {
has $!attr; method attr() is rw {$!attr }
}

Scalar containers are transparent to type checks and most kinds of read-only accesses. A .VAR makes them visible:

my $x = 42; say$x.^name;       # OUTPUT: «Int␤»
say $x.VAR.^name; # OUTPUT: «Scalar␤» And is rw on a parameter requires the presence of a writable Scalar container: sub f($x is rw) { say $x }; f 42; CATCH { default { say .^name, ': ', .Str } }; # OUTPUT: «X::Parameter::RW: Parameter '$x' expected a writable container, but got Int value␤»

Callable containers

Callable containers provide a bridge between the syntax of a Routine call and the actual call of the method CALL-ME of the object that is stored in the container. The sigil & is required when declaring the container and has to be omitted when executing the Callable. The default type constraint is Callable.

my &callable = -> $ν { say "$ν is", $ν ~~ Int??" whole"!!" not whole" } callable( ⅓ ); callable( 3 ); The sigil has to be provided when referring to the value stored in the container. This in turn allows Routines to be used as arguments to calls. sub f() {} my &g = sub {} sub caller(&c1, &c2){ c1, c2 } caller(&f, &g); Binding Next to assignment, Perl 6 also supports binding with the := operator. When binding a value or a container to a variable, the lexpad entry of the variable is modified (and not just the container it points to). If you write my$x := 42;

then the lexpad entry for $x directly points to the Int 42. Which means that you cannot assign to it anymore: my$x := 42;
$x = 23; CATCH { default { say .^name, ': ', .Str } }; # OUTPUT: «X::AdHoc: Cannot assign to an immutable value␤» You can also bind variables to other variables: my$a = 0;
my $b = 0;$a := $b;$b = 42;
say $a; # OUTPUT: «42␤» Here, after the initial binding, the lexpad entries for$a and $b both point to the same scalar container, so assigning to one variable also changes the contents of the other. You've seen this situation before: it is exactly what happened with the signature parameter marked as is rw. Sigilless variables and parameters with the trait is raw always bind (whether = or := is used): my$a = 42;
my \b = $a; b++; say$a;         # OUTPUT: «43␤»

sub f($c is raw) {$c++ }
f($a); say$a;         # OUTPUT: «44␤»

Scalar containers and listy things

There are a number of positional container types with slightly different semantics in Perl 6. The most basic one is List; it is created by the comma operator.

say (1, 2, 3).^name;    # OUTPUT: «List␤»

A list is immutable, which means you cannot change the number of elements in a list. But if one of the elements happens to be a scalar container, you can still assign to it:

my $x = 42; ($x, 1, 2)[0] = 23;
say $x; # OUTPUT: «23␤» ($x, 1, 2)[1] = 23;     # Cannot modify an immutable value
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int␤»

So the list doesn't care about whether its elements are values or containers, they just store and retrieve whatever was given to them.

Lists can also be lazy; in that case, elements at the end are generated on demand from an iterator.

An Array is just like a list, except that it forces all its elements to be containers, which means that you can always assign to elements:

my @a = 1, 2, 3;
@a[0] = 42;
say @a;         # OUTPUT: «[42 2 3]␤»

@a actually stores three scalar containers. @a[0] returns one of them, and the assignment operator replaces the integer value stored in that container with the new one, 42.

Assigning and binding to array variables

Assignment to a scalar variable and to an array variable both do the same thing: discard the old value(s), and enter some new value(s).

Nevertheless, it's easy to observe how different they are:

my $x = 42; say$x.^name;   # OUTPUT: «Int␤»
my @a = 42; say @a.^name;   # OUTPUT: «Array␤»

This is because the Scalar container type hides itself well, but Array makes no such effort. Also assignment to an array variable is coercive, so you can assign a non-array value to an array variable.

To place a non-Array into an array variable, binding works:

my @a := (1, 2, 3);
say @a.^name;               # OUTPUT: «List␤»

Binding to array elements

As a curious side note, Perl 6 supports binding to array elements:

my @a = (1, 2, 3);
@a[0] := my $x;$x = 42;
say @a;                     # OUTPUT: «[42 2 3]␤»

If you've read and understood the previous explanations, it is now time to wonder how this can possibly work. After all, binding to a variable requires a lexpad entry for that variable, and while there is one for an array, there aren't lexpad entries for each array element, because you cannot expand the lexpad at runtime.

The answer is that binding to array elements is recognized at the syntax level and instead of emitting code for a normal binding operation, a special method (called BIND-KEY) is called on the array. This method handles binding to array elements.

Note that, while supported, one should generally avoid directly binding uncontainerized things into array elements. Doing so may produce counter-intuitive results when the array is used later.

my @a = (1, 2, 3);
@a[0] := 42;         # This is not recommended, use assignment instead.
my $b := 42; @a[1] :=$b;         # Nor is this.
@a[2] = $b; # ...but this is fine. @a[1, 2] := 1, 2; # runtime error: X::Bind::Slice CATCH { default { say .^name, ': ', .Str } }; # OUTPUT: «X::Bind::Slice: Cannot bind to Array slice␤» Operations that mix Lists and Arrays generally protect against such a thing happening accidentally. Flattening, items and containers The % and @ sigils in Perl 6 generally indicate multiple values to an iteration construct, whereas the$ sigil indicates only one value.

my @a = 1, 2, 3;
for @a { };         # 3 iterations
my $a = (1, 2, 3); for$a { };         # 1 iteration

@-sigiled variables do not flatten in list context:

my @a = 1, 2, 3;
my @b = @a, 4, 5;
say @b.elems;               # OUTPUT: «3␤»

There are operations that flatten out sublists that are not inside a scalar container: slurpy parameters (*@a) and explicit calls to flat:

my @a = 1, 2, 3;
say (flat @a, 4, 5).elems;  # OUTPUT: «5␤»

sub f(*@x) { @x.elems };
say f @a, 4, 5;             # OUTPUT: «5␤»

You can also use | to create a Slip, introducing a list into the other.

my @l := 1, 2, (3, 4, (5, 6)), [7, 8, (9, 10)];
say (|@l, 11, 12); # OUTPUT: «(1 2 (3 4 (5 6)) [7 8 (9 10)] 11 12)␤»
say (flat @l, 11, 12) # OUTPUT: «(1 2 3 4 5 6 7 8 (9 10) 11 12)␤»

In the first case, every element of @l is slipped as the corresponding elements of the resulting list. flat, in the other hand, flattens all elements including the elements of the included array, except for (9 10).

As hinted above, scalar containers prevent that flattening:

sub f(*@x) { @x.elems };
my @a = 1, 2, 3;
say f $@a, 4, 5; # OUTPUT: «3␤» The @ character can also be used as a prefix to coerce the argument to a list, thus removing a scalar container: my$x = (1, 2, 3);
.say for @$x; # 3 iterations However, the decont operator <> is more appropriate to decontainerize items that aren't lists: my$x = ^Inf .grep: *.is-prime;
say "$_ is prime" for @$x;  # WRONG! List keeps values, thus leaking memory
say "$_ is prime" for$x<>; # RIGHT. Simply decontainerize the Seq

my $y := ^Inf .grep: *.is-prime; # Even better; no Scalars involved at all Methods generally don't care whether their invocant is in a scalar, so my$x = (1, 2, 3);
$x.map(*.say); # 3 iterations maps over a list of three elements, not of one. Self-referential data Containers types, including Array and Hash, allow you to create self-referential structures. my @a; @a[0] = @a; put @a.perl; # OUTPUT: «((my @Array_75093712) = [@Array_75093712,])␤» Perl 6 does not prevent you from creating and using self-referential data; You may end up in a loop trying to dump the data; as a last resort, you can use Promises to handle timeouts. Type constraints Any container can have a type constraint in the form of a type object or a subset. Both can be placed between a declarator and the variable name or after the trait of. The constraint is a property of the variable, not the container. subset Three-letter of Str where .chars == 3; my Three-letter$acronym = "ÞFL";

In this case, the type constraint is the (compile-type defined) subset Three-letter.

Variables may have no container in them, yet still offer the ability to re-bind and typecheck that rebind. The reason for that is in such cases the binding operator := performs the typecheck:

my Int \z = 42;
z := 100; # OK
z := "x"; # Typecheck failure

The same isn't the case when, say, binding to a Hash key, as the binding is then handled by a method call (even though the syntax remains the same, using := operator).

The default type constraint of a Scalar container is Mu. Introspection of type constraints on containers is provided by .VAR.of method, which for @ and % sigiled variables gives the constraint for values:

my Str $x; say$x.VAR.of;  # OUTPUT: «(Str)␤»
my Num @a;
say @a.VAR.of;  # OUTPUT: «(Num)␤»
my Int %h;
say %h.VAR.of;  # OUTPUT: «(Int)␤»

Definedness constraints

A container can also enforce a variable to be defined. Put a smiley in the declaration:

my Int:D $def = 3; say$def; # OUTPUT: «3␤»
$def = Int; # Typecheck failure You'll also need to initialize the variable in the declaration, it can't be left undefined after all. It's also possible to have this constraint enforced in all variables declared in a scope with the default defined variables pragma. People coming from other languages where variables are always defined will want to have a look. Custom containers To provide custom containers Perl 6 provides the class Proxy. It takes two methods that are called when values are stored or fetched from the container. Type checks are not done by the container itself and other restrictions like readonlyness can be broken. The returned value must therefore be of the same type as the type of the variable it is bound to. We can use type captures to work with types in Perl 6. sub lucky(::T$type) {
my T $c-value; # closure variable return Proxy.new( FETCH => method () {$c-value },
STORE => method (T $new-value) { X::OutOfRange.new(what => 'number', got => '13', range => '-∞..12, 14..∞').throw if$new-value == 13;
$c-value =$new-value;
}
);
}

my Int $a := lucky(Int); say$a = 12;    # OUTPUT: «12␤»
say $a = 'FOO'; # X::TypeCheck::Binding say$a = 13;    # X::OutOfRange
CATCH { default { say .^name, ': ', .Str } };

43 Contexts and contextualizers

What are contexts and how to get into them

A context is needed, in many occasions, to interpret the value of a container. In Perl 6, we will use context to coerce the value of a container into some type or class, or decide what to do with it, as in the case of the sink context.

Sink

Sink is equivalent to void context, that is, a context in which we throw (down the sink, as it were) the result of an operation or the return value from a block. In general, this context will be invoked in warnings and errors when a statement does not know what to do with that value.

my $sub = ->$a { return $a² };$sub; # OUTPUT: «WARNINGS:␤Useless use of $sub in sink context (line 1)␤»  You can force that sink context on Iterators, by using the sink-all method. Procs can also be sunk via the sink method, forcing them to raise an exception and not returning anything. In general, blocks will warn if evaluated in sink context; however, gather/take blocks are explicitly evaluated in sink context, with values returned explicitly using take. In sink context, an object will call its sink method if present: sub foo { return [<a b c>] does role { method sink { say "sink called" } } } foo # OUTPUT: sink called  Number This context, and probably all of them except sink above, are conversion or interpretation contexts in the sense that they take an untyped or typed variable and duck-type it to whatever is needed to perform the operation. In some cases that will imply a conversion (from Str to Numeric, for instance); in other cases simply an interpretation (IntStr will be interpreted as Int or as Str). Number context is called whenever we need to apply a numerical operation on a variable. my$not-a-string="1                 ";
my $neither-a-string="3 "; say$not-a-string+$neither-a-string; # OUTPUT: «4␤»  In the code above, strings will be interpreted in numeric context as long as there is only some numbers and no other characters. It can have any number of leading or trailing whitespace, however. Numeric context can be forced by using arithmetic operators such as + or -. In that context, the Numeric method will be called if available and the value returned used as the numeric value of the object. my$t = True;
my $f = False; say$t+$f; # OUTPUT: «1␤» say$t.Numeric; # OUTPUT: «1␤»
say $f.Numeric; # OUTPUT: «0␤» my$list= <a b c>;
say True+$list; # OUTPUT: «4␤»  In the case of listy things, the numeric value will be in general equivalent to .elems; in some cases, like Thread it will return an unique thread identifier. String In a string context, values can be manipulated as strings. This context is used, for instance, for coercing non-string values so that they can be printed to standard output.  say$very-complicated-and-hairy-object; # OUTPUT: something meaningful


Or when smartmatching to a regular expression:

say 333444777 ~~ /(3+)/; # OUTPUT: «｢333｣␤ 0 => ｢333｣␤»

In general, the Str routine will be called on a variable to contextualize it; since this method is inherited from Mu, it is always present, but it is not always guaranteed to work. In some core classes it will issue a warning.

~ is the (unary) string contextualizer. As an operator, it concatenates strings, but as a prefix operator it becomes the string context operator.

my @array = [ [1,2,3], [4,5,6]];
say ~@array; # OUTPUT: «1 2 3 4 5 6␤»


This will happen also in a reduction context, when [~] is applied to a list

say [~] [ 3, 5+6i, Set(<a b c>), [1,2,3] ]; # OUTPUT: «35+6ic a b1 2 3␤»

In that sense, empty lists or other containers will stringify to an empty string:

say [~] [] ; # OUTPUT: «␤»

Since ~ acts also as buffer concatenation operator, using it will have to check that every element is not empty, since a single empty buffer in string context will behave as a string, thus yielding an error.

say [~] Buf.new(0x3,0x33), Buf.new(0x2,0x22);
# OUTPUT: «Buf:0x<03 33 02 22>␤»

However,

my $non-empty = Buf.new(0x3, 0x33); my$empty = [];
my $non-empty-also = Buf.new(0x2,0x22); say [~]$non-empty, $empty,$non-empty-also;
# OUTPUT: «(exit code 1) Cannot use a Buf as a string, but you called the Stringy method on it
# in block <unit> at /tmp/bO_heb6AS9 line 1␤␤»


Since ~ is putting in string context the second element of this list, ~ is going to be using the second form that applies to strings, thus yielding the shown error. Simply making sure that everything you concatenate is a buffer will avoid this problem.

my $non-empty = Buf.new(0x3, 0x33); my$empty = Buf.new();
my $non-empty-also = Buf.new(0x2,0x22); say [~]$non-empty, $empty,$non-empty-also; # OUTPUT: «Buf:0x<03 33 02 22>␤»

In general, a context will coerce a variable to a particular type by calling the contextualizer; in the case of mixins, if the context class is mixed in, it will behave in that way.

my $described-number = 1i but 'Unity in complex plane'; say$described-number; # OUTPUT: «Unity in complex plane␤»

but creates a mixin, which endows the complex number with a Str method. say puts into string context, that is, it calls Str, the string contextualizer, with the result shown above.

44 Control flow

Statements used to control the flow of execution

statements

Perl 6 programs consists of one or more statements. Simple statements are separated by semicolons. The following program will say "Hello" and then say "World" on the next line.

say "Hello";
say "World";

In most places where spaces appear in a statement, and before the semicolon, it may be split up over many lines. Also, multiple statements may appear on the same line. It would be awkward, but the above could also be written as:

say
"Hello"; say "World";

blocks

Blocks

Like many languages, Perl 6 uses blocks enclosed by { and } to turn multiple statements into a single statement. It is ok to skip the semicolon between the last statement in a block and the closing }.

{ say "Hello"; say "World" }

When a block stands alone as a statement, it will be entered immediately after the previous statement finishes, and the statements inside it will be executed.

say 1;                    # OUTPUT: «1␤»
{ say 2; say 3 };         # OUTPUT: «2␤3␤»
say 4;                    # OUTPUT: «4␤»

Unless it stands alone as a statement, a block simply creates a closure. The statements inside are not executed immediately. Closures are another topic and how they are used is explained elsewhere. For now it is just important to understand when blocks run and when they do not:

say "We get here"; { say "then here." }; { say "not here"; 0; } or die;


In the above example, after running the first statement, the first block stands alone as a second statement, so we run the statement inside it. The second block does not stand alone as a statement, so instead, it makes an object of type Block but does not run it. Object instances are usually considered to be true, so the code does not die, even though that block would evaluate to 0, were it to be executed. The example does not say what to do with the Block object, so it just gets thrown away.

Most of the flow control constructs covered below are just ways to tell perl6 when, how, and how many times, to enter blocks like that second block.

Before we go into those, an important side-note on syntax: If there is nothing (or nothing but comments) on a line after a closing curly brace where you would normally put semicolon, then you do not need the semicolon:

# All three of these lines can appear as a group, as is, in a program
{ 42.say }                # OUTPUT: «42␤»
{ 43.say }                # OUTPUT: «43␤»
{ 42.say }; { 43.say }    # OUTPUT: «42␤43␤»

...but:

{ 42.say }  { 43.say }    # Syntax error
{ 42.say; } { 43.say }    # Also a syntax error, of course


So, be careful when you backspace in a line-wrapping editor:

{ "Without semicolons line-wrapping can be a bit treacherous.".say } \
{ 43.say } # Syntax error


You have to watch out for this in most languages anyway to prevent things from getting accidentally commented out. Many of the examples below may have unnecessary semicolons for clarity.

Phasers

Blocks may have phasers: special labeled blocks that break their execution into phases that run in particular phases. See the page phasers for the details.

do

The simplest way to run a block where it cannot be a stand-alone statement is by writing do before it:

# This dies half of the time
do { say "Heads I win, tails I die."; Bool.pick } or die; say "I win.";


Note that you need a space between the do and the block.

The whole do {...} evaluates to the final value of the block. The block will be run when that value is needed in order to evaluate the rest of the expression. So:

False and do { 42.say };

...will not say 42. However, the block is only evaluated once each time the expression it is contained in is evaluated:

# This says "(..1 ..2 ..3)" not "(..1 ...2 ....3)"
my $f = "."; say do {$f ~= "." } X~ 1, 2, 3;

In other words, it follows the same reification rules as everything else.

Technically, do is a loop which runs exactly one iteration.

A do may also be used on a bare statement (without curly braces) but this is mainly just useful for avoiding the syntactical need to parenthesize a statement if it is the last thing in an expression:

3, do if 1 { 2 }  ; # OUTPUT: «(3, 2)␤»
3,   (if 1 { 2 }) ; # OUTPUT: «(3, 2)␤»

3,    if 1 { 2 }  ; # Syntax error


...which brings us to if.

if

To conditionally run a block of code, use an if followed by a condition. The condition, an expression, will be evaluated immediately after the statement before the if finishes. The block attached to the condition will only be evaluated if the condition means True when coerced to Bool. Unlike some languages the condition does not have to be parenthesized, instead the { and } around the block are mandatory:

if 1 { "1 is true".say }  ; # says "1 is true"

if 1   "1 is true".say    ; # syntax error, missing block

if 0 { "0 is true".say }  ; # does not say anything, because 0 is false

if 42.say and 0 { 43.say }; # says "42" but does not say "43"


There is also a form of if called a "statement modifier" form. In this case, the if and then the condition come after the code you want to run conditionally. Do note that the condition is still always evaluated first:

43.say if 42.say and 0;     # says "42" but does not say "43"
43.say if 42.say and 1;     # says "42" and then says "43"
say "It is easier to read code when 'if's are kept on left of screen"
if True;                # says the above, because it is true
{ 43.say } if True;         # says "43" as well

The statement modifier form is probably best used sparingly.

The if statement itself will either slip us an empty list, if it does not run the block, or it will return the value which the block produces:

my $d = 0; say (1, (if 0 {$d += 42; 2; }), 3, $d); # says "(1 3 0)" my$c = 0; say (1, (if 1 { $c += 42; 2; }), 3,$c); # says "(1 2 3 42)"
say (1, (if 1 { 2, 2 }), 3);         # does not slip, says "(1 (2 2) 3)"

For the statement modifier it is the same, except you have the value of the statement instead of a block:

say (1, (42 if True) , 2); # says "(1 42 2)"
say (1, (42 if False), 2); # says "(1 2)"
say (1,  42 if False , 2); # says "(1 42)" because "if False, 2" is true

The if does not change the topic ($_) by default. In order to access the value which the conditional expression produced, you have to ask for it more strongly: $_ = 1; if 42 { $_.say } ; # says "1"$_ = 1; if 42 -> $_ {$_.say }          ; # says "42"
$_ = 1; if 42 ->$a { $_.say;$a.say } ; # says "1" then says "42"
$_ = 1; if 42 {$_.say; $^a.say } ; # says "1" then says "42" else/elsif A compound conditional may be produced by following an if conditional with else to provide an alternative block to run when the conditional expression is false: if 0 { say "no" } else { say "yes" } ; # says "yes" if 0 { say "no" } else{ say "yes" } ; # says "yes", space is not required  The else cannot be separated from the conditional statement by a semicolon, but as a special case, it is OK to have a newline. if 0 { say "no" }; else { say "yes" } ; # syntax error  if 0 { say "no" } else { say "yes" } ; # says "yes"  Additional conditions may be sandwiched between the if and the else using elsif. An extra condition will only be evaluated if all the conditions before it were false, and only the block next to the first true condition will be run. You can end with an elsif instead of an else if you want. if 0 { say "no" } elsif False { say "NO" } else { say "yes" } # says "yes" if 0 { say "no" } elsif True { say "YES" } else { say "yes" } # says "YES" if 0 { say "no" } elsif False { say "NO" } # does not say anything sub right { "Right!".say; True } sub wrong { "Wrong!".say; False } if wrong() { say "no" } elsif right() { say "yes" } else { say "maybe" } # The above says "Wrong!" then says "Right!" then says "yes" You cannot use the statement modifier form with else or elsif: 42.say if 0 else { 43.say } # syntax error  All the same rules for semicolons and newlines apply, consistently if 0 { say 0 }; elsif 1 { say 1 } else { say "how?" } ; # syntax error if 0 { say 0 } elsif 1 { say 1 }; else { say "how?" } ; # syntax error  if 0 { say 0 } elsif 1 { say 1 } else { say "how?" } ; # says "1"  if 0 { say 0 } elsif 1 { say 1 } else { say "how?" } ; # says "1" if 0 { say 0 } elsif 1 { say 1 } else { say "how?" } ; # says "1" if 0 { say "no" } elsif False { say "NO" } else { say "yes" } ; # says "yes" The whole thing either slips us an empty list (if no blocks were run) or returns the value produced by the block that did run: my$d = 0; say (1,
(if 0 { $d += 42; "two"; } elsif False {$d += 43; 2; }),
3, $d); # says "(1 3 0)" my$c = 0; say (1,
(if 0 { $c += 42; "two"; } else {$c += 43; 2; }),
3, $c); # says "(1 2 3 43)" It's possible to obtain the value of the previous expression inside an else, which could be from if or the last elsif if any are present: $_ = 1; if 0     { } else -> $a { "$_ $a".say } ; # says "1 0"$_ = 1; if False { } else -> $a { "$_ $a".say } ; # says "1 False" if False { } elsif 0 { } else ->$a { $a.say } ; # says "0" unless When you get sick of typing "if not (X)" you may use unless to invert the sense of a conditional statement. You cannot use else or elsif with unless because that ends up getting confusing. Other than those two differences unless works the same as #if: unless 1 { "1 is false".say } ; # does not say anything, since 1 is true  unless 1 "1 is false".say ; # syntax error, missing block  unless 0 { "0 is false".say } ; # says "0 is false"  unless 42.say and 1 { 43.say } ; # says "42" but does not say "43" 43.say unless 42.say and 0; # says "42" and then says "43" 43.say unless 42.say and 1; # says "42" but does not say "43"$_ = 1; unless 0 { $_.say } ; # says "1"$_ = 1; unless 0 -> $_ {$_.say }     ; # says "0"
$_ = 1; unless False ->$a { $a.say } ; # says "False" my$c = 0; say (1, (unless 0 { $c += 42; 2; }), 3,$c); # says "(1 2 3 42)"
my $d = 0; say (1, (unless 1 {$d += 42; 2; }), 3, $d); # says "(1 3 0)" with, orwith, without The with statement is like if but tests for definedness rather than truth. In addition, it topicalizes on the condition, much like given: with "abc".index("a") { .say } # prints 0 Instead of elsif, orwith may be used to chain definedness tests: # The below code says "Found a at 0" my$s = "abc";
with   $s.index("a") { say "Found a at$_" }
orwith $s.index("b") { say "Found b at$_" }
orwith $s.index("c") { say "Found c at$_" }
else                 { say "Didn't find a, b or c" }

You may intermix if-based and with-based clauses.

# This says "Yes"
if 0 { say "No" } orwith Nil { say "No" } orwith 0 { say "Yes" };

As with unless, you may use without to check for undefinedness, but you may not add an else clause:

my $answer = Any; without$answer { warn "Got: {$_.perl}" } There are also with and without statement modifiers: my$answer = (Any, True).roll;
say 42 with $answer; warn "undefined answer" without$answer;

when

The when block is similar to an if block and either or both can be used in an outer block, they also both have a "statement modifier" form. But there is a difference in how following code in the same, outer block is handled: When the when block is executed, control is passed to the enclosing block and following statements are ignored; but when the if block is executed, following statements are executed. (Note there are other ways to modify the default behavior of each which are discussed in other sections.) The following examples should illustrate the if or when block's default behavior assuming no special exit or other side effect statements are included in the if or when blocks:

{
if X {...} # if X is true in boolean context, block is executed
# following statements are executed regardless
}
{
when X {...} # if X is true in boolean context, block is executed
# and control passes to the outer block
# following statements are NOT executed
}


Should the if and when blocks above appear at file scope, following statements would be executed in each case.

There is one other feature a when has that if doesn't: the when's boolean context test defaults to $_ ~~ while the if's does not. That has an effect on how one uses the X in the when block without a value for$_ (it's Any in that case and Any smartmatches on True: Any ~~ True yields True). Consider the following:

{
my $a = 1; my$b = True;
when $a { say 'a' }; # no output when so$a { say 'a' }  # a (in "so $a" 'so' coerces$a to Boolean context True
# which matches with Any)
when $b { say 'b' }; # no output (this statement won't be run) }  Finally, when's statement modifier form does not effect execution of following statements either inside or outside of another block: say "foo" when X; # if X is true statement is executed # following statements are not affected  for The for loop iterates over a list, running the statements inside a block once on each iteration. If the block takes parameters, the elements of the list are provided as arguments. my @foo = 1..3; for @foo {$_.print } # prints each value contained in @foo
for @foo { .print }   # same thing, because .print implies a $_ argument for @foo { 42.print } # prints 42 as many times as @foo has elements Pointy block syntax or a placeholder may be used to name the parameter, of course. my @foo = 1..3; for @foo ->$item { print $item } for @foo { print$^item }            # same thing

Multiple parameters can be declared, in which case the iterator takes as many elements from the list as needed before running the block.

my @foo = 1..3;
for @foo.kv -> $idx,$val { say "$idx:$val" }
my %hash = <a b c> Z=> 1,2,3;
for %hash.kv -> $key,$val { say "$key =>$val" }
for 1, 1.1, 2, 2.1 { say "$^x <$^y" }  # says "1 < 1.1" then says "2 < 2.1"

Parameters of a pointy block can have default values, allowing to handle lists with missing elements.

my @list = 1,2,3,4;
for @list -> $a,$b = 'N/A', $c = 'N/A' { say "$a $b$c"
}
# OUTPUT: «1 2 3␤4 N/A N/A␤»

If the postfix form of for is used a block is not required and the topic is set for the statement list.

say „I $_ butterflies!“ for <♥ ♥ ♥>; # OUTPUT«I ♥ butterflies!␤I ♥ butterflies!␤I ♥ butterflies!␤» A for may be used on lazy lists – it will only take elements from the list when they are needed, so to read a file line by line, you could use: for$*IN.lines -> $line { .say }  Iteration variables are always lexical, so you don't need to use my to give them the appropriate scope. Also, they are read-only aliases. If you need them to be read-write, use <-> instead of ->. If you need to make$_ read-write in a for loop, do so explicitly.

my @foo = 1..3;
for @foo <-> $_ {$_++ }

A for loop can produce a List of the values produced by each run of the attached block. To capture these values, put the for loop in parenthesis or assign them to an array:

(for 1, 2, 3 { $_ * 2 }).say; # OUTPUT «(2 4 6)␤» my @a = do for 1, 2, 3 {$_ * 2 }; @a.say; # OUTPUT «[2 4 6]␤»
my @b = (for 1, 2, 3 { $_ * 2 }); @b.say; # OUTPUT: «[2 4 6]␤» gather/take gather is a statement or block prefix that returns a sequence of values. The values come from calls to take in the dynamic scope of the gather block. my @a = gather { take 1; take 5; take 42; } say join ', ', @a; # OUTPUT: «1, 5, 42␤» gather/take can generate values lazily, depending on context. If you want to force lazy evaluation use the lazy subroutine or method. Binding to a scalar or sigilless container will also force laziness. For example my @vals = lazy gather { take 1; say "Produced a value"; take 2; } say @vals[0]; say 'between consumption of two values'; say @vals[1]; # OUTPUT: # 1 # between consumption of two values # Produced a value # 2 gather/take is scoped dynamically, so you can call take from subs or methods that are called from within gather: sub weird(@elems, :$direction = 'forward') {
my %direction = (
forward  => sub { take $_ for @elems }, backward => sub { take$_ for @elems.reverse },
random   => sub { take $_ for @elems.pick(*) }, ); return gather %direction{$direction}();
}

say weird(<a b c>, :direction<backward> );          # OUTPUT: «(c b a)␤»

If values need to be mutable on the caller side, use take-rw.

supply/emit

Emits the invocant into the enclosing supply:

my $supply = supply { emit$_ for "foo", 42, .5;
}
$supply.tap: { say "received {.^name} ($_)";
}

# OUTPUT:
# received Rat (0.5)

given

The given statement is Perl 6's topicalizing keyword in a similar way that switch topicalizes in languages such as C. In other words, given sets $_ inside the following block. The keywords for individual cases are when and default. The usual idiom looks like this: my$var = (Any, 21, any <answer lie>).pick;
given $var { when 21 { say$_ * 2 }
when 'lie' { .say }
default { say 'default' }
}

The given statement is often used alone:

given 42 { .say; .Numeric; }

This is a lot more understandable than:

{ .say; .Numeric; }(42)

default and when

A block containing a default statement will be left immediately when the sub-block after the default statement is left. It is as though the rest of the statements in the block are skipped.

given 42 {
"This says".say;
$_ == 42 and ( default { "This says, too".say; 43; } ); "This never says".say; } # The above block evaluates to 43 A when statement will also do this (but a when statement modifier will not.) In addition, when statements smartmatch the topic ($_) against a supplied expression such that it is possible to check against values, regular expressions, and types when specifying a match.

for 42, 43, "foo", 44, "bar" {
when Int { .say }
when /:i ^Bar/ { .say }
default  { say "Not an Int or a Bar" }
}
# OUTPUT: «42␤43␤Not an Int or a Bar␤44␤Bar␤»

In this form, the given/when construct acts much like a set of if/elsif/else statements. Be careful with the order of the when statements. The following code says "Int" not 42.

given 42 {
when Int { say "Int" }
when 42  { say 42 }
default  { say "huh?" }
}
# OUTPUT: «Int␤»

When a when statement or default statement causes the outer block to return, nesting when or default blocks do not count as the outer block, so you can nest these statements and still be in the same "switch" just so long as you do not open a new block:

given 42 {
when Int {
when 42  { say 42 }
say "Int"
}
default  { say "huh?" }
}
# OUTPUT: «42»

when statements can smartmatch against Signatures.

succeed

Both proceed and succeed are meant to be used only from inside when or default blocks.

The proceed statement will immediately leave the when or default block, skipping the rest of the statements, and resuming after the block. This prevents the when or default from exiting the outer block.

given * {
default {
proceed;
"This never says".say
}
}
"This says".say;


This is most often used to enter multiple when blocks. proceed will resume matching after a successful match, like so:

given 42 {
when Int   { say "Int"; proceed }
when 42    { say 42 }
when 40..* { say "greater than 40" }
default    { say "huh?" }
}
# OUTPUT: «Int␤»
# OUTPUT: «42␤»

Note that the when 40..* match didn't occur. For this to match such cases as well, one would need a proceed in the when 42 block.

This is not like a C switch statement, because the proceed does not merely enter the directly following block, it attempts to match the given value once more, consider this code:

given 42 {
when Int { "Int".say; proceed }
when 43  { 43.say }
when 42  { 42.say }
default  { "got change for an existential answer?".say }
}
# OUTPUT: «Int␤»
# OUTPUT: «42␤»

...which matches the Int, skips 43 since the value doesn't match, matches 42 since this is the next positive match, but doesn't enter the default block since the when 42 block doesn't contain a proceed.

By contrast, the succeed keyword short-circuits execution and exits the entire given block at that point. It may also take an argument to specify a final value for the block.

given 42 {
when Int {
say "Int";
succeed "Found";
say "never this!";
}
when 42 { say 42 }
default { say "dunno?" }
}
# OUTPUT: «Int␤»

If you are not inside a when or default block, it is an error to try to use proceed or succeed. Also remember, the when statement modifier form does not cause any blocks to be left, and any succeed or proceed in such a statement applies to the surrounding clause, if there is one:

given 42 {
{ say "This says" } when Int;
"This says too".say;
when * > 41 {
{ "And this says".say; proceed } when * > 41;
"This never says".say;
}
"This also says".say;
}

given as a statement

given can follow a statement to set the topic in the statement it follows.

.say given "foo";
# OUTPUT: «foo␤»

printf "%s %02i.%02i.%i",
<Mo Tu We Th Fr Sa Su>[.day-of-week - 1],
.day,
.month,
.year
given DateTime.now;
# OUTPUT: «Sa 03.06.2016»

loop

The loop statement takes three statements in parentheses separated by ; that take the role of initializer, conditional and incrementer. The initializer is executed once and any variable declaration will spill into the surrounding block. The conditional is executed once per iteration and coerced to Bool, if False the loop is stopped. The incrementer is executed once per iteration.

loop (my $i = 0;$i < 10; $i++) { say$i;
}

The infinite loop does not require parentheses.

loop { say 'forever' }


The loop statement may be used to produce values from the result of each run of the attached block if it appears in lists:

(loop ( my $i = 0;$i++ < 3;) { $i * 2 }).say; # OUTPUT: «(2 4 6)␤» my @a = (loop ( my$j = 0; $j++ < 3;) {$j * 2 }); @a.say;   # OUTPUT: «[2 4 6]␤»
my @b = do loop ( my $k = 0;$k++ < 3;) { $k * 2 }; @b.say; # same thing Unlike a for loop, one should not rely on whether returned values are produced lazily. It would probably be best to use eager to guarantee that a loop whose return value may be used actually runs: sub heads-in-a-row { (eager loop (; 2.rand < 1;) { "heads".say }) } while, until The while statement executes the block as long as its condition is true. So my$x = 1;
while $x < 4 { print$x++;
}
print "\n";

# OUTPUT: «123␤»

Similarly, the until statement executes the block as long as the expression is false.

my $x = 1; until$x > 3 {
print $x++; } print "\n"; # OUTPUT: «123␤» The condition for while or until can be parenthesized, but there must be a space between the keyword and the opening parenthesis of the condition. Both while and until can be used as statement modifiers. E. g. my$x = 42;
$x-- while$x > 12

Also see repeat/while and repeat/until below.

All these forms may produce a return value the same way loop does.

repeat/while, repeat/until

Executes the block at least once and, if the condition allows, repeats that execution. This differs from while/until in that the condition is evaluated at the end of the loop, even if it appears at the front.

my $x = -42; repeat {$x++;
} while $x < 5;$x.say; # OUTPUT: «5␤»

repeat {
$x++; } while$x < 5;
$x.say; # OUTPUT: «6␤» repeat while$x < 10 {
$x++; }$x.say; # OUTPUT: «10␤»

repeat while $x < 10 {$x++;
}
$x.say; # OUTPUT: «11␤» repeat {$x++;
} until $x >= 15;$x.say; # OUTPUT: «15␤»

repeat {
$x++; } until$x >= 15;
$x.say; # OUTPUT: «16␤» repeat until$x >= 20 {
$x++; }$x.say; # OUTPUT: «20␤»

repeat until $x >= 20 {$x++;
}
loop {
last if $guard-- <= 0; once { put 'once' }; print 'many' } # OUTPUT: «once␤manymanymany» This works per "clone" of the containing code object, so: ({ once 42.say } xx 3).map: {$_(), $_()}; # says 42 thrice Note that this is not a thread-safe construct when the same clone of the same block is run by multiple threads. Also remember that methods only have one clone per class, not per object. quietly A quietly block will suppress all warnings generated in it. quietly { warn 'kaput!' }; warn 'still kaput!'; # OUTPUT: «still kaput! [...]␤» Any warning generated from any routine called from within the block will also be suppressed: sub told-you { warn 'hey...' }; quietly { told-you; warn 'kaput!' }; warn 'Only telling you now!' # OUTPUT: «Only telling you now!␤ [...] ␤» LABELs while, until, loop and for loops can all take a label, which can be used to identify them for next, last, and redo. Nested loops are supported, for instance: OUTAHERE: while True { for 1,2,3 ->$n {
last OUTAHERE if $n == 2; } } Labels can be used also within nested loops to name each loop, for instance: OUTAHERE: loop ( my$i = 1; True; $i++ ) { OUTFOR: for 1,2,3 ->$n {
# exits the for loop before its natural end
last OUTFOR if $n == 2; } # exits the infinite loop last OUTAHERE if$i >= 2;
}


next

The next command starts the next iteration of the loop. So the code

my @x = 1, 2, 3, 4, 5;
for @x -> $x { next if$x == 3;
print $x; }  prints "1245". If the NEXT phaser is present, it runs before the next iteration: my Int$i = 0;
while ($i < 10) { if ($i % 2 == 0) {
next;
}

say "$i is odd."; NEXT {$i++;
}
}
# OUTPUT: «1 is odd.␤3 is odd.␤5 is odd.␤7 is odd.␤9 is odd.␤»


last

The last command immediately exits the loop in question.

my @x = 1, 2, 3, 4, 5;
for @x -> $x { last if$x == 3;
print $x; }  prints "12". If the LAST phaser is present, it runs before exiting the loop: my Int$i = 1;
while ($i < 10) { if ($i % 5 == 0) {
last;
}

LAST {
say "The last number was $i."; } NEXT {$i++;
}
}
# OUTPUT: «The last number was 5.␤»


redo

The redo command restarts the loop block without evaluating the conditional again.

loop {
my $x = prompt("Enter a number"); redo unless$x ~~ /\d+/;
last;
}


45 Data structures

How Perl 6 deals with data structures and what we can expect from them

Scalar structures

Some classes do not have any internal structure and to access parts of them, specific methods have to be used. Numbers, strings, and some other monolithic classes are included in that class. They use the $sigil, although complex data structures can also use it. my$just-a-number = 7;
my $just-a-string = "8"; There is a Scalar class, which is used internally to assign a default value to variables declared with the$ sigil.

my $just-a-number = 333; say$just-a-number.VAR.^name; # OUTPUT: «Scalar␤»

Any complex data structure can be scalarized by using the item contextualizer $: (1, 2, 3,$(4, 5))[3].VAR.^name.say; # OUTPUT: «Scalar␤»

However, this means that it will be treated as such in the context they are. You can still access its internal structure.

(1, 2, 3, $(4, 5))[3][0].say; # OUTPUT: «4␤» An interesting side effect, or maybe intended feature, is that scalarization conserves identity of complex structures. for ^2 { my @list = (1, 1); say @list.WHICH; } # OUTPUT: «Array|93947995146096␤Array|93947995700032␤» Every time (1, 1) is assigned, the variable created is going to be different in the sense that === will say it is; as it is shown, different values of the internal pointer representation are printed. However for ^2 { my$list = (1, 1);
say $list.WHICH } # OUTPUT: «List|94674814008432␤List|94674814008432␤» In this case,$list is using the Scalar sigil and thus will be a Scalar. Any scalar with the same value will be exactly the same, as shown when printing the pointers.

Complex data structures

Complex data structures fall in two different broad categories: Positional, or list-like and Associative, or key-value pair like, according to how you access its first-level elements. In general, complex data structures, including objects, will be a combination of both, with object properties assimilated to key-value pairs. While all objects subclass Mu, in general complex objects are instances of subclasses of Any. While it is theoretically possible to mix in Positional or Associative without doing so, most methods applicable to complex data structures are implemented in Any.

Navigating these complex data structures is a challenge, but Perl 6 provides a couple of functions that can be used on them: deepmap and duckmap. While the former will go to every single element, in order, and do whatever the block passed requires,

say [[1, 2, [3, 4]],[[5, 6, [7, 8]]]].deepmap( *.elems );
# OUTPUT: «[[1 1 [1 1]] [1 1 [1 1]]]␤»

which returns 1 because it goes to the deeper level and applies elems to them, deepmap can perform more complicated operations:

say [[1, 2, [3, 4]], [[5, 6, [7, 8]]]].duckmap:
-> $array where .elems == 2 {$array.elems };
# OUTPUT: «[[1 2 2] [5 6 2]]␤»

In this case, it dives into the structure, but returns the element itself if it does not meet the condition in the block (1, 2), returning the number of elements of the array if it does (the two 2s at the end of each subarray).

Since d(eep|uck)map are Any methods, they also apply to Associative arrays:

say %( first => [1, 2], second => [3,4] ).deepmap( *.elems );
# OUTPUT: «{first => [1 1], second => [1 1]}␤»

Only in this case, they will be applied to every list or array that is a value, leaving the keys alone.

Positional and Associative can be turned into each other.

say %( first => [1, 2], second => [3,4] ).list[0];
# OUTPUT: «second => [3 4]␤»

However, in this case, and for Rakudo >= 2018.05, it will return a different value every time it runs. A hash will be turned into a list of the key-value pairs, but it is guaranteed to be disordered. You can also do the operation in the opposite direction, as long as the list has an even number of elements (odd number will result in an error):

say <a b c d>.Hash # OUTPUT: «{a => b, c => d}␤»

But

say <a b c d>.Hash.kv # OUTPUT: «(c d a b)␤»

will obtain a different value every time you run it; kv turns every Pair into a list.

Complex data structures are also generally Iterable. Generating an iterator out of them will allow the program to visit the first level of the structure, one by one:

.say for 'א'..'ס'; # OUTPUT: «א␤ב␤ג␤ד␤ה␤ו␤ז␤ח␤ט␤י␤ך␤כ␤ל␤ם␤מ␤ן␤נ␤ס␤»

'א'..'ס' is a Range, a complex data structure, and with for in front it will iterate until the list is exhausted. You can use for on your complex data structures by overriding the iterator method (from role Iterable):

class SortedArray is Array {
method iterator() {
self.sort.iterator
}
};
my @thing := SortedArray.new([3,2,1,4]);
.say for @thing; # OUTPUT: «1␤2␤3␤4␤»

for calls directly the iterator method on @thing making it return the elements of the array in order. Much more on iterating on the page devoted to it.

Functional structures

Perl 6 is a functional language and, as such, functions are first-class data structures. Functions follow the Callable role, which is the 4th element in the quartet of fundamental roles. Callable goes with the & sigil, although in most cases it is elided for the sake of simplicity; this sigil elimination is always allowed in the case of Callables.

my &a-func= { (^($^þ)).Seq }; say a-func(3), a-func(7); # OUTPUT: «(0 1 2)(0 1 2 3 4 5 6)␤» Blocks are the simplest callable structures, since Callables cannot be instantiated. In this case we implement a block that logs events and can retrieve them: my$logger = -> $event,$key = Nil  {
state %store;
if ( $event ) { %store{ DateTime.new( now ) } =$event;
} else {
%store.keys.grep( /$key/ ) } }$logger( "Stuff" );
$logger( "More stuff" ); say$logger( Nil, "2018-05-28" ); # OUTPUT: «(Stuff More stuff)␤»

A Block has a Signature, in this case two arguments, the first of which is the event that is going to be logged, and the second is the key to retrieve the events. They will be used in an independent way, but its intention is to showcase the use of a state variable that is kept from every invocation to the next. This state variable is encapsulated within the block, and cannot be accessed from outside except by using the simple API the block provides: calling the block with a second argument. The two first invocations log two events, the third invocation at the bottom of the example use this second type of call to retrieve the stored values. Blocks can be cloned:

my $clogger =$logger.clone;
$clogger( "Clone stuff" );$clogger( "More clone stuff" );
say $clogger( Nil, "2018-05-28" ); # OUTPUT: «(Clone stuff More clone stuff)␤»  And cloning will reset the state variable; instead of cloning, we can create façades that change the API. For instance, eliminate the need to use Nil as first argument to retrieve the log for a certain date: my$gets-logs = $logger.assuming( Nil, * );$logger( %(changing => "Logs") );
say $gets-logs( "2018-05-28" ); # OUTPUT: «({changing => Logs} Stuff More stuff)␤»  assuming wraps around a block call, giving a value (in this case, Nil) to the arguments we need, and passing on the arguments to the other arguments we represent using *. In fact, this corresponds to the natural language statement "We are calling$logger assuming the first argument is Nil". We can slightly change the appearance of these two Blocks to clarify they are actually acting on the same block:

my $Logger =$logger.clone;
my $Logger::logs =$Logger.assuming( *, Nil );
my $Logger::get =$Logger.assuming( Nil, * );
$Logger::logs( <an array> );$Logger::logs( %(key => 42) );
say $Logger::get( "2018-05-28" );  Although :: is generally used for invocation of class methods, it is actually a valid part of the name of a variable. In this case we use them conventionally to simply indicate$Logger::logs and $Logger::get are actually calling$Logger, which we have capitalized to use a class-like appearance. The point of this tutorial is that using functions as first-class citizens, together with the use of state variables, allows the use of certain interesting design patterns such as this one.

As such first class data structures, callables can be used anywhere another type of data can.

my @regex-check = ( /<alnum>/, /<alpha>/, /<punct>/ );
say @regex-check.map: "33af" ~~ *;
# OUTPUT: «(｢3｣␤ alnum => ｢3｣ ｢a｣␤ alpha => ｢a｣ Nil)␤»

Regexes are actually a type of callable:

say /regex/.does( Callable ); # OUTPUT: «True␤»

And in the example above we are calling regexes stored in an array, and applying them to a string literal.

Callables are composed by using the function composition operator ∘:

my $typer = ->$thing { $thing.^name ~ ' → ' ~$thing };
my $Logger::withtype =$Logger::logs ∘ $typer;$Logger::withtype( Pair.new( 'left', 'right' ) );
$Logger::withtype( ¾ ); say$Logger::get( "2018-05-28" );
# OUTPUT: «(Pair → left right Rat → 0.75)␤»


say $one-fraction; # OUTPUT: «0.333333␤»  On the other hand, my OneOver$ = ⅔; will cause a type-check error. Subsets can use Whatever, that is, *, to refer to the argument; but this will be instantiated every time you use it to a different argument, so if we use it twice in the definition we would get an error. In this case we are using the topic single variable, $_, to check the instantiation. Subsetting can be done directly, without the need of declaring it, in signatures. Infinite structures and laziness It might be assumed that all the data contained in a data structure is actually there. That is not necessarily the case: in many cases, for efficiency reasons or simply because it is not possible, the elements contained in a data structure only jump into existence when they are actually needed. This computation of items as they are needed is called reification. # A list containing infinite number of un-reified Fibonacci numbers: my @fibonacci = 1, 1, * + * … ∞; # We reify 10 of them, looking up the first 10 of them with array index: say @fibonacci[^10]; # OUTPUT: «(1 1 2 3 5 8 13 21 34 55)␤» # We reify 5 more: 10 we already reified on previous line, and we need to # reify 5 more to get the 15th element at index 14. Even though we need only # the 15th element, the original Seq still has to reify all previous elements: say @fibonacci[14]; # OUTPUT: «987␤» Above we were reifying a Seq we created with the sequence operator, but other data structures use the concept as well. For example, an un-reified Range is just the two end points. In some languages, calculating the sum of a huge range is a lengthy and memory-consuming process, but Perl 6 calculates it instantly: say sum 1 .. 9_999_999_999_999; # OUTPUT: «49999999999995000000000000␤» Why? Because the sum can be calculated without reifying the Range; that is, without figuring out all the elements it contains. This is why this feature exists. You can even make your own things reify-on-demand, using gather and take: my$seq = gather {
say "About to make 1st element"; take 1;
say "About to make 2nd element"; take 2;
}
say "Let's reify an element!";
say $seq[0]; say "Let's reify more!"; say$seq[1];
say "Both are reified now!";
say $seq[^2]; # OUTPUT: # Let's reify an element! # About to make 1st element # 1 # Let's reify more! # About to make 2nd element # 2 # Both are reified now! # (1 2) Following the output above, you can see the print statements inside the gather got executed only when we reified the individual elements while looking up an element. Also note that the elements got reified just once. When we printed the same elements again on the last line of the example, the messages inside gather was no longer printed. This is because the construct used already-reified elements from the Seq's cache. Note that above we assigned the gather to a Scalar container (the$ sigil), not the Positional one (the @ sigil). The reason is that the @-sigiled variables are mostly eager. What this means is they reify the stuff assigned to them right away most of the time. The only time they don't do it is when the items are known to be is-lazy, like our sequence generated with infinity as the end point. Were we to assign the gather to a @-variable, the say statements inside of it would've been printed right away.

Another way to fully-reify a list, is by calling .elems on it. This is the reason why checking whether a list contains any items is best done by using .Bool method (or just using if @array { … }), since you don't need to reify all the elements to find out if there are any of them.

There are times where you do want to fully-reify a list before doing something. For example, the IO::Handle.lines returns a Seq. The following code contains a bug; keeping reification in mind, try to spot it:

my $fh = "/tmp/bar".IO.open; my$lines = $fh.lines; close$fh;
say $lines[0];  We open a filehandle, then assign return of .lines to a Scalar variable, so the returned Seq does not get reified right away. We then close the filehandle, and try to print an element from$lines.

The bug in the code is by the time we reify the $lines Seq on the last line, we've already closed the filehandle. When the Seq's iterator tries to generate the item we've requested, it results in the error about attempting to read from a closed handle. So, to fix the bug we can either assign to a @-sigiled variable or call .elems on$lines before closing the handle:

my $fh = "/tmp/bar".IO.open; my @lines =$fh.lines;
close $fh; say @lines[0]; # no problem!  We can also use any function whose side effect is reification, like .elems mentioned above: my$fh = "/tmp/bar".IO.open;
my $lines =$fh.lines;
say "Read $lines.elems() lines"; # reifying before closing handle close$fh;
say $lines[0]; # no problem!  Using eager will also reify the whole sequence: my$fh = "/tmp/bar".IO.open;
my $lines = eager$fh.lines; # Uses eager for reification.
close $fh; say$lines[0];


Introspection

Languages that allow introspection like Perl 6 have functionalities attached to the type system that let the developer access container and value metadata. This metadata can be used in a program to carry out different actions depending on their value. As it is obvious from the name, metadata are extracted from a value or container via the metaclass.

my $any-object = "random object"; my$metadata = $any-object.HOW; say$metadata.^mro;                   # OUTPUT: «((ClassHOW) (Any) (Mu))␤»
say $metadata.can($metadata, "uc" ); # OUTPUT: «(uc uc)␤»

With the first say we show the class hierarchy of the metamodel class, which in this case is Metamodel::ClassHOW. It inherits directly from Any, meaning any method there can be used; it also mixes in several roles which can give you information about the class structure and functions. But one of the methods of that particular class is can, which we can use to look up whether the object can use the uc (uppercase) method, which it obviously can. However, it might not be so obvious in some other cases, when roles are mixed in directly into a variable. For instance, in the case of %hash-plus defined above:

say %hash-plus.^can("last"); # OUTPUT: «(last)␤»


In this case we are using the syntactic sugar for HOW.method, ^method, to check if your data structure responds to that method; the output, which shows the name of the methods that match, certifies that we can use it.

See also this article on class introspection on how to access class properties and methods, and use it to generate test data for a class; this Advent Calendar article describes the meta-object protocol extensively.

46 Date and time functions

Processing date and time in Perl 6

Perl 6 includes several classes that deal with temporal information: Date, DateTime, Instant and Duration. The three first are dateish, so they mix in the Dateish role, which defines all methods and properties that classes that deal with date should assume. It also includes a class hierarchy of exceptions rooted in X::Temporal.

We will try to illustrate these classes in the next (somewhat extended) example, which can be used to process all files in a directory (by default .) with a particular extension (by default .p6) in an directory, sort them according to their age, and compute how many files have been created per month and how many were modified in certain periods expressed in ranges of months:

sub MAIN( $path = ".",$extension = "p6" ) {
my DateTime $right = DateTime.now; my %metadata; my %files-month; my %files-period; for dir($path).grep( / \.$extension$/ ) -> $file { CATCH { when X::Temporal { say "Date-related problem", .payload } when X::IO { say "File-related problem", .payload } default { .payload.say } } my Instant$modified = $file.modified; my Instant$accessed = $file.accessed; my Duration$duration = $accessed -$modified;
my $age =$right - DateTime($accessed); my$time-of-day = $file.changed.DateTime.hh-mm-ss but Dateish; my$file-changed-date =  $file.changed.Date; %metadata{$file} = %( modified => $modified, accessed =>$accessed,
age => $age, difference =>$duration,
changed-tod => $time-of-day, changed-date =>$file-changed-date);
%files-month{$file-changed-date.month}++; given$file-changed-date {
when Date.new("2018-01-01")..^Date.new("2018-04-01") { %files-period<pre-grant>++}
when Date.new("2018-04-01")..Date.new("2018-05-31") { %files-period<grant>++}
default { %files-period<post-grant>++};
}
}

%metadata.sort( { $^a.value<age> <=>$^b.value<age> } ).map: {
say $^x.key, ", ",$^x.value<accessed modified age difference changed-tod changed-date>.join(", ");
};
%files-month.keys.sort.map: {
say "Month $^x → %files-month{$^x}"
};

%files-period.keys.map: {
say "Period $^x → %files-period{$^x}"
};
}


DateTime is used in line 6 to contain the current date and time returned by now.

A CATCH phaser is declared in lines 11 to 15. Its main mission is to distinguish between DateTime-related exceptions and other types. These kind of exception can arise from invalid formats or timezone clashes. Barring some corruption of the file attributes, both are impossible, but in any case they should be caught and separated from other types of exceptions.

We use Instants in lines 16-17 to represent the moment in which the files where accessed and modified. An Instant is measured in atomic seconds, and is a very low-level description of a time event; however, the Duration declared in line 18 represent the time transcurred among two different Instants, and we will be using it to represent the age.

For some variables we might be interested in dealing with them with some dateish traits. $time-of-day contains the time of the day the file was changed; changed will return an Instant, but it is converted into a Date (which is Dateish while Instant is not) and then the time of day is extracted from that.$time-of-day will have «Str+{Dateish}␤» type.

We will use the date in this variable to find out the period when the files were changed.

Date.new("2018-01-01")..^Date.new("2018-04-01")

creates a date Range and $file-changed-date is smartmatched against it. Dates can be used this way; in this case it creates a Range that excludes its last element. This very variable is also used to compute the month of the year when the file was modified. Date is obviously Dateish and then has the month method to extract that property from it. Duration objects can be compared. This is used in  %metadata.sort({$^a.value<age> <=> $^b.value<age> });  to sort the files by age. 47 Enumeration An example using the enum type In Perl 6 the enum type is much more complex than in some other languages, and the details are found in its type description here: enum. This short document will give a simple example of its use as is the usual practice in C-like languages. Say we have a program that needs to write to various directories; we want a function that, given a directory name, tests it for (1) its existence and (2) whether it can be written to by the user of the program; this implies that there are three possible states from the user perspective: either you can write (CanWrite), or there is no directory (NoDir) or the directory exists, but you cannot write (NoWrite). The results of the test will determine what actions the program takes next. enum DirStat <CanWrite NoDir NoWrite>; sub check-dir-status($dir --> DirStat) {
if $dir.IO.d { # dir exists, can the program user write to it? my$f = "$dir/.tmp"; spurt$f, "some text";
CATCH {
# unable to write for some reason
return NoWrite;
}
# if we get here we must have successfully written to the dir
unlink $f; return CanWrite; } # if we get here the dir must not exist return NoDir; } # test each of three directories by a non-root user my$dirs =
'/tmp',  # normally writable by any user
'/',     # writable only by root
'~/tmp'; # a non-existent dir in the user's home dir
for $dirs ->$dir {
my $stat = check-dir-status$dir;
say "status of dir '$dir':$stat";
if $stat ~~ CanWrite { say " user can write to dir:$dir";
}
}
# output
#   status of dir '/tmp': CanWrite
#     user can write to dir: /tmp
#   status of dir '/': NoWrite
#   status of dir '~/tmp': NoDir


48 Exceptions

Using exceptions in Perl 6

Exceptions in Perl 6 are objects that hold information about errors. An error can be, for example, the unexpected receiving of data or a network connection no longer available, or a missing file. The information that an exception objects store is, for instance, a human-readable message about the error condition, the backtrace of the raising of the error, and so on.

All built-in exceptions inherit from Exception, which provides some basic behavior, including the storage of a backtrace and an interface for the backtrace printer.

Ad hoc exceptions can be used by calling die with a description of the error:

die "oops, something went wrong";
# RESULT: «oops, something went wrong in block <unit> at my-script.p6:1␤»

It is worth noting that die prints the error message to the standard error $*ERR. Typed exceptions Typed exceptions provide more information about the error stored within an exception object. For example, if while executing .zombie copy on an object, a needed path foo/bar becomes unavailable, then an X::IO::DoesNotExist exception can be raised: die X::IO::DoesNotExist.new(:path("foo/bar"), :trying("zombie copy")) # RESULT: «Failed to find 'foo/bar' while trying to do '.zombie copy' # in block <unit> at my-script.p6:1» Note how the object has provided the backtrace with information about what went wrong. A user of the code can now more easily find and correct the problem. Catching exceptions It's possible to handle exceptional circumstances by supplying a CATCH block: die X::IO::DoesNotExist.new(:path("foo/bar"), :trying("zombie copy")); CATCH { when X::IO {$*ERR.say: "some kind of IO exception was caught!" }
}

# OUTPUT: «some kind of IO exception was caught!»

Here, we are saying that if any exception of type X::IO occurs, then the message some kind of IO exception was caught! will be sent to stderr, which is what $*ERR.say does, getting displayed on whatever constitutes the standard error device in that moment, which will probably be the console by default. A CATCH block uses smartmatching similar to how given/when smartmatches on options, thus it's possible to catch and handle various categories of exceptions inside a when block. To handle all exceptions, use a default statement. This example prints out almost the same information as the normal backtrace printer. CATCH { default {$*ERR.say: .payload;
for .backtrace.reverse {
next if .file.starts-with('SETTING::');
next unless .subname;
$*ERR.say: " in block {.subname} at {.file} line {.line}"; } } } Note that the match target is a role. To allow user defined exceptions to match in the same manner, they must implement the given role. Just existing in the same namespace will look alike but won't match in a CATCH block. Exception handlers and enclosing blocks After a CATCH has handled the exception, the block enclosing the CATCH block is exited. In other words, even when the exception is handled successfully, the rest of the code in the enclosing block will never be executed. die "something went wrong ..."; CATCH { # will definitely catch all the exception default { .Str.say; } } say "This won't be said."; # but this line will be never reached since # the enclosing block will be exited immediately # OUTPUT: «something went wrong ...␤» Compare with this: CATCH { CATCH { default { .Str.say; } } die "something went wrong ..."; } say "Hi! I am at the outer block!"; # OUTPUT: «Hi! I am at the outer block!␤» See Resuming of exceptions, for how to return control back to where the exception originated. try blocks A try block is a normal block with the use fatal pragma turned on and an implicit CATCH block that drops the exception, which means you can use it to contain them. { my$x = +"a";
say $x.^name; } # OUTPUT: «Failure␤» try { my$x = +"a";
say $x.^name; }  Any exception that is thrown in such a block will be caught by the implicit CATCH block or a CATCH block provided by the user. In the latter case, any unhandled exception will be rethrown. If you choose not to handle the exception, they will be contained by the block. try { die "Tough luck"; say "Not gonna happen"; } try { fail "FUBAR"; }  In both try blocks above, exceptions will be contained within the block, but the say statement will not be run. We can handle them, though: class E is Exception { method message() { "Just stop already!" } } try { E.new.throw; # this will be local say "This won't be said."; } say "I'm alive!"; try { CATCH { when X::AdHoc { .Str.say; .resume } } die "No, I expect you to DIE Mr. Bond!"; say "I'm immortal."; E.new.throw; say "No, you don't!"; } Which would output: I'm alive! No, I expect you to DIE Mr. Bond! I'm immortal. Just stop already! in block <unit> at exception.p6 line 21  Since the CATCH block is handling just the X::AdHoc exception thrown by the die statement, but not the E exception. In the absence of a CATCH block, all exceptions will be contained and dropped, as indicated above. resume will resume execution right after the exception has been thrown; in this case, in the die statement. Please consult the section on resuming of exceptions for more information on this. A try-block is a normal block and as such treats its last statement as the return value of itself. We can therefore use it as a right-hand side. say try { +"99999" } // "oh no"; # OUTPUT: «99999␤» say try { +"hello" } // "oh no"; # OUTPUT: «oh no␤»  Try blocks support else blocks indirectly by returning the return value of the expression or Nil if an exception was thrown. with try +"♥" { say "this is my number:$_"
} else {
say "not my number!"
}
# OUTPUT: «not my number!␤»

try can also be used with a statement instead of a block:

say try "some-filename.txt".IO.slurp // "sane default";
# OUTPUT: «sane default␤»


What try actually causes is, via the use fatal pragma, an immediate throw of the exceptions that happen within its scope, but by doing so the CATCH block is invoked from the point where the exception is thrown, which defines its scope.

my $error-code = "333"; sub bad-sub { die "Something bad happened"; } try { my$error-code = "111";

CATCH {
default {
say "Error $error-code ", .^name, ': ',.Str } } } # OUTPUT: «Error 111 X::AdHoc: Something bad happened␤»  Throwing exceptions Exceptions can be thrown explicitly with the .throw method of an Exception object. This example throws an AdHoc exception, catches it and allows the code to continue from the point of the exception by calling the .resume method. { X::AdHoc.new(:payload<foo>).throw; "OHAI".say; CATCH { when X::AdHoc { .resume } } } "OBAI".say; # OUTPUT: «OHAI␤OBAI␤» If the CATCH block doesn't match the exception thrown, then the exception's payload is passed on to the backtrace printing mechanism. { X::AdHoc.new(:payload<foo>).throw; "OHAI".say; CATCH { } } "OBAI".say; # RESULT: «foo # in block <unit> at my-script.p6:1» This next example doesn't resume from the point of the exception. Instead, it continues after the enclosing block, since the exception is caught, and then control continues after the CATCH block. { X::AdHoc.new(:payload<foo>).throw; "OHAI".say; CATCH { when X::AdHoc { } } } "OBAI".say; # OUTPUT: «OBAI␤» throw can be viewed as the method form of die, just that in this particular case, the sub and method forms of the routine have different names. Resuming of exceptions Exceptions interrupt control flow and divert it away from the statement following the statement that threw it. Any exception handled by the user can be resumed and control flow will continue with the statement following the statement that threw the exception. To do so, call the method .resume on the exception object. CATCH { when X::AdHoc { .resume } } # this is step 2 die "We leave control after this."; # this is step 1 say "We have continued with control flow."; # this is step 3 Resuming will occur right after the statement that has caused the exception, and in the innermost call frame: sub bad-sub { die "Something bad happened"; return "not returning"; } { my$return = bad-sub;
say "Returned $return"; CATCH { default { say "Error ", .^name, ': ',.Str;$return = '0';
.resume;

}
}
}
# OUTPUT:
# Returned not returning


}
}

# prints "message\n" to $*ERR and exits, no backtrace Control exceptions Control exceptions are thrown by certain keywords and are handled either automatically or by the appropriate phaser. Any unhandled control exception is converted to a normal exception. { return; CATCH { default {$*ERR.say: .^name, ': ',.Str } } }

# OUTPUT: «X::ControlFlow::Return: Attempt to return outside of any Routine␤»
# was CX::Return

49 Functions

Functions and functional programming in Perl 6

Routines are one of the means Perl 6 has to reuse code. They come in several forms, most notably methods, which belong in classes and roles and are associated with an object; and functions (also called subroutines or subs, for short), which can be called independently of objects.

Subroutines default to lexical (my) scoping, and calls to them are generally resolved at compile time.

Subroutines can have a signature, also called parameter list, which specifies which, if any, arguments the signature expects. It can specify (or leave open) both the number and types of arguments, and the return value.

Introspection on subroutines is provided via Routine.

Defining/Creating/Using functions

Subroutines

The basic way to create a subroutine is to use the sub declarator followed by an optional identifier:

sub my-func { say "Look ma, no args!" }
my-func;

The sub declarator returns a value of type Sub that can be stored in any container:

my &c = sub { say "Look ma, no name!" }
c;     # OUTPUT: «Look ma, no name!␤»

my Any:D $f = sub { say 'Still nameless...' }$f();  # OUTPUT: «Still nameless...␤»

my Code \a = sub { say ‚raw containers don't implement postcircumfix:<( )>‘ };
a.();  # OUTPUT: «raw containers don't implement postcircumfix:<( )>␤»

The declarator sub will declare a new name in the current scope at compile time. As such any indirection has to be resolved at compile time:

constant aname = 'foo';
sub ::(aname) { say 'oi‽' };
foo;

This will become more useful once macros are added to Perl 6.

To have the subroutine take arguments, a signature goes between the subroutine's name and its body, in parentheses:

sub exclaim  ($phrase) { say$phrase  ~  "!!!!"
}
exclaim "Howdy, World";


By default, subroutines are lexically scoped. That is, sub foo {...} is the same as my sub foo {...} and is only defined within the current scope.

sub escape($str) { # Puts a slash before non-alphanumeric characters S:g[<-alpha -digit>] = "\\$/" given $str } say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤» { sub escape($str) {
# Writes each non-alphanumeric character in its hexadecimal escape
S:g[<-alpha -digit>] = "\\x[{ $/.ord.base(16) }]" given$str
}

say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤»
}

# Back to original escape function
say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»


Subroutines don't have to be named. If unnamed, they're called anonymous subroutines.

say sub ($a,$b) { $a ** 2 +$b ** 2 }(3, 4) # OUTPUT: «25␤»

But in this case, it's often desirable to use the more succinct block syntax. Subroutines and blocks can be called in place, as in the example above.

say -> $a,$b { $a ** 2 +$b ** 2 }(3, 4)    # OUTPUT: «25␤»

Or even

say { $^a ** 2 +$^b ** 2 }(3, 4)            # OUTPUT: «25␤»

Whenever you see something like { $_ + 42 }, ->$a, $b {$a ** $b }, or {$^text.indent($:spaces) }, that's Block syntax. It's used after every if, for, while, etc. for 1, 2, 3, 4 ->$a, $b { say$a ~ $b; } # OUTPUT: «12␤34␤» They can also be used on their own as anonymous blocks of code. say {$^a ** 2 + $^b ** 2}(3, 4) # OUTPUT: «25␤» For block syntax details, see the documentation for the Block type. Signatures The parameters that a function accepts are described in its signature. sub format (Str$s)  { ... }
->  $a,$b  { ... }


Details about the syntax and use of signatures can be found in the documentation on the Signature class.

Automatic signatures

If no signature is provided but either of the two automatic variables @_ or %_ are used in the function body, a signature with *@_ or *%_ will be generated. Both automatic variables can be used at the same time.

sub s { say @_, %_ };
say &s.signature # OUTPUT: «(*@_, *%_)␤»

Arguments

Arguments are supplied as a comma separated list. To disambiguate nested calls, use parentheses:

sub f(&c){ c() * 2 }; # call the function reference c with empty parameter list
sub g($p){$p - 2 };
say(g(42), 45);       # pass only 42 to g()

When calling a function, positional arguments should be supplied in the same order as the function's signature. Named arguments may be supplied in any order, but it's considered good form to place named arguments after positional arguments. Inside the argument list of a function call, some special syntax is supported:

sub f(|c){};
f :named(35);     # A named argument (in "adverb" form)
f named => 35;    # Also a named argument
f :35named;       # A named argument using abbreviated adverb form
f 'named' => 35;  # Not a named argument, a Pair in a positional argument
my \c = <a b c>.Capture;
f |c;             # Merge the contents of Capture $c as if they were supplied Arguments passed to a function are conceptually first collected in a Capture container. Details about the syntax and use of these containers can be found in the documentation on the Capture class. When using named arguments, note that normal List "pair-chaining" allows one to skip commas between named arguments. sub f(|c){}; f :dest</tmp/foo> :src</tmp/bar> :lines(512); f :32x :50y :110z; # This flavor of "adverb" works, too f :a:b:c; # The spaces are also optional. Return values Any Block or Routine will provide the value of its last expression as a return value to the caller. If either return or return-rw is called, then its parameter, if any, will become the return value. The default return value is Nil. sub a { 42 }; sub b { say a }; sub c { }; b; # OUTPUT: «42␤» say c; # OUTPUT: «Nil␤» Multiple return values are returned as a list or by creating a Capture. Destructuring can be used to untangle multiple return values. sub a { 42, 'answer' }; put a.perl; # OUTPUT: «(42, "answer")␤» my ($n, $s) = a; put [$s, $n]; # OUTPUT: «answer 42␤» sub b { <a b c>.Capture }; put b.perl; # OUTPUT: «\("a", "b", "c")␤» Return type constraints Perl 6 has many ways to specify a function's return type: sub foo(--> Int) {}; say &foo.returns; # OUTPUT: «(Int)␤»  sub foo() returns Int {}; say &foo.returns; # OUTPUT: «(Int)␤»  sub foo() of Int {}; say &foo.returns; # OUTPUT: «(Int)␤»  my Int sub foo() {}; say &foo.returns; # OUTPUT: «(Int)␤»  Attempting to return values of another type will cause a compilation error. sub foo() returns Int { "a"; }; foo; # Type check fails  returns and of are equivalent, and both take only a Type since they are declaring a trait of the Callable. The last declaration is, in fact, a type declaration, which obviously can take only a type. -->, however, can take either undefined or definite values. Note that Nil and Failure are exempt from return type constraints and can be returned from any routine, regardless of its constraint: sub foo() returns Int { fail }; foo; # Failure returned sub bar() returns Int { return }; bar; # Nil returned  Multi-dispatch Perl 6 allows for writing several routines with the same name but different signatures. When the routine is called by name, the runtime environment determines the proper candidate and invokes it. Each candidate is declared with the multi keyword. Dispatch happens depending on the number (arity), type and name of arguments. Consider the following example: # version 1 multi happy-birthday($name ) {
say "Happy Birthday $name !"; } # version 2 multi happy-birthday($name, $age ) { say "Happy {$age}th Birthday $name !"; } # version 3 multi happy-birthday( :$name, :$age, :$title  = 'Mr' ) {
say "Happy {$age}th Birthday$title $name !"; } # calls version 1 (arity) happy-birthday 'Larry'; # OUTPUT: «Happy Birthday Larry !␤» # calls version 2 (arity) happy-birthday 'Luca', 40; # OUTPUT: «Happy 40th Birthday Luca !␤» # calls version 3 # (named arguments win against arity) happy-birthday( age => '50', name => 'John' ); # OUTPUT: «Happy 50th Birthday Mr John !␤» # calls version 2 (arity) happy-birthday( 'Jack', 25 ); # OUTPUT: «Happy 25th Birthday Jack !␤»  The first two versions of the happy-birthday sub differs only in the arity (number of arguments), while the third version uses named arguments and is chosen only when named arguments are used, even if the arity is the same of another multi candidate. When two sub have the same arity, the type of the arguments drive the dispatch; when there are named arguments they drive the dispatch even when their type is the same as another candidate: multi happy-birthday( Str$name, Int $age ) { say "Happy {$age}th Birthday $name !"; } multi happy-birthday( Str$name, Str $title ) { say "Happy Birthday$title $name !"; } multi happy-birthday( Str :$name, Int :$age ) { say "Happy Birthday$name, you turned $age !"; } happy-birthday 'Luca', 40; # OUTPUT: «Happy 40th Birthday Luca !␤» happy-birthday 'Luca', 'Mr'; # OUTPUT: «Happy Birthday Mr Luca !␤» happy-birthday age => 40, name => 'Luca'; # OUTPUT: «Happy Birthday Luca, you turned 40 !␤»  Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence. For more information about type constraints see the documentation for the Signature class. multi as-json(Bool$d) { $d ?? 'true' !! 'false'; } multi as-json(Real$d) { ~$d } multi as-json(@d) { sprintf '[%s]', @d.map(&as-json).join(', ') } say as-json( True ); # OUTPUT: «true␤» say as-json( 10.3 ); # OUTPUT: «10.3␤» say as-json( [ True, 10.3, False, 24 ] ); # OUTPUT: «[true, 10.3, false, 24]␤» multi without any specific routine type always defaults to a sub, but you can use it on methods as well. The candidates are all the multi methods of the object: class Congrats { multi method congratulate($reason, $name) { say "Hooray for your$reason, $name"; } } role BirthdayCongrats { multi method congratulate('birthday',$name) {
say "Happy birthday, $name"; } multi method congratulate('birthday',$name, $age) { say "Happy {$age}th birthday, $name"; } } my$congrats = Congrats.new does BirthdayCongrats;

$congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤»$congrats.congratulate('birthday','Bob');    # OUTPUT: «Happy birthday, Bob␤»

Unlike sub, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected.

Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates.

proto

proto is a way to formally declare commonalities between multi candidates. It acts as a wrapper that can validate but not modify arguments. Consider this basic example:

proto congratulate(Str $reason, Str$name, |) {*}
multi congratulate($reason,$name) {
say "Hooray for your $reason,$name";
}
multi congratulate($reason,$name, Int $rank) { say "Hooray for your$reason, $name -- got rank$rank!";
}

congratulate('being a cool number', 'Fred');     # OK
congratulate('being a cool number', 'Fred', 42); # OK
congratulate('being a cool number', 42);         # Proto match error


The proto insists that all multi congratulate subs conform to the basic signature of two strings, optionally followed by further parameters. The | is an un-named Capture parameter, and allows a multi to take additional arguments. The first two calls succeed, but the third fails (at compile time) because 42 doesn't match Str.

say &congratulate.signature # OUTPUT: «(Str $reason, Str$name, | is raw)␤»


You can give the proto a function body, and place the {*} where you want the dispatch to be done.

# attempts to notify someone -- False if unsuccessful
proto notify(Str $user,Str$msg) {
my \hour = DateTime.now.hour;
if hour > 8 or hour < 22 {
return {*};
} else {
# we can't notify someone when they might be sleeping
return False;
}
}

{*} always dispatches to candidates with the parameters it's called with. Parameter defaults and type coercions will work but are not passed on.

proto mistake-proto(Str() $str, Int$number = 42) {*}
multi mistake-proto($str,$number) { say $str.^name } mistake-proto(7, 42); # OUTPUT: «Int␤» -- not passed on  mistake-proto('test'); # fails -- not passed on  only The only keyword preceding sub or method indicates that it will be the only function with that name that inhabits a given namespace. only sub you () {"Can make all the world seem right"}; This will make other declarations in the same namespace, such as sub you ($can ) { "Make the darkness bright" }

fail with an exception of type X::Redeclaration. only is the default value for all subs; in the case above, not declaring the first subroutine as only will yield exactly the same error; however, nothing prevents future developers from declaring a proto and preceding the names with multi. Using only before a routine is a defensive programming feature that declares the intention of not having routines with the same name declared in the same namespace in the future.

(exit code 1)
===SORRY!=== Error while compiling /tmp/hDM1N2OAOo
Redeclaration of routine 'you' (did you mean to declare a multi-sub?)
at /tmp/hDM1N2OAOo:1
------> ( $can ) { "Make the darkness bright" }⏏<EOL>  Anonymous sub cannot be declared only. only sub {}' will throw an error of type, surprisingly, X::Anon::Multi. Conventions and idioms While the dispatch system described above provides a lot of flexibility, there are some conventions that most internal functions, and those in many modules, will follow. Slurpy conventions Perhaps the most important one of these conventions is the way slurpy list arguments are handled. Most of the time, functions will not automatically flatten slurpy lists. The rare exceptions are those functions that don't have a reasonable behavior on lists of lists (e.g., chrs) or where there is a conflict with an established idiom (e.g., pop being the inverse of push). If you wish to match this look and feel, any Iterable argument must be broken out element-by-element using a **@ slurpy, with two nuances: • Lists created with a , at the top level only count as one Iterable. This can be achieved by using a slurpy with a + or +@ instead of **: sub grab(+@a) { "grab$_".say for @a }

which is shorthand for something very close to:

multi sub grab(**@a) { "grab $_".say for @a } multi sub grab(\a) { a ~~ Iterable and a.VAR !~~ Scalar ?? nextwith(|a) !! nextwith(a,) } This results in the following behavior, which is known as the "single argument rule" and is important to understand when invoking slurpy functions: grab(1, 2); # OUTPUT: «grab 1␤grab 2␤» grab((1, 2)); # OUTPUT: «grab 1␤grab 2␤» grab($(1, 2));   # OUTPUT: «grab 1 2␤»
grab((1, 2), 3); # OUTPUT: «grab 1 2␤grab 3␤»


This also makes user-requested flattening feel consistent whether there is one sublist, or many:

grab(flat (1, 2), (3, 4));   # OUTPUT: «grab 1␤grab 2␤grab 3␤grab 4␤»
grab(flat $(1, 2),$(3, 4)); # OUTPUT: «grab 1 2␤grab 3 4␤»
grab(flat (1, 2));           # OUTPUT: «grab 1␤grab 2␤»
grab(flat $(1, 2)); # OUTPUT: «grab 1␤grab 2␤»  It's worth noting that mixing binding and sigilless variables in these cases requires a bit of finesse, because there is no Scalar intermediary used during binding. my$a = (1, 2);  # Normal assignment, equivalent to $(1, 2) grab($a);        # OUTPUT: «grab 1 2␤»
my $b := (1, 2); # Binding,$b links directly to a bare (1, 2)
grab($b); # OUTPUT: «grab 1␤grab 2␤» my \c = (1, 2); # Sigilless variables always bind, even with '=' grab(c); # OUTPUT: «grab 1␤grab 2␤»  Functions are first-class objects Functions and other code objects can be passed around as values, just like any other object. There are several ways to get hold of a code object. You can assign it to a variable at the point of declaration: my$square = sub (Numeric $x) {$x * $x } # and then use it: say$square(6);    # OUTPUT: «36␤»

Or you can reference an existing named function by using the &-sigil in front of it.

sub square($x) {$x * $x }; # get hold of a reference to the function: my$func = &square

This is very useful for higher order functions, that is, functions that take other functions as input. A simple one is map, which applies a function to each input element:

sub square($x) {$x * $x }; my @squared = map &square, 1..5; say join ', ', @squared; # OUTPUT: «1, 4, 9, 16, 25␤» Infix form To call a subroutine with 2 arguments like an infix operator, use a subroutine reference surrounded by [ and ]. sub plus {$^a + $^b }; say 21 [&plus] 21; # OUTPUT: «42␤» Closures All code objects in Perl 6 are closures, which means they can reference lexical variables from an outer scope. sub generate-sub($x) {
my $y = 2 *$x;
return sub { say $y }; # ^^^^^^^^^^^^^^ inner sub, uses$y
}
my $generated = generate-sub(21);$generated(); # OUTPUT: «42␤»

Here, $y is a lexical variable inside generate-sub, and the inner subroutine that is returned uses it. By the time that inner sub is called, generate-sub has already exited. Yet the inner sub can still use$y, because it closed over the variable.

Another closure example is the use of map to multiply a list of numbers:

my $multiply-by = 5; say join ', ', map {$_ * $multiply-by }, 1..5; # OUTPUT: «5, 10, 15, 20, 25␤» Here, the block passed to map references the variable$multiply-by from the outer scope, making the block a closure.

Languages without closures cannot easily provide higher-order functions that are as easy to use and powerful as map.

Routines

Routines are code objects that conform to type Routine, most notably Sub, Method, Regex and Submethod.

They carry extra functionality in addition to what a Block supplies: they can come as multis, you can wrap them, and exit early with return:

my $keywords = set <if for unless while>; sub has-keyword(*@words) { for @words ->$word {
return True if $word (elem)$keywords;
}
False;
}

say has-keyword 'not', 'one', 'here';       # OUTPUT: «False␤»
say has-keyword 'but', 'here', 'for';       # OUTPUT: «True␤»

Here, return doesn't just leave the block inside which it was called, but the whole routine. In general, blocks are transparent to return, they attach to the outermost routine.

Routines can be inlined and as such provide an obstacle for wrapping. Use the pragma use soft; to prevent inlining to allow wrapping at runtime.

sub testee(Int $i, Str$s){
rand.Rat * $i ~$s;
}

sub wrap-to-debug(&c){
say "wrapping {&c.name} with arguments {&c.signature.perl}";
&c.wrap: sub (|args){
note "calling {&c.name} with {args.gist}";
my \ret-val := callwith(|args);
note "returned from {&c.name} with return value {ret-val.perl}";
ret-val
}
}

my $testee-handler = wrap-to-debug(&testee); # OUTPUT: «wrapping testee with arguments :(Int$i, Str $s)» say testee(10, "ten"); # OUTPUT: «calling testee with \(10, "ten")␤returned from testee with return value "6.151190ten"␤6.151190ten» &testee.unwrap($testee-handler);
say testee(10, "ten");
# OUTPUT: «6.151190ten␤»
Important ones: candidates, wrap, unwrap, assuming, arity, count

Defining operators

Operators are just subroutines with funny names. The funny names are composed of the category name (infix, prefix, postfix, circumfix, postcircumfix), followed by a colon, and a list of the operator name or names (two components in the case of circumfix and postcircumfix).

This works both for adding multi candidates to existing operators and for defining new ones. In the latter case, the definition of the new subroutine automatically installs the new operator into the grammar, but only in the current lexical scope. Importing an operator via use or import also makes it available.

# adding a multi candidate to an existing operator:
multi infix:<+>(Int $x, "same") { 2 *$x };
say 21 + "same";            # OUTPUT: «42␤»

# defining a new operator
sub postfix:<!>(Int $x where {$x >= 0 }) { [*] 1..$x }; say 6!; # OUTPUT: «720␤»  The operator declaration becomes available as soon as possible, so you can recurse into a just-defined operator: sub postfix:<!>(Int$x where { $x >= 0 }) {$x == 0 ?? 1 !! $x * ($x - 1)!
}
say 6!;                     # OUTPUT: «720␤»


Circumfix and postcircumfix operators are made of two delimiters, one opening and one closing.

sub circumfix:<START END>(*@elems) {
"start", @elems, "end"
}

say START 'a', 'b', 'c' END;        # OUTPUT: «(start [a b c] end)␤»


Postcircumfixes also receive the term after which they are parsed as an argument:

sub postcircumfix:<!! !!>($left,$inside) {
"$left -> ($inside )"
}
say 42!! 1 !!;      # OUTPUT: «42 -> ( 1 )␤»


Blocks can be assigned directly to operator names. Use a variable declarator and prefix the operator name with a &-sigil.

my &infix:<ieq> = -> |l { [eq] l>>.fc };
say "abc" ieq "Abc";
# OUTPUT: «True␤»

Precedence

Operator precedence in Perl 6 is specified relatively to existing operators. The traits is tighter, is equiv and is looser can be provided with an operator to indicate how the precedence of the new operators is related to other, existing ones. More than one trait can be applied.

For example, infix:<*> has a tighter precedence than infix:<+>, and squeezing one in between works like this:

sub infix:<!!>($a,$b) is tighter(&infix:<+>) {
2 * ($a +$b)
}

say 1 + 2 * 3 !! 4;     # OUTPUT: «21␤»


Here, the 1 + 2 * 3 !! 4 is parsed as 1 + ((2 * 3) !! 4), because the precedence of the new !! operator is between that of + and *.

The same effect could have been achieved with:

sub infix:<!!>($a,$b) is looser(&infix:<*>) { ... }

To put a new operator on the same precedence level as an existing operator, use is equiv(&other-operator) instead.

Associativity

When the same operator appears several times in a row, there are multiple possible interpretations. For example:

1 + 2 + 3

could be parsed as

(1 + 2) + 3         # left associative

or as

1 + (2 + 3)         # right associative

For addition of real numbers, the distinction is somewhat moot, because + is mathematically associative.

But for other operators it matters a great deal. For example, for the exponentiation/power operator, infix:<**> :

say 2 ** (2 ** 3);      # OUTPUT: «256␤»
say (2 ** 2) ** 3;      # OUTPUT: «64␤»

Perl 6 has the following possible associativity configurations:

A Assoc Meaning of $a !$b ! $c L left ($a ! $b) !$c
R right $a ! ($b ! $c) N non ILLEGAL C chain ($a ! $b) and ($b ! $c) X list infix:<!>($a; $b;$c)

You can specify the associativity of an operator with the is assoc trait, where left is the default associativity.

sub infix:<§>(*@a) is assoc<list> {
'(' ~ @a.join('|') ~ ')';
}

say 1 § 2 § 3;      # OUTPUT: «(1|2|3)␤»


Traits

Traits are subroutines that run at compile time and modify the behavior of a type, variable, routine, attribute, or other language object.

Examples of traits are:

class ChildClass is ParentClass { ... }
#                ^^ trait, with argument ParentClass
has $.attrib is rw; # ^^^^^ trait with name 'rw' class SomeClass does AnotherRole { ... } # ^^^^ trait has$!another-attribute handles <close>;
#                       ^^^^^^^ trait


... and also is tighter, is looser, is equiv and is assoc from the previous section.

Traits are subs declared in the form trait_mod<VERB> , where VERB stands for the name like is, does or handles. It receives the modified thing as argument, and the name as a named argument. See Sub for details.

multi sub trait_mod:<is>(Routine $r, :$doubles!) {
$r.wrap({ 2 * callsame; }); } sub square($x) is doubles {
$x *$x;
}

say square 3;       # OUTPUT: «18␤»


See type Routine for the documentation of built-in routine traits.

Re-dispatching

There are cases in which a routine might want to call the next method from a chain. This chain could be a list of parent classes in a class hierarchy, or it could be less specific multi candidates from a multi dispatch, or it could be the inner routine from a wrap.

Fortunately, we have a series of re-dispatching tools that help us to make it easy.

sub callsame

callsame calls the next matching candidate with the same arguments that were used for the current candidate and returns that candidate's return value.

proto a(|) {*}

multi a(Any $x) { say "Any$x";
return 5;
}

multi a(Int $x) { say "Int$x";
my $res = callsame; say "Back in Int with$res";
}

a 1;        # OUTPUT: «Int 1␤Any 1␤Back in Int with 5␤»


sub callwith

callwith calls the next candidate matching the original signature, that is, the next function that could possibly be used with the arguments provided by users and returns that candidate's return value.

proto a(|) {*}

multi a(Any $x) { say "Any$x";
return 5;
}
multi a(Int $x) { say "Int$x";
my $res = callwith($x + 1);
say "Back in Int with \$res";
}

a 1;        # OUTPUT: «Int 1␤Any 2␤Back in Int with 5␤»


Here, a 1 calls the most specific Int c