Untitled

Welcome to the official documentation of the Perl 6 programming language! Besides online browsing and searching, you can also 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 documentation, including tutorials, HowTos and FAQs (Frequently Asked Questions).

You may also be interested in the Perl 6 design documents, which are in some places more complete than this documentation, but targeted toward compiler writers rather than users of the language. Documentation for the different but related Perl 5 language can be found on the Perl 5 documentation website.

# 1 5to6-nutshell

Perl 5 to Perl 6, in a nutshell: How do I do what I used to do?

This page attempts to index 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 won't be).

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.

# 1.1 CPAN

See https://modules.perl6.org/ .

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.

There are multiple projects aiming to make it possible to use Perl 5 modules directly from Perl 6 code:

v5 A slang that lets Rakudo itself parse blocks of Perl 5 code, and compile them to the same bytecode that it compiles Perl 6 code to.

Inline::Perl5 Uses an embedded instance of the perl interpreter to run Perl 5 code called from your Perl 6 script.

Of these, Inline::Perl5 is currently the furthest along and the most promising.

# 1.2 Syntax

## 1.2.1 -> 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.

## 1.2.2 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]&lt;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

- 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 &lt; 0) { ... }          # Perl 5, dies in Perl 6
      if ($a &lt; 0) { ... }         # Perl 6
      if $a &lt; 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

- No space allowed around the method call operator.

      $customer -> name; # Perl 5
      $customer.name;    # Perl 6

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

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

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

    # 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");

See also S03#Minimal whitespace DWIMmery and S04#Statement parsing in the Perl 6 design docs.

## 1.2.3 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.

(See also #Dereferencing).

### 1.2.3.1 $ Scalar

The $ sigil is now always used with "scalar" variables (e.g. $name), and no longer for array indexing and Hash indexing. That is, you can still use $x[1] and $x{"foo"}, but it will act on $x, with no effect on a similarly named @x or %x. Those would now be accessed with @x[1] and %x{"foo"}.

### 1.2.3.2 @ 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.

### 1.2.3.3 % 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.

### 1.2.3.4 & 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 = \&amp;foo; # Perl 5
    my $sub = &amp;foo;  # Perl 6

    callback => sub { say @_ }  # Perl 5 - can't pass built-in sub directly
    callback => &amp;say            # Perl 6 - &amp; 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;
      &amp;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

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

      # TODO: Suggest .callsame once it has been implemented in Rakudo.

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

      # TODO: Suggest .nextsame and .nextwith once they've been implemented in Rakudo.

### 1.2.3.5 * 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, file handles, 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(&lt;H>), scalar(&lt;H>);
    }
    open FILE, '&lt;', $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
    sub read_2 {
        my ($fh) = @_;
        return scalar(&lt;$fh>), scalar(&lt;$fh>);
    }
    open my $in_file, '&lt;', $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;
    my ($line1, $line2) = read-n($in-file, 2);

## 1.2.4 [] Array indexing/slicing

Index and slice operations on arrays no longer inflect the variable's sigil, and adverbs can be used to control the type of slice:

- Indexing

      say $months[2]; # Perl 5
      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.

## 1.2.5 {} 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&lt;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&lt;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&lt;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.

## 1.2.6 Reference creation

TODO: Rewrite this section to make it clear that the "referencing/ dereferencing" metaphor does not map cleanly to the actual Perl 6 container system, and focus more on how one would translate or replace actual code that uses references in Perl 5.

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.

In Perl 6, anonymous arrays and hashes and subs still return their reference during creation. References to named subs are generated by preceding the sub name with a & sigil. References to existing named variables are generated by item context.

    my $aref = [ 1, 2, 9 ];          # Both Perl 5&amp;6
    my $href = { A => 98, Q => 99 }; # Both Perl 5&amp;6 [*See Note*]

    my $aref =     \@aaa  ; # Perl 5
    my $aref = item(@aaa) ; # Perl 6

    my $href =     \%hhh  ; # Perl 5
    my $href = item(%hhh) ; # Perl 6

    my $sref =     \&amp;foo  ; # Perl 5
    my $sref =      &amp;foo  ; # Perl 6

NOTE: If one or more values reference the topic variable, $_, the right-hand side of the assignment will be interpreted as a Block, not a Hash:

    my @people = [
        { id => "1A", firstName => "Andy", lastName => "Adams" },
        { id => "2B", firstName => "Beth", lastName => "Burke" },
        # ...
    ];

    sub lookup-user (Hash $h) { #`(Do something...) $h }

    my @names = map {
        my $query = { name => "$_&lt;firstName> $_&lt;lastName>" };
        say $query.WHAT;       # Block
        say $query&lt;name>;      # ERROR: Type Block does not support associative indexing

        lookup-user($query);   # Type check failed in binding $h; expected Hash but got Block
    }, @people;

Instead, you should either:

- 1) use the %() hash constructor:

      my $query = %( name => "$_&lt;firstName> $_&lt;lastName>" );

- 2) assign to a Hash type (%) directly:

      my %query = name => "$_&lt;firstName> $_&lt;lastName>";   # No braces required

- or 3) simply avoid the issue altogether by explicitly providing a name for the topic variable:

      my @names = @people.map: -> $person {
          lookup-user( %( name => "$person&lt;firstName> $person&lt;lastName>" ) );
      };

See Hash assignment for more details.

## 1.2.7 Dereferencing

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, the curly braces are changed to parentheses.

    # Perl 5
        say      ${$scalar_ref};
        say      @{$arrayref  };
        say keys %{$hashref   };
        say      &amp;{$subref    };

    # Perl 6
        say      $($scalar_ref);
        say      @($arrayref  );
        say keys %($hashref   );
        say      &amp;($subref    );

Note that in both Perl 5 and Perl 6, the surrounding curly braces or parens can often be omitted, though the omission can reduce readability.

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, we now use the dot operator . for those tasks.

    # Perl 5
        say $arrayref->[7];
        say $hashref->{'fire bad'};
        say $subref->($foo, $bar);

    # Perl 6
        say $arrayref.[7];
        say $hashref.{'fire bad'};
        say $subref.($foo, $bar);

In recent versions of Perl 5 (5.20 and later), a new feature allows the use of the arrow op for dereferencing. See http://search.cpan.org/~shay/perl-5.20.1/pod/perl5200delta.pod#Experimental_Postfix_Dereferencing That new feature corresponds Perl 6 .list and .hash methods:

    # Perl 5.20
        use experimental qw&lt; postderef >;
        my @a = $arrayref->@*;
        my %h = $hashref->%*;
        my @slice = $arrayref->@[3..7];

    # Perl 6
        my @a = $arrayref.list;         # or @($arrayref)
        my %h = $hashref.hash;          # or %($hashref)
        my @slice = $arrayref[3..7];

The "Zen" slice does the same thing:

    # Perl 6
        my @a = $arrayref[];
        my %h = $hashref{};

See S32/Containers

# 1.3 Operators

See S03/Operators for full details on all operators.

Unchanged:

- , List Separator

- + 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

## 1.3.1 <=> 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.

## 1.3.2 ~~ Smart-match operator

While the operator has not changed, the rules for what exactly is matched depends on the types of both arguments, and those rules are far from identical in Perl 5 and Perl 6. See S03/Smart matching

## 1.3.3 & | ^ String Bitwise ops

## 1.3.4 & | ^ Numeric Bitwise ops

## 1.3.5 & | ^ 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)
    +&amp;  +|  +^  And Or Xor: Numeric
    ~&amp;  ~|  ~^  And Or Xor: String
    ?&amp;  ?|  ?^  And Or Xor: Boolean

    # Prefix ops (one argument, after the op)
    +^  Not: Numeric
    ~^  Not: String
    ?^  Not: Boolean (same as the ! op)

## 1.3.6 << >> Numeric shift left|right ops

Replaced by +< and +> .

    say 42 &lt;&lt; 3; # Perl 5
    say 42 +&lt; 3; # Perl 6

## 1.3.7 => 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.

    # 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 Pair,
    # 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

## 1.3.8 ? : Ternary operator

Now spelled with two question marks instead of one question mark, and two exclamation points instead of one colon.

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

## 1.3.9 . (Dot op) 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

## 1.3.10 x List Repeat op or String Repeat op

In Perl 5, x was the Repetition operator.

In scalar context, x would repeat a string. In Perl 6, x repeats strings in any context.

In list context, x would repeat a list—but only if the left argument is parenthesized! In Perl 6, the new xx op repeats lists 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;            # Parens no longer needed
        @ones = 5 xx @ones;         # Parens no longer needed

## 1.3.11 .. ... 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. Range has many new wrinkles in Perl 6, but 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.

## 1.3.12 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"

# 1.4 Compound Statements

## 1.4.1 Conditionals

### 1.4.1.1 if elsif else unless

Mostly unchanged; parens 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.

### 1.4.1.2 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 {
        when "a match" {
            do-something();
        }
        when "another match" {
            do-something-else();
        }
        default {
            do-default-thing();
        }
    }

This is simple in the sense that a scalar value is matched in the when statements. More generally, the matches are actually smart-matches on the input value such that lookups using more complex entities such as regexps can be used instead of scalar values.

See also the warnings on the smart-match op above.

## 1.4.2 Loops

### 1.4.2.1 while until

Mostly unchanged; parens 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 (&lt;IN_FH>)  { } # Perl 5
    for $IN_FH.lines { } # Perl 6

### 1.4.2.2 do while/until

    do {
        ...
    } while $x &lt; 10;

    do {
        ...
    } until $x >= 10;

The construct is still present, but do was renamed to repeat, to better represent what the construct does:

    repeat {
        ...
    } while $x &lt; 10;

    repeat {
        ...
    } until $x >= 10;

### 1.4.2.3 for foreach

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 semi-colons within the parens to determine which type of loop to parse.

The C-style three-factor form now uses the loop keyword, and is otherwise unchanged. The parens *are* still required.

    for  ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 5
    loop ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 6

The loop-iterator form of for or foreach is named for in Perl 6. foreach is no longer a keyword. Parens are optional.

The iteration variable, if any, has been moved from before the list, to after the list and an added arrow operator.

The iteration variable is now always lexical; my is neither needed nor allowed.

In Perl 5, the iteration variable is a read-write alias to the current list element.

In Perl 6, that alias is read-only (for safety), unless you change -> to <->. When translating, 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 &lt;-> $car   {...} # Perl 6; read-write

If the default topic $_ is being used, but needs to be read-write, then just use <-> and explicitly specify $_.

    for (@cars)      {...} # Perl 5; default topic
    for @cars        {...} # Perl 6; $_ is read-only
    for @cars &lt;-> $_ {...} # Perl 6; $_ is read-write

#### 1.4.2.3.1 each

Here is the equivalent to Perl 5’s while…each(%hash) or while…each(@array) (= iterating over both the keys or 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

## 1.4.3 Flow Control statements

Unchanged:

- next

- last

- redo

### 1.4.3.1 continue

There is no longer a continue block. Instead, use a NEXT block 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 ~= ':'
            }
        }

# 1.5 Functions

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

## 1.5.1 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

## 1.5.2 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

## 1.5.3 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

# 1.6 Regular Expressions ( Regex / Regexp )

## 1.6.1 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. See S05/Substitution.

## 1.6.2 Captures start with 0, not 1

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

## 1.6.3 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

## 1.6.4 Add :P5 or :Perl5 adverb

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/  &lt;[aeiou]> / ; # Perl 6, native new syntax

## 1.6.5 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 look-around 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>

(Unrelated to <> syntax, the "lookaround" /foo\Kbar/ becomes /foo <( bar )> /

- (?(?{condition))yes-pattern|no-pattern) becomes [ <?{condition}> yes-pattern | no-pattern ]

## 1.6.6 Longest token matching (LTM) displaces alternation

In Perl 6 regexen, | 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 ||.

TODO more rules. Use translate_regex.pl from Blue Tiger in the meantime.

# 1.7 Pragmas

### 1.7.6.1 strict

Strict mode is now on by default.

### 1.7.6.2 warnings

Warnings are now on by default.

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

### 1.7.6.3 autodie

The functions which were altered by autodie to throw exceptions on error, now throw exceptions by default unless you test the return value explicitly.

    # Perl 5
    open my $i_fh, '&lt;', $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; # Throws exception on error
    my $o_fh = open $output_path, :w; # Throws exception on error

### 1.7.6.4 base

### 1.7.6.5 parent

Both use base and use parent have been replaced in Perl 6 by the is keyword, in the class declaration.

    # Perl 5
    package Cat;
    use base qw(Animal);

    # Perl 6
    class Cat is Animal;

### 1.7.6.6 bigint bignum bigrat

No longer relevant.

Int is now arbitrary precision, as is the numerator of Rat (the denominator is limited to 2**64, after which it will automatically upgrade to Num to preserve performance). If you want a Rat with an arbitrary-precision denominator, FatRat is available.

### 1.7.6.7 constant

In Perl 6, constant is a declarator for variables, just like my, except the variable is permanently locked to the result of its initialization expression (evaluated at compile time).

So, change the => to = , and add a sigil.

    use constant DEBUG => 0; # Perl 5
    constant $DEBUG = 0;     # Perl 6

    use constant pi => 4 * atan2(1, 1); # Perl 5
    # pi, e, i are built-in constants in  Perl 6

### 1.7.6.8 encoding

TODO Allows you to write your script in non-ascii or non-utf8

### 1.7.6.9 integer

Perl pragma to use integer arithmetic instead of floating point

### 1.7.6.10 lib

Manipulate @INC at compile time

### 1.7.6.11 mro

No longer relevant.

In Perl 6, method calls now always use the C3 method resolution order.

### 1.7.6.12 utf8

No longer relevant.

In Perl 6, source code is expected to be in utf8 encoding.

### 1.7.6.13 vars

Discouraged in Perl 5. See http://perldoc.perl.org/vars.html.

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

# 1.8 Command-line flags

See S19/commandline

Unchanged:

-c -e -h -I -n -p -S -T -v -V

### 1.8.6.1 -a

Unchanged in the Spec, but not yet implemented in Rakudo.

For now, change your code to use .split manually.

### 1.8.6.2 -F

Unchanged in the Spec, but not yet implemented in Rakudo.

For now, change your code to use .split manually.

### 1.8.6.3 -l

This is now the default behavior.

### 1.8.6.4 -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.

### 1.8.6.5 -E

Since all features are already enabled, just use lowercase -e .

### 1.8.6.6 -d, -dt, -d:foo, -D, etc.

Replaced with the ++BUG metasyntactic option.

### 1.8.6.7 -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

Taint warnings are not yet specified.

- -P -u -U -W -X

Removed. See S19#Removed Syntactic Features.

- -w

This is now the default behavior.

# 1.9 File-related operations

## 1.9.1 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, "&lt;", "file" or die "$!";
    my @lines = &lt;$fh>;
    close $fh;

In Perl 6, this has been simplified to

    my @lines = "file".IO.lines;

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
    # read the file
    my @lines = "test-file".IO.slurp.split(/\n/);
    say @lines.elems;    #-> 4

## 1.9.2 Trapping 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.

# 1.10 Environment variables

## 1.10.1 Perl module library path

In Perl5 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 Perl5, 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.

# 1.11 Misc.

## 1.11.1 '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;

## 1.11.2 dump

Gone.

The Perl 6 design allows for automatic transparent saving-and-loading of compiled bytecode.

Rakudo supports this only for modules so far.

## 1.11.3 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 (in the current implementation of Rakudo (2015.03)) remove the module Bar statement. (Please note that not having the module statement isn't consistent with Synopsis 11, however it works.)

The module Bar now is merely a file called Bar.pm with the following contents:

    use v6;

    sub EXPORT(*@import-list) {
        my %exportable-subs =
            '&amp;foo' => &amp;foo,
            '&amp;bar' => &amp;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 &lt;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 &lt;foo>;
    foo(1);
    bar(5);       #!> "Undeclared routine: bar used at line 3"

however, this will work

    use Bar &lt;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 &lt;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.

# 1.12 Core modules

### 1.12.3.1 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!"]]

### 1.12.3.2 Getopt::Long

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

    # Perl 5
        use 5.010;
        use Getopt::Long;
        GetOptions(
            'length=i' => \( my $length = 24       ), # numeric
            'file=s'   => \( my $data = 'file.dat' ), # string
            'verbose'  => \( my $verbose           ), # flag
        ) or die;
        say $length;
        say $data;
        say 'Verbosity ', ($verbose ? 'on' : 'off') if defined $verbose;
    perl example.pl
        24
        file.dat
    perl example.pl --file=foo --length=42 --verbose
        42
        foo
        Verbosity on

    perl example.pl --length=abc
        Value "abc" invalid for option length (number expected)
        Died at c.pl line 3.

    # Perl 6
        sub MAIN( Int :$length = 24, :file($data) = 'file.dat', Bool :$verbose ) {
            say $length if $length.defined;
            say $data   if $data.defined;
            say 'Verbosity ', ($verbose ?? 'on' !! 'off');
        }
    perl6 example.p6
        24
        file.dat
        Verbosity off
    perl6 example.p6 --file=foo --length=42 --verbose
        42
        foo
        Verbosity on
    perl6 example.p6 --length=abc
        Usage:
          c.p6 [--length=&lt;Int>] [--file=&lt;Any>] [--verbose]

Note that Perl 6 auto-generates a full usage message on error in command-line parsing.

# 1.13 Automated Translation

A quick way to find the Perl 6 version of a Perl 5 construct, is to run it through an automated translator.

NOTE: None of these translators are yet complete.

## 1.13.1 Blue Tiger

This project is dedicated to automated modernization of Perl code. It does not (yet) have a web front-end, and so must be locally installed to be useful. It also contains a separate program to translate Perl 5 regexes into Perl 6.

https://github.com/Util/Blue_Tiger/

## 1.13.2 Perlito

Online Translator!

This project is a suite of Perl cross-compilers, including Perl 5-to-6 translation. It has a web front-end, and so can be used without installation. It only supports a subset of Perl 5 syntax so far.

http://fglock.github.io/Perlito/perlito/perlito5.html

## 1.13.3 MAD

Larry Wall's own code for translating Perl 5 to Perl 6 has bit-rotted, and is not (currently) viable on recent releases of Perl 5.

MAD (Misc Attribute Definition) is a configuration option when building Perl from a source distribution. The `perl` executable analyses and translates your Perl sourcecode into an op-tree, and then executes the program by walking the op-tree. Normally, most of the details from the analysis are thrown away during this process. When MAD is enabled, the `perl` executable will save those details to an XML file, which can then be read and further processed into Perl 6 code by a MAD parser.

Please consult #perl6 to find out the best release of Perl 5 to use for your MAD science experiments.

## 1.13.4 Perl-ToPerl6

Jeff Goff's Perl::ToPerl6 module for Perl 5 is designed around Perl::Critic's framework. It aims to convert Perl5 to compilable (if not necessarily running) Perl 6 code with the bare minimum of changes. Code transformers are configurable and pluggable, so you can create and contribute your own transformers, and customize existing transformers to your own needs. You can install the latest release from CPAN, or follow the project live on GitHub. An online converter may become available at some point.

# 1.14 Other sources of translation knowledge

- https://perlgeek.de/en/article/5-to-6

- https://github.com/Util/Blue_Tiger/

- https://perl6advent.wordpress.com/2011/12/23/day-23-idiomatic-perl-6/

- http://www.perlfoundation.org/perl6/index.cgi?perl_6_delta_tablet

# 2 5to6-perlfunc

Perl 5 to Perl 6 guide - functions

# 2.1 DESCRIPTION

A (hopefully) comprehensive list of Perl 5 builtin functions with their Perl 6 equivalents with notes on variations between them where necessary.

# 2.2 NOTE

I will not be explaining the functions in detail. This document is an attempt to guide you from the functions in Perl 5's perlfunc document to their equivalents in Perl 6. For full documentation on the Perl 6 functions, please see the Perl 6 documentation.

One general comment: Perl 6 takes its objects a lot more seriously than Perl 5. In Perl 6, everything is an object, although the language is flexible enough to not force you to work in an object oriented manner if you do not wish to do so. What this does mean, however, is that a lot of things that are function calls of the form function(@args) are now also method calls of the form @args.function (In rare cases, there is only a method call). This should be obvious in the following text, but it probably behooves you to get into that frame of mind now.

Also, unless otherwise stated, the use of the term "function" here will mean a function in the style of func(@args), while "method" will refer to a function in the style of @args.func.

# 2.3 Alphabetical Listing of Perl Functions

## 2.3.1 Filetests

- -X FILEHANDLE

- -X EXPR

- -X DIRHANDLE

- -X

Perl 6 gives you a couple of options when it comes to file tests. You can do a smart match (~~) or you can call a method.

In Perl 6, you don't need to actually open a filehandle in the traditional way (although you can) to do a filetest. You can simply append .IO to the filename. For instance, here is how to check if a file is readable using smart match:

    '/path/to/file'.IO ~~ :r

You can, of course, use an already opened filehandle. Here, using the file handle $fh, is an example, using the method syntax for the file test:

    $fh.r

Most of the former filetests have colon equivalents for use with smart match:

    :e Exists
    :d Directory
    :f File
    :l Symbolic link
    :r Readable
    :w Writable
    :x Executable
    :s Size
    :z Zero size

All of these tests can be used as methods (without the colon).

Three tests, however, only have method equivalents:

    $fh.modified; # -M $fh
    $fh.accessed; # -A $fh
    $fh.changed;  # -C $fh

The remaining filetests in Perl 5 do not appear to be implemented in Perl 6.

The documentation for this can be found at File test operators.

There is more information on reading and writing files at io. Also, the section on open() below may be helpful.

## 2.3.2 abs

- abs VALUE

Works as a function (abs($x)), but also as a method. One gotcha, however - method calls bind more tightly than -, so, for example, -15.abs evaluates as -(15.abs) giving you -15. In this example, you would have to do something like (-15).abs.

abs also operates on $_ in the absence of a value, but not as a function, and as a method you need to call it as .abs rather than simply abs.

## 2.3.3 accept

- accept NEWSOCKET,GENERICSOCKET

accept is a method you can call on a server, e. g. $server.accept(). Instead of returning a packed address, it returns a socket, most likely an IO::Socket object of some sort.

## 2.3.4 alarm

- alarm SECONDS

[NEEDS FURTHER RESEARCH] alarm() is no more. It has been suggested that a replacement may be somewhere in the new Concurrency features, such as Promise.in, but some digging may be needed to find a true analog.

## 2.3.5 atan2

- atan2 Y,X

Available as a function as well as being able to be used as a method. For instance, these are equivalent:

    atan2(100);
    100.atan2;

## 2.3.6 bind

- bind SOCKET,NAME

[NEEDS FURTHER RESEARCH] No sign of a socket-related bind() in Perl 6. At a guess, whatever socket binding is needed happens when you create a new socket object.

## 2.3.7 binmode

- binmode FILEHANDLE

Instead of this, you would use :bin as the file mode when opening the socket. E. g. my $fh = open("path/to/file", :bin);

## 2.3.8 bless

- bless REF,CLASSNAME

With the changes in class creation in Perl 6, this may find less use than in Perl 5, and is a method as well as a function. The Perl 6 docs say "Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object." If you're porting a module from Perl 5 to Perl 6, it's quite possible you'll want to use new for creating objects rather than bless, although there may be some situations in which the latter may still be useful.

## 2.3.9 break

- break

Not in Perl 6. For breaking out of given blocks, you should probably take a look at proceed and succeed here.

## 2.3.10 caller

- caller EXPR

[NEEDS FURTHER RESEARCH] What caller does in Perl 5 is taken on by callframe. However, a simple call to callframe will be of little use, as it will return a CallFrame object, rather than any useful information. The filename and line number returned as the second and third values from caller in Perl 5, are in callframe.annotations. You get them by using callframe().annotations.<file line> or, individually, with callframe().annotations.<file> and callframe().annotations.<line> . There does not seem to be a simple way of getting the package name out of callframe however.

## 2.3.11 chdir

- chdir EXPR

Seems to work as it does in Perl 5.

## 2.3.12 chmod

- chmod LIST

Functions as under Perl 5, with the difference that octal numbers are represented differently (0o755 rather than 0755). You may also use it as a method, e. g. $fh.chmod(0o755).

## 2.3.13 chomp

- chomp VARIABLE

The behavior of chomp is different than in Perl 5. It leaves the target unaffected and returns the target with a final logical newline removed. I. e. $x = "howdy\n";$y = chomp($x); results in $x containing "howdy\n" and $y containing "howdy". Also works as a method, i. e. $y = $x.chomp.

## 2.3.14 chop

- chop VARIABLE

As with chomp, in Perl 6, this returns the chopped string, rather than chopping in place. I. e. $x = "howdy";$y = chop($x); results in $x being "howdy" and $y being "howd". Also works as a method: $y = $x.chop

## 2.3.15 chown

- chown LIST

chown is not in Perl 6.

## 2.3.16 chr

- chr NUMBER

Similar to the Perl 5 version, coerces the target to an integer, and uses that as a Unicode code point to return the relevant character. Can be used as a function and a method:

    chr(65); # "A"
    65.chr;  # "A"

## 2.3.17 chroot

- chroot FILENAME

Apparently this is not in Perl 6.

## 2.3.18 close

- close FILEHANDLE

As in Perl 5, closes a filehandle. Returns a boolean value. Both close $fh and $fh.close will work.

## 2.3.19 closedir

- closedir DIRHANDLE

Currently, there is no closedir function. When it is implemented, it may well be a method in the IO::Dir class.

## 2.3.20 connect

- connect SOCKET,NAME

Not clearly documented, but it appears that connect will be a method you would call on some variety of IO::Socket object.

## 2.3.21 continue

- continue BLOCK

- continue

Instead of a continue block, you should use a NEXT block. The closest analog to a bare continue; in Perl 5 appears to be proceed/succeed.

## 2.3.22 cos

- cos EXPR

Works as in Perl 5, but can be also used as a method, i. e. (1/60000).cos.

## 2.3.23 crypt

- crypt PLAINTEXT,SALT

This appears not to have made it into Perl 6.

## 2.3.24 dbm functions

- dbmclose HASH

- dbmopen HASH,DBNAME,MASK

These functions have largely been superseded in Perl 5, and are unlikely to ever turn up in Perl 6 (although any assumptions about the Perl 6 database implementation may be premature).

## 2.3.25 defined

- defined EXPR

Probably does what you expect, but technically it returns False on the type object, and True otherwise. This may make more sense when you realize that $num.perl is the type Any if you haven't assigned anything to it, and the assigned value if you have. Can, of course be used as a method: $num.defined

## 2.3.26 delete

- delete EXPR

Perl 6 replaces this with the new adverb syntax, specifically the :delete adverb. E. g. my $deleted_value = %hash{$key}:delete; and my $deleted_value = @array[$i]:delete;.

## 2.3.27 die

- die LIST

Works similarly to the Perl 5 version, but Perl 6's Exception mechanism may give you more power and flexibility than is available in Perl 5. See exceptions. To omit the stacktrace and location, like Perl 5's die "...\n", use:

    note "...";
    exit 1;

## 2.3.28 do

- do BLOCK

Similar to the Perl 5 version. Note that there must be a space between the do and the block.

- do EXPR

Has been replaced in Perl 6 by EVALFILE.

## 2.3.29 dump

- dump LABEL

According to S29, dump has been... dumped.

## 2.3.30 each

- each HASH

There is no exact equivalent, but you can use %hash.kv which returns a list of keys and values. For example: for %hash.kv -> $k, $v { say "$k: $v" }

Incidentally, what we have there with the -> is called a pointy block and, though there are a number of examples in the documentation, there doesn't seem to be a really clear explanation of how they work. https://design.perl6.org/S04.html#The_for_statement may be of some help here, as well as the design document at https://design.perl6.org/S06.html#%22Pointy_blocks%22. There is also some information at https://en.wikibooks.org/wiki/Perl_6_Programming/Blocks_and_Closures#Pointy_Blocks

## 2.3.31 eof

- eof FILEHANDLE

In Perl 6, this is not usable as a function, but only as a method. I. e. $filehandle.eof. Returns True if at end of file.

## 2.3.32 eval

- eval EXPR

- eval EXPR

Replaced by EVAL. Note that EVAL does not do any exception handling!

## 2.3.33 evalbytes

- evalbytes EXPR

No longer seems to exist.

## 2.3.34 exec

- exec LIST

Nothing in Perl 6 exactly replicates the Perl 5 exec. shell and run are similar to Perl 5's system, but exec's behavior of not returning after executing a system command would have to be emulated by something like shell($command);exit(); or possibly exit shell($command);

## 2.3.35 exists

- exists EXPR

In Perl 6, this is not a function, but an adverb:

    %hash{$key}:exists;
    @array[$i]:exists;

## 2.3.36 exit

- exit EXPR

Appears to do the same thing as in Perl 5.

## 2.3.37 exp

- exp EXPR

Same as in Perl 5, but can also be used as a method: 5.exp;

## 2.3.38 fc

- fc EXPR

Looks like it does the same thing as in Perl 5.

## 2.3.39 fcntl

- fcntl FILEHANDLE,FUNCTION,SCALAR

Appears not to be in Perl 6.

## 2.3.40 __FILE__

- __FILE__

Replaced by $?FILE.

## 2.3.41 fileno

- fileno FILEHANDLE

S32 indicates that this should be available as a method, but appears currently unimplemented.

## 2.3.42 flock

- flock FILEHANDLE,OPERATION

Currently unimplemented.

## 2.3.43 fork

- fork

Not implemented as a built in function, but available through the NativeCall interface. E. g. use NativeCall; sub fork returns int32 is native { * }; say fork;.

## 2.3.44 formats

- format

- formline PICTURE,LIST

Perl 6 does not have built-in formats.

## 2.3.45 getc

- getc FILEHANDLE

Reads a single character from the input stream as in Perl 5. May now also be used as a method: $filehandle.getc

## 2.3.46 getlogin

- getlogin

S29 lists it, but it does not seem to be implemented yet.

## 2.3.47 getpeername

- getpeername SOCKET

S29 lists it, but the implementation does not seem clear or, for that matter, implemented.

## 2.3.48 getpgrp

- getpgrp PID

Does not appear to be implemented.

## 2.3.49 getpriority

- getpriority WHICH,WHO

Does not appear to be implemented.

## 2.3.50 get and set functions

- getpwnam NAME

- getgrnam NAME

- gethostbyname NAME

- getnetbyname NAME

- getprotobyname NAME

- getpwuid UID

- getgrgid GID

- getservbyname NAME,PROTO

- gethostbyaddr ADDR,ADDRTYPE

- getnetbyaddr ADDR,ADDRTYPE

- getprotobynumber NUMBER

- getservbyport PORT,PROTO

- getpwent

- getgrent

- gethostent

- getnetent

- getprotoent

- getservent

- setpwent

- setgrent

- sethostent STAYOPEN

- setnetent STAYOPEN

- setprotoent STAYOPEN

- setservent STAYOPEN

- endpwent

- endgrent

- endhostent

- endnetent

- endprotoent

- endservent

[NEEDS FURTHER RESEARCH] Apparently this range of functions are to be handled by roles like User, Group, etc.

## 2.3.51 getsock*

- getsockname SOCKET

- getsockopt SOCKET,LEVEL,OPTNAME

[NEEDS FURTHER RESEARCH] These are likely implemented by some kind of IO::Socket object, but details are unclear.

## 2.3.52 glob

- glob EXPR

Used in an example in S32, but apparently unimplemented.

## 2.3.53 gmtime

- gmtime EXPR

Like the various parts of localtime, gmtime's functionality appears to in the DateTime object. To get a UTC version of a DateTime object for the current time, for instance, use my $gmtime = DateTime.now.utc.

## 2.3.54 goto

- goto LABEL

- goto EXPR

- goto &NAME

[NEEDS FURTHER RESEARCH] Described in S04, but not yet fully documented.

## 2.3.55 grep

- grep BLOCK LIST

- grep EXPR,LIST

Still in Perl 6, with the caveat that the block form now requires a comma after the block. I.e. @foo = grep { $_ = "bars" }, @baz. Can also be used as a method: @foo = @bar.grep(/^f/)

## 2.3.56 hex

- hex EXPR

Replaced by the adverbial form :16. E. g. :16("aF") returns 175.

Alternately, the same result can be achieved by using the .base method: 0xaF.base(10)

It just so happens that .Str defaults to base 10, so if you just say 0xaF, that will also print 175, but that may not be immediately obvious, so may not be the best way to go for this.

## 2.3.57 import

- import LIST

Was never a builtin function in Perl 5 in the first place. In Perl 6, typically, one declares functions as exportable or not, and all the exportable ones are exported. Nevertheless, selective importing is possible, but beyond the scope of this document. For details, see this section.

## 2.3.58 index

- index STR,SUBSTR,POSITION

Works as in Perl 5. Can also now be used as a method: "howdy!".index("how"); # 0

## 2.3.59 int

- int EXPR

There is a truncate function in Perl 6 (also usable as a method) that does what Perl 5's int does. You may want to use that as a direct translation of Perl 5 code, but in Perl 6, you can just as easily call the .Int method on the number. 3.9.Int; # 3 and 3.9.truncate are equivalent.

## 2.3.60 ioctl

- ioctl FILEHANDLE,FUNCTION,SCALAR

Currently unimplemented in Perl 6.

## 2.3.61 join

- join EXPR,LIST

Works as in Perl 5, and also works as a method: @x.join(",")

## 2.3.62 keys

- keys HASH

Works as in Perl 5, and can also be used as a method: %hash.keys

## 2.3.63 kill

- kill SIGNAL, LIST

- kill SIGNAL

Now part of the Proc::Async class, but looks to work as in Perl 5.

## 2.3.64 last

- last LABEL

- last EXPR

- last

Same as in Perl 5.

## 2.3.65 lc

- lc EXPR

Works as in Perl 5, and also as a method: "UGH".lc

## 2.3.66 lcfirst

- lcfirst EXPR

Does not exist in Perl 6.

## 2.3.67 length

- length EXPR

Replaced by chars, typically used as a method ($string.chars), but also works as a function.

## 2.3.68 __LINE__

- __LINE__

Replaced by $?LINE.

## 2.3.69 link

- link OLDFILE,NEWFILE

In Perl 6, part of the IO::Path class. The only difference between Perl 5 and Perl 6 is that the argument order has changed. It's now link($original, $linked_file).

## 2.3.70 listen

- listen SOCKET,QUEUESIZE

Not clearly documented, but it appears that listen will be a method you would call on some variety of IO::Socket object.

## 2.3.71 local

- local EXPR

The Perl 6 equivalent is temp.

## 2.3.72 localtime

- localtime EXPR

Most of the functionality of localtime is found in DateTime. The specific parts of localtime can be found as follows:

    my $d = DateTime.now;
     $sec  = $d.second; # Potentially includes fractional seconds
     $min  = $d.minute;
     $hour = $d.hour;
     $mday = $d.day-of-month; # or $d.day; 1..31
     $mon  = $d.month; # 1..12
     $year = $d.year;
     $wday = $d.day-of-week; # 1 => Monday, 2 => Tuesday, etc.
     $yday = $d.day-of-year; # 1..366

Please note that ranges are not 0-based in Perl 6, as shown in the comments in the example.

There does not currently appear to be a way to get Perl 5's $isdst. Also, the result of scalar(localtime) that Perl 5 provides is not available. $d.Str will give something along the lines of "2015-06-29T12:49:31-04:00".

## 2.3.73 lock

- lock THING

In Perl 6, a method in the Lock class.

## 2.3.74 log

- log EXPR

Available in Perl 6. Also works as a method. I. e. log(2) is equivalent to 2.log.

## 2.3.75 lstat

- lstat FILEHANDLE

- lstat EXPR

- lstat DIRHANDLE

- lstat

Likely implemented somewhere in one of the IO classes in Perl 6, but it is not clear where at this time.

## 2.3.76 m//

- m//

Regular expression syntax is somewhat different in Perl 6, but the match operator still exists. If you're trying to rewrite some Perl 5 code, the most important difference is that =~ is replaced by the smart match operator, ~~. Similarly, !~ is replaced by !~~. Options for regex operators are adverbs and are complicated. For details, see Adverbs

## 2.3.77 map

- map BLOCK LIST

- map EXPR,LIST

As a function, the only difference between Perl 5 and Perl 6 is that, if you're using a block, the block must be followed by a comma. Can also be used as a method: @new = @old.map: { $_ * 2 }

## 2.3.78 mkdir

- mkdir FILENAME,MASK

- mkdir FILENAME

Works as in Perl 5.

- mkdir

The zero argument (implicit $_) version is not permitted in Perl 6.

## 2.3.79 msg*

- msgctl ID,CMD,ARG

- msgget KEY,FLAGS

- msgrcv ID,VAR,SIZE,TYPE,FLAGS

- msgsnd ID,MSG,FLAGS

Not builtins in Perl 6. May appear in an external module at some point. Maybe.

## 2.3.80 my

- my VARLIST

- my TYPE VARLIST

- my VARLIST : ATTRS

- my TYPE VARLIST : ATTRS

Works as in Perl 5.

## 2.3.81 next

- next LABEL

- next EXPR

- next

The same in Perl 6.

## 2.3.82 no

- no MODULE VERSION

- no MODULE LIST

- no MODULE

- no VERSION

In Perl 6, this is usable for pragmas such as strict, but not for modules. It's unclear whether it can be used for versions, but since that's currently something of a moot point, I would guess not.

## 2.3.83 oct

- oct

Replaced by the adverbial form :8. E. g. :8("100") returns 64.

## 2.3.84 open

- open FILEHANDLE,EXPR

- open FILEHANDLE,MODE,EXPR

- open FILEHANDLE,MODE,EXPR,LIST

- open FILEHANDLE,MODE,REFERENCE

- open FILEHANDLE

The most obvious change from Perl 5 is the file mode syntax. To open a file for reading only, you would say open("file", :r). For write- only, read-write, and append, you would use :w, :rw, and :a respectively. There are also options for encoding and how the filehandle deals with newlines. Details here.

## 2.3.85 opendir

- opendir DIRHANDLE,EXPR

Not a builtin function in Perl 6. You would use the IO::Path class:

    my $dir = IO::Path.new("directory");

    my $dir = "directory".IO; # Same, but probably more direct

## 2.3.86 ord

- ord EXPR

Same as in Perl 5. May be used as a method: "howdy!".ord; # 104

## 2.3.87 our

- our VARLIST

- our TYPE VARLIST

- our VARLIST : ATTRS

- our TYPE VARLIST : ATTRS

The same in Perl 6.

## 2.3.88 pack

- pack TEMPLATE,LIST

Available in Perl 6. The template options are currently more restricted than they are in Perl 5. The current documented list can be found at unpack.

## 2.3.89 package

- package NAMESPACE

- package NAMESPACE VERSION

- package NAMESPACE BLOCK

- package NAMESPACE VERSION BLOCK

S10 indicates that package can be used in Perl 6, but only with a block. I. e. package Foo { ... } means that the code within the block would be in package Foo. There is a special case where a declaration of the form package Foo; as the first statement in a file indicates that the rest of the file is Perl 5 code, but the usefulness of this is unclear. In fact, as modules and classes are declared with distinct keywords (such as class), it's unlikely you will use package directly in Perl 6.

## 2.3.90 __PACKAGE__

- __PACKAGE__

Replaced by $?PACKAGE.

## 2.3.91 pipe

- pipe READHANDLE,WRITEHANDLE

Probably replaced by something in the IO::Pipe class, but this is not clearly documented.

## 2.3.92 pop

- pop ARRAY

Works in Perl 6, and can also be used as a method. I. e. my $x = pop @a; and my $x = @a.pop; are equivalent.

## 2.3.93 pos

- pos SCALAR

Not available in Perl 6. The closest equivalent is the :c adverb, which defaults to $/.to if $/ is true, and 0 if it isn't. For information on :c, see Continue.

## 2.3.94 print

- print FILEHANDLE LIST

- print FILEHANDLE

- print LIST

- print

print can be used as a function in Perl 6, defaulting to standard out. To use print as a function with a filehandle instead of standard out, you need to put a colon after the filehandle. I. e. print $fh: "Howdy!". The use of the colon as an "invocant marker" here is discussed at https://design.perl6.org/S03.html#line_4019. Alternately, you can use a method call: $fh.print("howdy!")

## 2.3.95 printf

- printf FILEHANDLE

- printf FORMAT, LIST

- printf

Works in Perl 6. For the formats, see the documentation for sprintf.

## 2.3.96 prototype

- prototype FUNCTION

No available in Perl 6. The closest equivalent seems to be .signature. E. g. say &sprintf.signature results in "(Cool $format, *@args)".

## 2.3.97 push

- push ARRAY,LIST

Works as in Perl 5, as well as being available as a method: @a.push("foo");. Note: the flattening behaviour is different in Perl 6: @b.push: @a will push @a into @b as a single element. See also the append method.

## 2.3.98 quoting

- q/STRING/

- qq/STRING/

- qw/STRING/

- qx/STRING/

These survive the transition to Perl 6. Some notes:

    q/.../ # is still equivalent to using single quotes.
    qq/.../ # is still equivalent to using double quotes.
    qw/.../ # is more commonly rendered as C&lt;&lt; &lt;...> >> in Perl 6.

There are some added quoting constructs and equivalents, as explained at quoting.

- qr/STRING/

Has been replaced by rx/.../.

- quotemeta EXPR

No direct equivalent, i.e. nothing that just returns the string with all the ASCII non-word characters backslashed. In regexes, however, using $foo will treat $foo as a literal string, and using <$foo> will interpret the contents of $foo as regex code. Note that the angle brackets are doing something different here than they do outside a regex. For more information on this, see https://design.perl6.org/S05.html#Extensible_metasyntax_(%3C...%3E)

## 2.3.99 rand

- rand EXPR

rand by itself works as it does in Perl 5, but you can no longer give it an argument. You can, however, use it as a method on a number to get that behavior. I. e. the Perl 5 rand(100) is equivalent to 100.rand in Perl 6. Additionally, you can get a random integer by using something like (^100).pick. For why you are able to do that, see ^ operator and pick.

## 2.3.100 read

- read FILEHANDLE,SCALAR,LENGTH,OFFSET

read is found in IO::Handle and IO::Socket in Perl 6. It reads the specified number of bytes (rather than characters) from the relevant handle or socket. The use of an offset available in Perl 5 is not documented to exist at this time.

## 2.3.101 readdir

- readdir DIRHANDLE

Not a builtin function. To iterate through the contents of a directory, take a look at dir routine.

## 2.3.102 readline

- readline

Not available in Perl 6. You most likely want to use the .lines method in some way. For more detailed information on reading from files, see io.

## 2.3.103 readlink

- readlink EXPR

Appears to be gone from Perl 6.

## 2.3.104 readpipe

- readpipe EXPR

- readpipe

Doesn't appear to be working in Perl 6, but qx// is functional, so it might be lurking around in some class that isn't obvious.

## 2.3.105 recv

- recv SOCKET,SCALAR,LENGTH,FLAGS

Appears to be in IO::Socket. Not extensively documented at this time.

## 2.3.106 redo

- redo LABEL

- redo EXPR

- redo

Unchanged in Perl 6.

## 2.3.107 ref

- ref EXPR

Gone. To quote S29, "If you really want the type name, you can use $var.WHAT.perl. If you really want P5 ref semantics, use Perl5::p5ref." Except that Perl5::p5ref does not seem to currently exist...

## 2.3.108 rename

- rename OLDNAME,NEWNAME

Still available in Perl 6.

## 2.3.109 requires

- require VERSION

Seems that require may work for modules in Perl 6, but unclear if it will work with version numbers.

## 2.3.110 reset

- reset EXPR

Seeing no evidence of this in Perl 6 and, in fact, S29 asks if there was a good use for this. I'm guessing it's probably gone.

## 2.3.111 return

- return EXPR

Appears to be available in Perl 6, although not clearly documented.

## 2.3.112 reverse

- reverse LIST

In Perl 6, this only reverses the elements of a list. reverse(@a) or @a.reverse. To reverse the characters in a string, use the .flip method.

## 2.3.113 rewinddir

- rewinddir DIRHANDLE

[NEEDS FURTHER RESEARCH] There does not appear to be an obvious direct equivalent. It is possible that some incantation in IO::Path may serve, but it's not clear what it would be.

## 2.3.114 rindex

- rindex STR,SUBSTR,POSITION

Works as in Perl 5, and may also be used as a method. E. g. $x = "babaganush";say $x.rindex("a");say $x.rindex("a", 3); # 5, 3

## 2.3.115 rmdir

- rmdir FILENAME

Works in Perl 6 and can also be used as a method. rmdir "Foo"; and "Foo".IO.rmdir; are equivalent.

## 2.3.116 s///

- s///

Regular expression syntax is somewhat different in Perl 6, but the substitution operator exists. If you're trying to rewrite some Perl 5 code, the most important difference is that =~ is replaced by the smart match operator, ~~. Similarly, !~ is !~~. Options for regex operators are adverbs and are complicated. For details, see Adverbs page

## 2.3.117 say

- say FILEHANDLE

- say LIST

- say

say can be used as a function, defaulting to standard out. To use say as a function with a filehandle instead of standard out, you need to put a colon after the filehandle. I. e. say $fh: "Howdy!". The use of the colon as an "invocant marker" here is discussed at https://design.perl6.org/S03.html#line_4019. Alternately, you can use a method call: $fh.say("howdy!")

## 2.3.118 scalar

- scalar EXPR

Gone. Apparently "very" gone.

## 2.3.119 seek

- seek FILEHANDLE,POSITION,WHENCE

Not documented in a any real way yet, but listed under the IO::Handle class.

## 2.3.120 seekdir

- seekdir DIRHANDLE,POS

Not currently documented, but looks to be something that would be implemented in one of the IO classes, likely IO::Path.

## 2.3.121 select

- select FILEHANDLE

"[S]elect as a global concept is dead." When I asked around about select, I was told that $*OUT and such are overridable in dynamic scope, and that IO::Capture::Simple (at https://github.com/sergot/IO-Capture-Simple) may be of use for something you might be doing with the value of select.

## 2.3.122 sem*

- semctl ID,SEMNUM,CMD,ARG

- semget KEY,NSEMS,FLAGS

- semop KEY,OPSTRING

Gone from the core. May turn up in a module somewhere.

## 2.3.123 send

- send SOCKET,MSG,FLAGS,TO

Can be found in the IO::Socket class.

## 2.3.124 setpgrp

- setpgrp PID,PGRP

No longer in core. Will probably wind up in a POSIX module.

## 2.3.125 setpriority

- setpriority WHICH,WHO,PRIORITY

No longer in core. Will probably wind up in a POSIX module.

## 2.3.126 setsockopt

- setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL

Not documented, but probably hiding in an IO class somewhere.

## 2.3.127 shift

- shift ARRAY

- shift EXPR

- shift

Works as a method as well as a function. shift @a and @a.shift are equivalent.

## 2.3.128 shm*

- shmctl ID,CMD,ARG

- shmget KEY,SIZE,FLAGS

- shmread ID,VAR,POS,SIZE

- shmwrite ID,STRING,POS,SIZE

Gone from the core. May turn up in a module somewhere.

## 2.3.129 shutdown

- shutdown SOCKET,HOW

Not documented, but likely moved into IO::Socket.

## 2.3.130 sin

- sin EXPR

Works as a function and also as a method. sin(2) and 2.sin are equivalent.

## 2.3.131 sleep

- sleep EXPR

Still works as in Perl 5. As of this writing, works as a method, but that is deprecated and will be removed soon.

## 2.3.132 sockets

- socket SOCKET,DOMAIN,TYPE,PROTOCOL

- socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL

Not currently documented, but will likely wind up in IO::Socket.

## 2.3.133 sort

- sort SUBNAME LIST

sort exists in Perl 6, but is somewhat different. $a and $b are no longer special (See 5to6-perlvar) and sort routines no longer return positive integers, negative integers, or 0, but rather Order::Increase, Order::Same, or Order::Decrease objects. See sort for details. May also be used as a method I. e. sort(@a) is equivalent to @a.sort.

## 2.3.134 splice

- splice ARRAY,OFFSET,LENGTH

- splice ARRAY,OFFSET

- splice ARRAY

- splice EXPR,OFFSET,LENGTH,LIST

- splice EXPR,OFFSET,LENGTH

- splice EXPR,OFFSET

- splice EXPR

Available in Perl 6. Can also be used as a method. splice(@foo, 2, 3, <M N O P>); is equivalent to @foo.splice(2, 3, <M N O P>); .

## 2.3.135 split

- split /PATTERN/,EXPR,LIMIT

- split /PATTERN/,EXPR

- split /PATTERN/

Works mostly as in Perl 5. There are some exceptions, though. To get the special behavior of using the empty string, you must actually use the empty string - the special case of the empty pattern // being treated as the empty string does not apply. If you use a regex for the split, it will use the regex, while a literal string will be treated literally. If you wish to have the delimiters included in the resulting list, you need to use the named parameter :all, like this: split(';', "a;b;c", :all) # a ; b ; c Empty chunks are not removed from the result list as they are in Perl 5. For that behavior, see comb. Details on split are here. Unsurprisingly, split also now works as a method: "a;b;c".split(';')

- split

The zero argument version must now be called with an explicit empty string, as described above.

## 2.3.136 sprintf

- sprintf FORMAT, LIST

Works as in Perl 5. The formats currently available are:

% | a literal percent sign
c | a character with the given codepoint
s | a string
d | a signed integer, in decimal
u | an unsigned integer, in decimal
o | an unsigned integer, in octal
x | an unsigned integer, in hexadecimal
e | a floating-point number, in scientific notation
f | a floating-point number, in fixed decimal notation
g | a floating-point number, in %e or %f notation
X | like x, but using uppercase letters
E | like e, but using an uppercase "E"
G | like g, but with an uppercase "E" (if applicable)

Compatibility:

i | a synonym for %d
D | a synonym for %ld
U | a synonym for %lu
O | a synonym for %lo
F | a synonym for %f

Perl 5 (non-)compatibility:

n | produces a runtime exception
p | produces a runtime exception

There are modifiers for integers, but they're mainly no-ops, as the semantics aren't settled:

h | interpret integer as native "short" (typically int16)
l | interpret integer as native "long" (typically int32 or int64)
ll | interpret integer as native "long long" (typically int64)
L | interpret integer as native "long long" (typically uint64)
q | interpret integer as native "quads" (typically int64 or larger)

## 2.3.137 sqrt

- sqrt EXPR

Works as a function and a method. sqrt(4) and 4.sqrt are equivalent.

## 2.3.138 srand

- srand EXPR

Available in Perl 6.

## 2.3.139 stat

- stat EXPR

- stat DIRHANDLE

- stat

Likely implemented somewhere in IO, but it is not clear where at this time.

## 2.3.140 state

- state VARLIST

- state TYPE VARLIST

- state VARLIST : ATTRS

- state TYPE VARLIST : ATTRS

Available in Perl 6, see state.

## 2.3.141 study

- study SCALAR

- study

study is no more.

## 2.3.142 sub

- sub NAME BLOCK

- sub NAME(PROTO) BLOCK

- sub NAME : ATTRS BLOCK

- sub NAME(PROTO) : ATTRS BLOCK

Unsurprisingly, we still have subroutines! You can have a signature in your subroutine which allows you to specify arguments. Nevertheless, in the absence of a signature (and only in the absence of a signature), @_ still contains what is passed to the function. So, in theory, you don't need to change that aspect of a function if porting from Perl 5 to Perl 6 (although you should probably consider the option of using a signature). For all the gory details, see functions.

## 2.3.143 __SUB__

- __SUB__

Replaced by &?ROUTINE.

## 2.3.144 substr

- substr EXPR,OFFSET,LENGTH,REPLACEMENT

- substr EXPR,OFFSET,LENGTH

- substr EXPR,OFFSET

Can be used as a function or a method. substr("hola!", 1, 3) and "hola!".substr(1, 3) both return "ola".

## 2.3.145 symlink

- symlink OLDFILE,NEWFILE

Part of IO::Path in Perl 6. The only difference between Perl 5 and Perl 6 is that the argument order has changed. It's now link($original, $linked_file).

## 2.3.146 syscall

- syscall NUMBER, LIST

Not a builtin in Perl 6. Most likely out in a module somewhere, but it's currently unclear where.

## 2.3.147 sys*

- sysopen FILEHANDLE,FILENAME,MODE

- sysopen FILEHANDLE,FILENAME,MODE,PERMS

- sysread FILEHANDLE,SCALAR,LENGTH,OFFSET

- sysread FILEHANDLE,SCALAR,LENGTH

- sysseek FILEHANDLE,POSITION,WHENCE

As with the non-sys versions of these functions, are probably lurking in the IO classes somewhere.

## 2.3.148 system

- system LIST

- system PROGRAM LIST

For this, you probably want (run) or (shell routine).

## 2.3.149 syswrite

- syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET

- syswrite FILEHANDLE,SCALAR,LENGTH

- syswrite FILEHANDLE,SCALAR

As with sysopen and friends, this has moved into the IO classes.

## 2.3.150 tell

- tell FILEHANDLE

In IO::Handle, but not yet documented, beyond a mention.

## 2.3.151 telldir

- telldir DIRHANDLE

Possibly in IO::Path, but not yet documented.

## 2.3.152 tie

- tie VARIABLE,CLASSNAME,LIST

- tied VARIABLE

[NEEDS FURTHER RESEARCH] S29 indicates that variable tying has been replaced by container types. Unfortunately, what this means in practical terms has not been obviously specified.

## 2.3.153 time

- time

"Returns an Int representing the current time." Although how it represents the current time isn't in the documentation currently, it appears to still be seconds since epoch, as in Perl 5.

## 2.3.154 times

- times

Not available in Perl 6.

## 2.3.155 tr///

- tr///

Works similarly to how it does in Perl 5. The one caveat is that ranges are specified differently. Instead of using a range "a-z", you would use "a..z", i. e. with Perl's range operator. In Perl 6, tr/// has a method version, which is better documented, called .trans. .trans uses a list of pairs, as follows: $x.trans(['a'..'c'] => ['A'..'C'], ['d'..'q'] => ['D'..'Q'], ['r'..'z'] => ['R'..'Z']); A much more extensive description of the uses of .trans can be found at https://design.perl6.org/S05.html#Transliteration. The y/// equivalent has been done away with.

## 2.3.156 truncate

- truncate FILEHANDLE,LENGTH

- truncate EXPR,LENGTH

Most likely somewhere in IO::Handle, but not currently documented.

## 2.3.157 uc

- uc EXPR

Works as a function and a method. uc("ha") and "ha".uc both return "HA".

## 2.3.158 ucfirst

- ucfirst EXPR

- ucfirst

Perl 6 has done away with ucfirst. The title case function tc probably does what you need here. tc function.

## 2.3.159 umask

- umask EXPR

Is an IO method. IO.umask returns the umask.

## 2.3.160 undef

- undef EXPR

There is no undef in Perl 6. You can't undefine a function, and the closest equivalent value is probably Nil, but you'll likely have no use for that. If you were using something like (undef, $file, $line) = caller;, you would just get the filename and line number directly in Perl 6 instead of discarding the first result of caller. caller has been replaced by callframe in Perl 6, so the equivalent statement would be ($file, $line) = callframe.annotations<file line>;

## 2.3.161 unlink

- unlink LIST

Still available. Usable as a method: "filename".IO.unlink

- unlink

The zero argument (implicit $_) version of unlink is not available in Perl 6.

## 2.3.162 unpack

- unpack TEMPLATE,EXPR

- unpack TEMPLATE

Available in Perl 6. The template options are currently more restricted than they are in Perl 5. The current documented list can be found here.

## 2.3.163 unshift

- unshift ARRAY,LIST

- unshift EXPR,LIST

Available in Perl 6. Can be used as a method. unshift(@a, "blah") is equivalent to @a.unshift("blah").

## 2.3.164 untie

- untie VARIABLE

[NEEDS FURTHER RESEARCH] Functions for tying variables seem to be replaced in Perl 6 by container types, as mentioned in S29. This has become no clearer since I wrote the entry for tie, above.

## 2.3.165 use

- use Module VERSION LIST

- use Module VERSION

- use Module LIST

- use Module

- use VERSION

Available in Perl 6, but, oddly, not yet documented. One assumes it works similarly, if not identically, to the way it does in Perl 5

## 2.3.166 utime

- utime LIST

S32 says this is gone, and refers you to Path.times. Unfortunately, there seems to be no sign of Path.times. Perhaps there will be something in IO::Path, but it is not currently evident.

## 2.3.167 values

- values HASH

- values ARRAY

- values EXPR

Available in Perl 6. Can also be used as a method. values %hash is equivalent to %hash.values.

## 2.3.168 vec

- vec EXPR,OFFSET,BITS

S29 says "Should replace vec with declared buffer/array of bit, uint2, uint4, etc." It is unclear, however, that this has actually happened.

## 2.3.169 wait

- wait

[NEEDS FURTHER RESEARCH] Unclear where this has gone. There's a wait method in Supply, and an await method in both Channel and Promise. Which, if any or all, of these is a direct equivalent of Perl 5's wait is unclear.

## 2.3.170 waitpid

- waitpid PID,FLAGS

As with wait, the disposition of this is unclear.

## 2.3.171 wantarray

- wantarray

There is no wantarray in Perl 6, because reasons.

There are very easy ways to cover many of the use cases which wantarray filled.

First, since Perl 6 does not need special reference syntax to contain a List or Array in a Scalar, simply returning a list may be all that is needed:

    sub listofstuff {
        return 1, 2, 3;
    }
    my $a = listofstuff();
    print $a;                      # prints "123"
    print join("&lt;", listofstuff()) # prints "1&lt;2&lt;3"

One of the most common use cases is to provide either an array of lines or elements, or a prettier string than would be produced by simply printing the array. One can mix in a custom .Str method for this purpose:

    sub prettylist(*@origlist) {
        @origlist but role {
            method Str { self.join("&lt;") }
        }
    }
    print prettylist(1, 2, 3);  # prints "1&lt;2&lt;3"
    print join(">", prettylist(3, 2, 1)); # prints "3>2>1"

In the above example, the returned list may be lazy, and the .Str method is not called until stringification happens, so no extra work is done to generate something which is not asked for.

Another use case is to create methods which are mutators when called in void context but produce copies during assignment. It is generally considered better form in Perl 6 not to do so, since users can quite easily turn any copy-producing method into a mutator using the .= operator:

    my $a = "foo\n";
    $a.ords.say; # says "(102 111 111 10)"
    $a .= chomp;
    $a.ords.say; # says "(102 111 111)"

However if you have your heart set on using the same function name for both operations, you can get most of the way there by mixing in a .sink method, which will be called when the result finds itself in void context. There are some caveats however, so again, this is not advised:

    multi sub increment($b is rw) {
        ($b + 1) does role { method sink { $b++ } }
    }
    multi sub increment($b) {
        $b + 1
    }
    my $a = 1;
    increment($a);
    say $a;                 # says "2"
    my $b = increment($a);
    say $a, $b;             # says "2 3"
    # ...users will just have to be aware that they should not accidentally
    # sink a stored value later, though this requires some effort to
    # actually do:
    sub identity($c is rw) { $c };
    $a = 1;
    $b = increment($a);
    identity($b);
    $a.say;                  # says "2"

## 2.3.172 warn

- warn LIST

warn throws an exception. To simply print a message to $*ERR, you would use the note function. For more on exceptions, see Exceptions.

## 2.3.173 write

- write FILEHANDLE

- write EXPR

- write

Formats are gone from Perl 6, so this no longer works.

## 2.3.174 y///

- y///

This synonym for tr/// is gone. For functionality, see the entry for tr///.

# 3 5to6-perlop

Perl 5 to Perl 6 guide - operators

# 3.1 DESCRIPTION

A (hopefully) comprehensive list of Perl 5 operators with their Perl 6 equivalents with notes on variations between them where necessary.

# 3.2 NOTE

I will not be explaining the operators in detail. This document is an attempt to guide you from the operators in Perl 5's perlop document to their equivalents in Perl 6. For full documentation on the Perl 6 equivalents, please see the Perl 6 documentation.

## 3.2.1 Operator Precedence and Associativity

The operator precedence table is somewhat different in Perl 6 than it is in Perl 5, so I will not detail it here. If you need to know the precedence and associativity of a given operator in Perl 6, refer to Operator Precedence.

## 3.2.2 Terms and List Operators

The things listed in Perl 5's perlop document as unary and list operators in this section tend to be things that can also be thought of as functions, such as print and chdir. As such, you can find information about them in 5to6-perlfunc.pod6. Parentheses are still used for grouping.

## 3.2.3 The Arrow Operator

As you typically will not be using references in Perl 6, the arrow is probably less useful as a dereferencing operator. If you do need to dereference something, however, the arrow is the dot. It is also the dot for method calls. So, Perl 5's $arrayref->[7] becomes $arrayref.[7] in Perl 6 and, similarly, $user->name becomes $user.name. The => arrow is used for constructing Pairs, see Pair term documentation.

## 3.2.4 Auto-increment and Auto-decrement

Work as in Perl 5. The one possible caveat is that they function by calling the succ method for ++ and the pred method for --. For builtin numeric types, this is unlikely to do something unusual, but custom types can define their own succ and pred methods, so in those cases, you should probably take note of what ++ and -- will actually do.

## 3.2.5 Exponentiation

Works as you would expect. The caveat in Perl 5's perlop about ** binding more tightly than unary minus (i. e. "-2**4" evaluates as "-(2**4)" rather than "(-2)**4)") seems to hold true for Perl 6.

## 3.2.6 Symbolic Unary Operators

As in Perl 5, unary ! and - do logical arithmetic negation, respectively. ?^ is used for bitwise logical negation, which the documentation indicates is equivalent to !. It may be relevant to note that these coerce their arguments to Bool and Numeric, respectively.

Unary ~ is the string context operator in Perl 6, so use prefix +^ for bitwise integer negation. Assumes two's complement.

+ does have an effect in Perl 6, coercing its argument to to the Numeric type.

Unary <\> is no more. If you really want to take a reference to an existing named variable, you can use item context, like so: $aref = item(@array) You can get a reference to a named subroutine by using the & sigil: <$sref = &foo> Anonymous arrays, hashes, and subs return their references during creation.

## 3.2.7 Binding Operators

=~ and !~ have been replaced by ~~ and !~~, respectively. Those of you who consider smart matching broken in Perl 5 will be happy to hear that it works much better in Perl 6, as the stronger typing means less guesswork.

## 3.2.8 Multiplicative Operators

Binary *, /, and % do multiplication, division, and modulo, respectively, as in Perl 5.

Binary x is slightly different in Perl 6, and has a companion. print '-' x 80; gives you a string of 80 dashes, but for the Perl 5 behavior of @ones = (1) x 80; giving you a list of 80 "1"s, you would use @ones = 1 xx 80;.

## 3.2.9 Additive Operators

Binary + and - do addition and subtraction, respectively, as you would expect..

As . is the method call operator, so binary ~ acts as the concatenation operator in Perl 6.

## 3.2.10 Shift Operators

<< and >> have been replaced by +< and +> .

## 3.2.11 Named Unary Operators

As noted above, you'll find these in 5to6-perlfunc.pod6.

## 3.2.12 Relational Operators

These all work as in Perl 5.

## 3.2.13 Equality Operators

== and != both work as in Perl 5.

<=> and cmp have different behavior in Perl 6. <=> does a numeric comparison, but returns <Order::Less>, <Order::Same>, or <Order::More> instead of Perl 5's -1, 0, or 1. To get the Perl 5 behavior (with the change that it returns the Order objects, rather than integers) of cmp, you would use the leg operator.

cmp does either <=> or leg, depending on the existing type of its arguments.

~~ is the smart match operator as in Perl 5, but it's also just the match operator in Perl 6, as noted above. For how smart matching works in Perl 6, see https://design.perl6.org/S03.html#Smart_matching.

## 3.2.14 Smartmatch Operator

See the entry on ~~ directly above.

## 3.2.15 Bitwise And

Binary & is +& in Perl 6.

## 3.2.16 Bitwise Or and Exclusive Or

Bitwise OR has changed from | in Perl 5 to +| in Perl 6. Similarly, bitwise XOR ^ is +^

## 3.2.17 C-style Logical And

Unchanged.

## 3.2.18 C-style Logical Or

Unchanged.

## 3.2.19 Logical Defined-Or

Remains in Perl 6 as //. Returns the first defined operand, or else the last operand. Also, there is a low precedence version, called orelse.

## 3.2.20 Range Operators

In list context, .. operates as the range operator and should not need to be changed. That said, there are exclusionary range operators that may be useful. These are:

    infix  ..^  Excludes endpoint. C&lt;1..^5; # 1 2 3 4 >
    infix  ^..  Excludes startpoint. C&lt;1^..5; # 2 3 4 5>
    infix  ^..^ Excludes both start- and endpoint. C&lt;1^..^5; # 2 3 4>
    prefix ^    From 0, excludes endpoint. C&lt;^5; # 0 1 2 3 4>

In scalar context, .. and ... work as flip-flop operators in Perl 5, but are little-known, and probably even less used. Those operations have been taken over by ff and fff in Perl 6, but are not clearly documented at this time.

## 3.2.21 Conditional Operator

?: has been replaced by ?? !!. I. e. where you would use $x = $ok ? $y : $z; in Perl 5, you would use $x = $ok ?? $y !! $z; in Perl 6.

## 3.2.22 Assignment Operators

Although not fully documented, S03 indicates that the mathematical and logical assignment operators should work as you would expect. The one noticeable change is that .= calls a mutating method on the object on the left, while ~= is the string concatenation assignment, as you might expect with the changes in . and ~. Also, the bitwise assignment operators are likely not separated into numeric and string versions (&=, etc., vs. &.=, etc.), as that feature is currently experimental in Perl 5 itself - although, again, this is not specifically documented.

## 3.2.23 Comma Operator

The comma operator works mostly as expected, but technically it creates Lists) or separates arguments in function calls. Also, there is a : variant that turns function calls into method calls - see this page.

The => operator works similarly to the Perl 5 "fat comma" behavior in that it allows an unquoted identifier on its left side, but in Perl 6 constructs Pair objects, rather than just functioning as a separator. If you are trying to just literally translate a line of Perl 5 code to Perl 6, it should behave as expected.

## 3.2.24 List Operators (Rightward)

Like the Named Unary Operators, you'll find these discussed in 5to6-perlfunc.pod.

## 3.2.25 Logical Not

The lower precedence version of !. As with !, coerces its argument to Bool.

## 3.2.26 Logical And

Lower precedence version of && as in Perl 5.

## 3.2.27 Logical or and Exclusive Or

or is the low precedence version of ||. The documentation lists an xor, but does not actually document it.

Additionally, there is a low precedence version of //, called orelse.

## 3.2.28 Quote and Quote-like Operators

For all the gory details on quoting constructs, see quoting.

There is a quoting operator that allows absolute literal strings: Q or ｢…｣, although the latter might be difficult to find on your keyboard, depending on your keyboard... Backslash escapes do not apply in Q quoted strings. E. g. Q{This is still a closing curly brace → \} renders "This is still a closing curly brace → \".

q does what you expect, allowing backslash escapes. E. g. q{This is not a closing curly brace → \}, but this is → } returning "This is not a closing curly brace → }, but this is →". As in Perl 5, you can get this behavior with single quotes.

qq allows interpolation of variables. However, by default, only scalar variables are interpolated. To get other variables to interpolate, you need to put square brackets after them. E. g. @a = <1 2 3>;say qq/@a[] example@example.com/; results in "1 2 3 example@example.com". Hashes interpolate in a possibly unexpected manner: %a = 1 => 2, 3 => 4;say "%a[]"; results in a space separating the pairs and tabs separating the key from the value in each pair (apparently). You can also interpolate Perl 6 code in strings using curly braces. For all the details, see Interpolation.

qw works as in Perl 5, and can also be rendered as <...> . E. g. qw/a b c/ is equivalent to <a b c> .

There is also a version of qw that interpolates, which is qqw. So my $a = 42;say qqw/$a b c/; gives you "42 b c".

Shell quoting is available through qx, but you should note that backticks do not do shell quoting as in Perl 5, and Perl variables are not interpolated in qx strings. If you need to interpolate Perl variables in a shell command string, you can use qqx instead.

The qr operator is gone from Perl 6.

tr/// is not well documented, but seems to work similarly to how it does in Perl 5. The one caveat is that ranges are specified differently. Instead of using a range "a-z", you would use "a..z", i. e. with Perl's range operator. tr/// has a method version, which is better documented, called .trans. .trans uses a list of pairs, as follows: $x.trans(['a'..'c'] => ['A'..'C'], ['d'..'q'] => ['D'..'Q'], ['r'..'z'] => ['R'..'Z']); A much more extensive description of the uses of .trans can be found at https://design.perl6.org/S05.html#Transliteration. The y/// equivalent has been done away with.

Heredocs are specified differently in Perl 6. You use :to with your quoting operator, e. g. q:to/END/; would start a heredoc ending with "END". Similarly, you get escaping and interpolation based on your quoting operator, i. e. literals with Q, backslash escapes with q, and interpolation with qq.

## 3.2.29 I/O Operators

The full details on Input/Output in Perl 6 can be found at io.

As <...> is the quote-words construct in Perl 6, <> is not used for reading lines from a file. You can do that by either making an IO object from a file name or using an open filehandle and then, in either case, calling .lines on it. I. e. either my @a = "filename".IO.lines; or my $fh = open "filename", :r;my @a = $fh.lines; (In the latter case, we are using :r to specifically open the file for reading). To do this in an iterative manner, you can use a for loop this way:

    for 'huge-csv'.IO.lines -> $line {
         # Do something with $line
     }

Note the use of -> there. That's part of the Block syntax, and in Perl 6 is needed for if, for, while, etc.

If you want to slurp the entire file into a scalar, you would - surprise! - use the .slurp method. For instance, my $x = "filename".IO.slurp; or my $fh = open "filename", :r;my $x = $fh.slurp;.

As noted in 5to6-perlvar.pod, the ARGV magic input filehandle has been replaced by $*ARGFILES, and the @ARGV array of command line arguments has been replaced by @*ARGS.

## 3.2.30 No-ops

Although it's not specifically documented, 1 while foo(); appears to work in this sense.

## 3.2.31 Bitwise String Operators

Documented individually above, but to summarize...

Bitwise integer negation is prefix +^. Bitwise boolean negation is ?^.

Bitwise and is +&.

Bitwise integer or is +|. Bitwise integer xor is infix +^. Bitwise boolean or is ?|.

Left shift and right shift are +< and +> .

# 4 5to6-perlsyn

Perl 5 to Perl 6 guide - syntax

perlsyn - Perl syntax

# 4.1 DESCRIPTION

A (hopefully) comprehensive description of the differences between Perl 5 and Perl 6 with regards to the syntax elements described in the perlsyn document.

# 4.2 NOTE

I will not be explaining Perl 6 syntax in detail. This document is an attempt to guide you from how things work in Perl 5 to the equivalents in Perl 6. For full documentation on the Perl 6 syntax, please see the Perl 6 documentation.

# 4.3 Free Form

Perl 6 is still largely free form. However, there are a few instances where the presence or lack of whitespace is now significant. For instance, in Perl 5, you can omit a space following a keyword (e. g. while($x < 5) or my($x, $y)). In Perl 6, that space is required, thus while ($x < 5) or my ($x, $y). In Perl 6, however, you can omit the parentheses altogether: while $x < 5 . This holds for if, for, etc.

Oddly, in Perl 5, you can leave spaces between an array or hash and its subscript, and before a postfix operator. So $seen {$_} ++ is valid. No more. That would now have to be %seen{$_}++.

If it makes you feel better, you can use backslashes to "unspace" whitespace, so you can use whitespace where it would otherwise be forbidden.

See Whitespace for details.

## 4.3.1 Declarations

As noted in 5to6-perlfunc.pod, there is no undef in Perl 6. A declared, but uninitialized scalar variable will evaluate to its type. In other words, my $x;say $x; will give you "(Any)". my Int $y;say $y; will give you "(Int)".

## 4.3.2 Comments

# starts a comment that runs to the end of the line as in Perl 5.

Embedded comments start with a hash character and a backtick (#`), followed by an opening bracketing character, and continue to the matching closing bracketing character. Like so:

    if #`( why would I ever write an inline comment here? ) True {
         say "something stupid";
     }

As in Perl 5, you can use pod directives to create multiline comments, with =begin comment before and =end comment after the comment.

## 4.3.3 Truth and Falsehood

The one difference between Perl 5 truth and Perl 6 truth is that, unlike Perl 5, Perl 6 treats the string "0" as true. Numeric 0 is still false, and you can use prefix + to coerce string "0" to numeric to get it to be false. Perl 6, additionally has an actual Boolean type, so, in many cases, True and False may be available to you without having to worry about what values count as true and false.

## 4.3.4 Statement Modifiers

Mostly, statement modifiers still work, with a few exceptions.

First, for loops are exclusively what were known in Perl 5 as foreach loops and for is not used for C-style for loops in Perl 6. To get that behavior, you want loop. loop cannot be used as a statement modifier.

In Perl 6, you cannot use the form do {...} while $x. You will want to replace do in that form with repeat. Similarly for do {...} until $x.

## 4.3.5 Compound Statements

The big change from Perl 5 is that given is not experimental or disabled by default in Perl 6. For the details on given see this page.

## 4.3.6 Loop Control

next, last, and redo have not changed from Perl 5 to Perl 6.

continue, however, does not exist in Perl 6. You would use a NEXT block in 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 ~= ':'
         }
     }

## 4.3.7 For Loops

As noted above, C-style for loops are not called for loops in Perl 6. They are just loop loops. To write an infinite loop, you do not need to use the C idiom of loop (;;) {...}, but may just omit the spec completely: loop {...}

## 4.3.8 Foreach Loops

In Perl 5, for, in addition to being used for C-style for loops, is a synonym for foreach. In Perl 6, for is just used for foreach style loops.

## 4.3.9 Switch Statements

Perl 6 has actual switch statements, provided by given with the individual cases handled by when and default. The basic syntax is:

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

The full details can be found here.

## 4.3.10 Goto

goto probably works similarly in Perl 6 to the way it does in Perl 5. However, as of this writing, it does not seem to be functional. For what is planned for goto, see https://design.perl6.org/S04.html#The_goto_statement.

## 4.3.11 The Ellipsis Statement

... (along with !!! and ???) are used to create stub declarations. This is a bit more complicated than the use of ... in Perl 5, so you'll probably want to look at https://design.perl6.org/S06.html#Stub_declarations for the gory details. That said, there doesn't seem to be an obvious reason why it shouldn't still fulfill the role it did in Perl 5, despite its role being expanded in Perl 6.

## 4.3.12 PODs: Embedded Documentation

Pod has changed between Perl 5 and Perl 6. Probably the biggest difference is that you need to enclose your pod between =begin pod and =end pod directives. There are a few tweaks here and there as well. For instance, as I have discovered while writing these documents, the vertical bar ("|") is significant in X<> codes, and it's not clear how to get a literal "|" into them. Your best bet may be to use the Perl 6 interpreter to check your pod. You can do this by using the --doc switch. E. g. perl6 --doc Whatever.pod. This will output any problems to standard error. (Depending on how/where you've installed perl6, you may need to specify the location of Pod::To::Text.) Details on Perl 6 style pod is at https://design.perl6.org/S26.html.

# 5 5to6-perlvar

Perl 5 to Perl 6 guide - special variables

# 5.1 DESCRIPTION

A (hopefully) comprehensive list of Perl 5 Special Variables with their Perl 6 equivalents with notes on variations between them where necessary.

# 5.2 NOTE

I will not be explaining the full use of the Perl 6 variables. This document is an attempt to guide you from the Special Variables in Perl 5 to their equivalents in Perl 6. For full documentation on the Perl 6 special variables, please see the Perl 6 documentation for those variables.

# 5.3 SPECIAL VARIABLES

## 5.3.1 General Variables

- $ARG

- $_

Thankfully, $_ is the general default variable as in Perl 5. The main difference in Perl 6 seems to be that you can now call methods on it. For instance, Perl 5's say $_ can be rendered in Perl 6 as $_.say. Furthermore, as it is the default variable, you don't even need to use the variable name. The previous example can also be achieved by using .say.

- @ARG

- @_

As Perl 6 now has function signatures, your arguments can go there, rather than depending on @_ for them. In fact, if you use a function signature, use of @_ will spit at you telling it cannot override an existing signature.

If, however, you do not use a function signature, @_ will contain the arguments you pass to the function as it did in Perl 5. Again, as with $_, you can call methods on it. Unlike $_ you cannot assume @_ as the default variable for those methods to operate on. I. e. @_.shift works, .shift does not.

- $LIST_SEPARATOR

- $"

Currently, there is no equivalent of the List Separator variable in Perl 6. Design document S28 says there isn't one, so you probably don't want to hold your breath.

- $PROCESS_ID

- $PID

- $$

$$ is replaced in Perl 6 by $*PID

- $PROGRAM_NAME

- $0

You can access the program name in Perl 6 via $*PROGRAM-NAME.

Note: $0 in Perl 6 is the variable holding the first captured value from a match (i. e. capture variables now start from $0 rather than $1).

- $REAL_GROUP_ID

- $GID

- $(

The real group id is provided by $*GROUP.Numeric in Perl 6. $*GROUP.Str returns the group name, rather than its number.

- $EFFECTIVE_GROUP_ID

- $EGID

- $)

The effective group id does not appear to be currently provided by Perl 6.

- $REAL_USER_ID

- $UID

- $<

The real user id is provided by $*USER.Numeric in Perl 6. $*USER.Str returns the user name, rather than its number.

- $EFFECTIVE_USER_ID

- $EUID

- $>

The effective user id does not appear to be currently provided by Perl 6.

- $SUBSCRIPT_SEPARATOR

- $SUBSEP

- $;

The subscript separator variable is not included in Perl 6. Frankly, if your Perl 5 code is using this, it's almost certainly really, really old.

- $a

- $b

$a and $b have no special meaning in Perl 6. sort() does not use them for anything special. They're just regular old variables.

This feature has been extended by having blocks with placeholder parameters which are more versatile. Placeholder variables are created with the ^ twigil (e. g. $^z. They can be used in a bare block or in a subroutine without an explicit parameter list. The arguments to the block are assigned to the placeholder variables in their Unicode order. I. e. even if the variables appear in the block in the order ($^q, $^z, $^a), they will be assigned in the order ($^a, $^q, $^z). Ergo:

        sort { $^a cmp $^z }, 1, 5, 6, 4, 2, 3;
         # (1 2 3 4 5 6)
         sort { $^g cmp $^a }, 1, 5, 6, 4, 2, 3;
         # (6 5 4 3 2 1)
         for 1..9 { say $^c, $^a, $^b; last }
         # 312

For more on placeholder variables, see this page

- %ENV

%ENV has been replaced by %*ENV in Perl 6. Note that the keys of this hash may not be exactly the same between Perl 5 and Perl 6. As of this writing, the only difference seems to be that OLDPWD is missing from Perl 6's %ENV.

- $OLD_PERL_VERSION

- $]

The version of perl is returned by $*PERL.version. For the beta this was "v6.b" with $*PERL containing "Perl 6 (6.b)".

- $SYSTEM_FD_MAX

- $^F

Although the design documents (S28) indicate that this will likely become $*SYS_FD_MAX, this has not yet been implemented.

- @F

[NEEDS FURTHER RESEARCH] A bit confusing at this point. Design doc S28 indicates that @F in Perl 5 is replaced by @_ in Perl 6, but it's unclear just how that works. On the other hand, it's currently something of a moot point, as the Perl 5 to Perl 6 Translation doc indicates that the -a and -F command-line switches are not yet implemented in rakudo.

- @INC

No longer exists in Perl 6. Please use "use lib" to manipulate the module repositories to be searched. The closest thing to @INC is really $*REPO. But that works completely differently from @INC mostly because of the precompilation capabilities of Perl 6.

    # Print out a list of compunit repositories
    .say for $*REPO.repo-chain;

- %INC

No longer exists in Perl 6. Because each Repository is responsible for remembering which modules have been loaded already. You can get a list of all loaded modules (compilation units) like so:

    use Test;
    use MyModule;
    say flat $*REPO.repo-chain.map(*.loaded); #-> (MyModule Test)

- $INPLACE_EDIT

- $^I

S28 suggests $*INPLACE_EDIT, but it does not yet seem to exist.

- $^M

S28 suggests $*EMERGENCY_MEMORY, but it does not yet seem to exist.

- $OSNAME

- $^O

This is somewhat unclear. It probably depends on what you mean by "the name of the operating system" as S28 has three different suggestions, all of which give different answers. On my OS X machine at this time...

    say $*KERNEL; # gives "darwin (14.3.0)"
    say $*DISTRO; # gives "macosx (10.10.3)"

Using .version on either of those will give you just the version number. .name gives the kernel or distro name. Those objects contain other information as well.

S28 also lists $*VM (which with my build of rakudo star currently gives "moar (2015.5.63.ge.7.a.473.c)"), but I'm unclear how the VM relates at all to the operating system.

- %SIG

[NEEDS FURTHER RESEARCH] No equivalent variable. S28 indicates that this functionality is dealt with in Perl 6 by event filters and exception translation.

- $BASETIME

- $^T

Replaced in Perl 6 by $*INITTIME. Unlike in Perl 5, this is not in seconds since epoch, but an Instant object, which is measured in atomic seconds, with fractions.

- $PERL_VERSION

- $^V

As with $] this has been replaced with $*PERL.version.

- ${^WIN32_SLOPPY_STAT}

There does not seem to be any analog to this in Perl 6.

- $EXECUTABLE_NAME

- $^X

This has been replaced by $*EXECUTABLE-NAME. Confusingly, the Perl 6 Variables doc says "Favor $*EXECUTABLE because it is not guaranteed that the perl executable is in PATH." Confusingly because $*EXECUTABLE is an IO object, which does not seem to be what you would want here. $*EXECUTABLE.Str would give the desired result, though.

## 5.3.2 Variables related to regular expressions

### 5.3.2.1 Performance issues

As shown below, $`, $&, and $' are gone from Perl 6, primarily replaced by variations on $/ and, with their elimination, the associated performance issues in Perl 5 do not apply.

- $<digits> ($1, $2, ...)

These existing variables do the same thing in Perl 6 as they do in Perl 5, except that they now start at $0 rather than $1. Furthermore, they are synonyms for indexed items in the match variable $/. I. e. $0 is equivalent to $/[0], $1 is equivalent to $/[1], etc.

- $MATCH

- $&

$/ now contains the match object, so the Perl 5 behavior of $& can be obtained by stringifying it, i. e. ~$/. $/.Str also should work, but ~$/ seems to be the consensus preference.

- ${^MATCH}

Since the former performance issues are done away with, this variable is not of use in Perl 6.

- $PREMATCH

- $`

Replaced by $/.prematch.

- ${^PREMATCH}

Since the former performance issues are done away with, this variable is not of use in Perl 6.

- $POSTMATCH

- $'

Replaced by $/.postmatch.

- ${^POSTMATCH}

Since the former performance issues are done away with, this variable is not of use in Perl 6.

- $LAST_PAREN_MATCH

- $+

Does not exist in Perl 6, but you can get the same information using $/[*- 1].Str ($/[*-1] would be the match object, not the actual string).

If you want to understand why that works, you can look at these documents:

- [ ] routine

- Whatever

...and possibly

- https://design.perl6.org/S02.html#line_1126

...though the design documents are not always up to date.

- $LAST_SUBMATCH_RESULT

- $^N

S28 suggests $*MOST_RECENT_CAPTURED_MATCH, but there does not seem to be any implemented variable that matches $^N.

- @LAST_MATCH_END

- @+

As with most regular expression related variables, this functionality is, at least in part, moved to the $/ variable in Perl 6. Or, in this case, the numbered variables that alias to the indexes of it. The offset is found by using the .to method. I. e. the first offset is $/[0].to, which is synonymous with $0.to. The value Perl 5 provides as $+[0] is provided by $/.to.

- %LAST_PAREN_MATCH

- %+

Once again, we move over to $/. The former $+{$match} is $/{$match}.

- @LAST_MATCH_START

- @-

Similarly to @+ being replaced by using the .to method, @- is replaced by using the .from method on $/ and its variations. The first offset is $/[0].from or the equivalent $0.from. Perl 5's $- [0] is $/.from.

- %LAST_MATCH_START

- %-

Much like %+, a use of %-{$match} would be replaced with $/{$match}.

- $LAST_REGEXP_CODE_RESULT

- $^R

S28 suggests $*LAST_REGEXP_CODE_RESULT, but no variable seems to actually exist yet.

- ${^RE_DEBUG_FLAGS}

No equivalent.

- ${^RE_TRIE_MAXBUF}

No equivalent.

## 5.3.3 Variables related to filehandles

- $ARGV

The name of the current file when reading lines can be obtained through $*ARGFILES.filename.

- @ARGV

@*ARGS contains the command line arguments.

- ARGV

This has been replaced by $*ARGFILES.

- ARGVOUT

As the -i command line switch has not yet been implemented, there is not yet an equivalent of ARGVOUT.

- $OUTPUT_FIELD_SEPARATOR

- $OFS

- $,

Currently no obvious equivalent.

- $INPUT_LINE_NUMBER

- $NR

- $.

The current line number is returned by the .ins method on the appropriate filehandle. E. g. $*IN.ins.

- $INPUT_RECORD_SEPARATOR

- $RS

- $/

This is accessed through the .nl-in method on the filehandle. E. g. $*IN.nl-in.

- $OUTPUT_RECORD_SEPARATOR

- $ORS

- $\

This is accessed through the .nl-out method on the filehandle. E. g. $*OUT.nl-out.

- $OUTPUT_AUTOFLUSH

- $|

Currently autoflush is not implemented in Perl 6.

- ${^LAST_FH}

Not implemented in Perl 6.

### 5.3.3.1 Variables related to formats

There are no built-in formats in Perl 6.

## 5.3.4 Error Variables

Because of how error variables have changed in Perl 6, I will not detail the changes individually.

To quote the Perl 6 docs, "$! is the error variable." That's it. All the error variables appear to have been eaten by $!. As with the rest of Perl 6, it's likely an object that will return various things depending on how you use it. Sadly, at the moment, the documentation for it is terribly sparse. It will probably do what you intend, but I'm not guaranteeing anything. Hopefully there will be more information in the near future.

## 5.3.5 Variables related to the interpreter state

- $COMPILING

- $^C

- $^D

Currently no equivalents for either of these variables.

- ${^ENCODING}

Although deprecated in Perl 5, this may have some sort of equivalent in $?ENC, but this is far from clear.

- ${^GLOBAL_PHASE}

No Perl 6 equivalent.

- $^H

- %^H

- ${^OPEN}

There may or may not be equivalents of these in Perl 6, but they're internal and you shouldn't be messing with them in the first place - certainly not if your understanding of Perl 6 requires you to read this document...

- $PERLDB

- $^P

The chance of the Perl 6 debugger resembling the Perl 5 debugger is slim at best, and at this point there does not seem to be an equivalent of this variable.

- ${^TAINT}

S28 claims this variable is "pending". Not currently in Perl 6.

- ${^UNICODE}

- ${^UTF8CACHE}

- ${^UTF8LOCALE}

These Unicode-related variables do not appear to exist in Perl 6, but - maybe? - could have analogs in $?ENC somewhere. This, however, is totally unconfirmed.

## 5.3.6 Deprecated and removed variables

It should go without saying that, as these have been removed from Perl 5 already, there should be no need to tell you how to use them in Perl 6.

# 6 About the Docs

Documentation for the Perl 6 Documentation Project

This documentation is an attempt to document the Perl 6 programming language with the goals of being comprehensive, easy to use, easy to navigate, and useful to both newcomers and experienced Perl 6 programmers.

An HTML version of the documentation is located online at https://docs.perl6.org.

The official source for this documentation is located at perl6/doc on GitHub.

# 6.1 Structure

All of the documentation is written in Pod6 and kept in the lib/ directory, and the lib/Language/ and lib/Type/ sub-directories. These files are processed as collections of definitions or "documentables", which are then post-processed and linked together.

# 6.2 Generating an HTML version

Generating this documentation requires:

- A recent version of the Rakudo Perl 6 compiler

- The Perl 6 modules Pod::To::HTML and URI::Escape (can be installed via panda)

- Optional: GraphViz, for creating graphs of the relationships between Perl 6 types

- Optional: Pygments, for doing syntax highlighting

Then, to generate the documentation into the html/ folder, run:

    perl6 htmlify.p6

Currently, to serve the generated documentation for your browser, Perl 5 with Mojolicious::Lite must be installed. Then run:

    perl app.pl daemon

# 6.3 Contributing

## 6.3.1 Adding definitions

Documentables can be defined using an =headN Pod directive, where N is greater than zero (e.g., =head1, =head2, =head3, …).

All of the paragraphs and blocks following that directive, up until the next directive of the same level, will be considered part of the documentable. So, in:

    =head2  <var class="replaceable">My Definition</var>

     Some paragraphs, followed by some code:

         my Code $examples = "amazing";

     Mind === blown.

     =head3 Minor details about  <var class="replaceable">My Definition</var>

     It's fantastic.

     =head2 And now, for something completely different

     …

The documentable My Definition extends down to the =head2 And now….

Documentables may contain other documentables. Class documentables, for example, often contain the methods the class implements.

Definitions must be in one of the following forms to be recognized as the start of a documentable named, say, Z:

- X<How to use the Z infix | infix,Z> (This a special case, which is always considered a definition)

- The Z Infix

- The C<Z> Infix

- Infix Z

- Infix C<Z>

- trait is cached (A special case for the trait documentables)

# 7 Classes and Objects

A tutorial for creating and using classes in Perl 6

More descriptive title?

Perl 6 has a rich built in syntax for the definition and use of classes for object oriented programming, allowing for the definition of state (as attributes,) and behaviour (as methods,) in the objects of a class.

A simple class is provided with a default constructor, that allows the setting of the attributes of the created object:

    class Point {
         has Int $.x;
         has Int $.y;
     }

     class Rectangle {
         has Point $.lower;
         has Point $.upper;

         method area() returns Int {
             ($!upper.x - $!lower.x) * ( $!upper.y - $!lower.y);
         }
     }

     # Create a new Rectangle from two Points
     my $r = Rectangle.new(lower => Point.new(x => 0, y => 0), upper => Point.new(x => 10, y => 10));

     say $r.area(); # -> 100

You are free, though, to provide your own construction and build implementation. The following, more elaborate, example shows how a dependency handler might look in Perl 6. It showcases custom constructors, private and public attributes, methods and various aspects of signatures. It's not very much code, and yet the result is interesting and, at times, useful.

    class Task {
         has      &amp;!callback;
         has Task @!dependencies;
         has Bool $.done;

         # Normally doesn't need to be written
         # BUILD is the equivalent of a constructor in other languages
         method new(&amp;callback, *@dependencies) {
             return self.bless(:&amp;callback, :@dependencies);
         }

         submethod BUILD(:&amp;!callback, :@!dependencies) { }

         method add-dependency(Task $dependency) {
             push @!dependencies, $dependency;
         }

         method perform() {
             unless $!done {
                 .perform() for @!dependencies;
                 &amp;!callback();
                 $!done = True;
             }
         }
     }

     my $eat =
         Task.new({ say 'eating dinner. NOM!' },
             Task.new({ say 'making dinner' },
                 Task.new({ say 'buying food' },
                     Task.new({ say 'making some money' }),
                     Task.new({ say 'going to the store' })
                 ),
                 Task.new({ say 'cleaning kitchen' })
             )
         );

     $eat.perform();

# 7.1 Starting with class

Perl 6, like many other languages, uses the class keyword to introduce a new class. The block that follows may contain arbitrary code, just as with any other block, but classes commonly contain state and behavior declarations. The example code includes attributes (state), introduced through the has keyword, and behaviors introduced through the method keyword.

Declaring a class creates a type object which, by default, is installed into the current package (just like a variable declared with our scope). This type object is an "empty instance" of the class. You've already seen these in previous chapters. For example, types such as Int and Str refer to the type object of one of the Perl 6 built-in classes. The example above uses the class name Task so that other code can refer to it later, such as to create class instances by calling the new method.

Type objects are undefined, in the sense that they return False if you call the .defined method on them. You can use this method to find out if a given object is a type object or not:

    my $obj = Int;
    if $obj.defined {
        say "Ordinary, defined object";
    } else {
        say "Type object";
    }

# 7.2 State

The first three lines inside the class block all declare attributes (called fields or instance storage in other languages). These are storage locations that every instance of a class will obtain. Just as a my variable cannot be accessed from outside its declared scope, attributes are not accessible outside of the class. This encapsulation is one of the key principles of object oriented design.

The first declaration specifies instance storage for a callback -- a bit of code to invoke in order to perform the task that an object represents:

    has &amp;!callback;

The & sigil indicates that this attribute represents something invocable. The ! character is a twigil, or secondary sigil. A twigil forms part of the name of the variable. In this case, the ! twigil emphasizes that this attribute is private to the class.

The second declaration also uses the private twigil:

    has Task @!dependencies;

However, this attribute represents an array of items, so it requires the @ sigil. These items each specify a task that must be completed before the present one can complete. Furthermore, the type declaration on this attribute indicates that the array may only hold instances of the Task class (or some subclass of it).

The third attribute represents the state of completion of a task:

    has Bool $.done;

This scalar attribute (with the $ sigil) has a type of Bool. Instead of the ! twigil, the . twigil is used. While Perl 6 does enforce encapsulation on attributes, it also saves you from writing accessor methods. Replacing the ! with a . both declares the attribute $!done and an accessor method named done. It's as if you had written:

    has Bool $!done;
    method done() { return $!done }

Note that this is not like declaring a public attribute, as some languages allow; you really get both a private storage location and a method, without having to write the method by hand. You are free instead to write your own accessor method, if at some future point you need to do something more complex than return the value.

Note that using the . twigil has created a method that will provide read-only access to the attribute. If instead the users of this object should be able to reset a task's completion state (perhaps to perform it again), you can change the attribute declaration:

    has Bool $.done is rw;

The is rw trait causes the generated accessor method to return something external code can modify to change the value of the attribute.

You can also supply default values to attributes (which works equally for those with and without accessors):

    has Bool $.done = False;

The assignment is carried out at object build time. The right-hand side is evaluated at that time, and can even reference earlier attributes:

    has Task @!dependencies;
    has $.ready = not @!dependencies;

# 7.3 Static fields?

Perl 6 has no static keyword. Nevertheless any class may declare anything that a module can, so making a scoped variable sounds like good idea.

    class Singleton {
         my Singleton $instance;
         method new {!!!}
         submethod instance {
             $instance = Singleton.bless unless $instance;
             $instance;
         }
     }

Class attributes defined by my or our may also be initialized when being declared, however we are implementing the Singleton pattern here and the object must be created during its first use. It is not 100% possible to predict the moment when attribute initialization will be executed, because it can take place during compilation, runtime or both, especially when importing the class using the use keyword.

    class HaveStaticAttr {
          my Foo $.foo = some_complicated_subroutine;
    }

Class attributes may also be declared with a secondary sigil -- in a similar manner to object attributes -- that will generate read-only accessors if the attribute is to be public.

# 7.4 Methods

While attributes give objects state, methods give objects behaviors. Let's ignore the new method temporarily; it's a special type of method. Consider the second method, add-dependency, which adds a new task to a task's dependency list.

    method add-dependency(Task $dependency) {
        push @!dependencies, $dependency;
    }

In many ways, this looks a lot like a sub declaration. However, there are two important differences. First, declaring this routine as a method adds it to the list of methods for the current class. Thus any instance of the Task class can call this method with the . method call operator. Second, a method places its invocant into the special variable self.

The method itself takes the passed parameter -- which must be an instance of the Task class -- and pushes it onto the invocant's @!dependencies attribute.

The second method contains the main logic of the dependency handler:

    method perform() {
        unless $!done {
            .perform() for @!dependencies;
            &amp;!callback();
            $!done = True;
        }
    }

It takes no parameters, working instead with the object's attributes. First, it checks if the task has already completed by checking the $!done attribute. If so, there's nothing to do.

Otherwise, the method performs all of the task's dependencies, using the for construct to iterate over all of the items in the @!dependencies attribute. This iteration places each item -- each a Task object -- into the topic variable, $_. Using the . method call operator without specifying an explicit invocant uses the current topic as the invocant. Thus the iteration construct calls the .perform() method on every Task object in the @!dependencies attribute of the current invocant.

After all of the dependencies have completed, it's time to perform the current Task's task by invoking the &!callback attribute directly; this is the purpose of the parentheses. Finally, the method sets the $!done attribute to True, so that subsequent invocations of perform on this object (if this Task is a dependency of another Task, for example) will not repeat the task.

## 7.4.1 Private Methods

Analogous to attributes, methods can be private. Private methods are declared with a prefixed exclamation mark. They are called with self! followed by the method's name. To call a private method of another class the calling class has to be trusted by the called class. A trust relationship is declared with trusts and the class to be trusted must already be declared. Calling a private method of another class requires an instance of that class and the fully qualified name of the method. Trust also allows access to private attributes.

    class B {...}

    class C {
        trusts B;
        has $!hidden = 'invisible';
        method !not-yours () { say 'hidden' }
        method yours-to-use () {
            say $!hidden;
            self!not-yours();
        }
    }

    class B {
        method i-am-trusted () {
            my C $c.=new;
            $c!C::not-yours();
        }
    }

    C.new.yours-to-use(); # the context of this call is GLOBAL, and not trusted by C
    B.new.i-am-trusted();

Trust relationships are not subject to inheritance. To trust the global namespace, the pseudo package GLOBAL can be used.

# 7.5 Constructors

Perl 6 is rather more liberal than many languages in the area of constructors. A constructor is anything that returns an instance of the class. Furthermore, constructors are ordinary methods. You inherit a default constructor named new from the base class Mu, but you are free to override new, as this example does:

    method new(&amp;callback, *@dependencies) {
        return self.bless(:&amp;callback, :@dependencies);
    }

The biggest difference between constructors in Perl 6 and constructors in languages such as C# and Java is that rather than setting up state on a somehow already magically created object, Perl 6 constructors actually create the object themselves. The easiest way to do this is by calling the bless method, also inherited from Mu. The bless method expects a set of named parameters providing the initial values for each attribute.

The example's constructor turns positional arguments into named arguments, so that the class can provide a nice constructor for its users. The first parameter is the callback (the thing which will execute the task). The rest of the parameters are dependent Task instances. The constructor captures these into the @dependencies slurpy array and passes them as named parameters to bless (note that :&callback uses the name of the variable -- minus the sigil -- as the name of the parameter).

Private attributes really are private. This means that bless is not allowed to bind things to &!callback and @!dependencies directly. To do this, we override the BUILD submethod, which is called on the brand new object by bless:

    submethod BUILD(:&amp;!callback, :@!dependencies) { }

Since BUILD runs in the context of the newly created Task object, it is allowed to manipulate those private attributes. The trick here is that the private attributes (&!callback and @!dependencies) are being used as the bind targets for BUILD's parameters. Zero-boilerplate initialization! See objects for more information.

The BUILD method is responsible for initializing all attributes, it must handle default values too:

    has &amp;!callback;
    has @!dependencies;
    has Bool ($.done, $.ready);
    submethod BUILD(
            :&amp;!callback,
            :@!dependencies,
            :$!done = False,
            :$!ready = not @!dependencies
        ) { }

See Object Construction for more options to influence object construction and attribute initialization.

# 7.6 Consuming our class

After creating a class, you can create instances of the class. Declaring a custom constructor provides a simple way of declaring tasks along with their dependencies. To create a single task with no dependencies, write:

    my $eat = Task.new({ say 'eating dinner. NOM!' });

An earlier section explained that declaring the class Task installed a type object in the namespace. This type object is a kind of "empty instance" of the class, specifically an instance without any state. You can call methods on that instance, as long as they do not try to access any state; new is an example, as it creates a new object rather than modifying or accessing an existing object.

Unfortunately, dinner never magically happens. It has dependent tasks:

    my $eat =
        Task.new({ say 'eating dinner. NOM!' },
            Task.new({ say 'making dinner' },
                Task.new({ say 'buying food' },
                    Task.new({ say 'making some money' }),
                    Task.new({ say 'going to the store' })
                ),
                Task.new({ say 'cleaning kitchen' })
            )
        );

Notice how the custom constructor and sensible use of whitespace allows a layout which makes task dependencies clear.

Finally, the perform method call recursively calls the perform method on the various other dependencies in order, giving the output:

    making some money
    going to the store
    buying food
    cleaning kitchen
    making dinner
    eating dinner. NOM!

# 7.7 Inheritance

Object Oriented Programming provides the concept of inheritance as one of the mechanisms to allow for code reuse. Perl 6 supports the ability for one class to inherit from one or more classes. When a class inherits from another class it informs the method dispatcher to follow the inheritance chain to look for a method to dispatch. This happens both for standard methods defined via the method keyword and for methods generated through other means such as attribute accessors.

    class Employee {
         has $.salary;

         method pay() {
             say "Here is \$$.salary";
         }
     }

     class Programmer is Employee {
         has @.known_languages is rw;
         has $.favorite_editor;

         method code_to_solve( $problem ) {
             say "Solving $problem using $.favorite_editor in "
             ~ $.known_languages[0] ~ '.';
         }
     }

Now any object of type Programmer can make use of the methods and accessors defined in the Employee class as though they were from the Programmer class.

    my $programmer = Programmer.new(
         salary => 100_000,
         known_languages => &lt;Perl5 Perl6 Erlang C++>,
         favorite_editor => 'vim'
     );

     $programmer.code_to_solve('halting problem');
     $programmer.pay();

## 7.7.1 Overriding inherited methods

Of course, classes can override methods and attributes defined by parent classes by defining their own. The example below demonstrates the Baker class overriding the Cook's cook method.

    class Cook is Employee {
         has @.utensils  is rw;
         has @.cookbooks is rw;

         method cook( $food ) {
             say "Cooking $food";
         }

         method clean_utensils {
             say "Cleaning $_" for @.utensils;
         }
     }

     class Baker is Cook {
         method cook( $confection ) {
             say "Baking a tasty $confection";
         }
     }

     my $cook = Cook.new(
         utensils => &lt;spoon ladle knife pan>,
         cookbooks => 'The Joy of Cooking',
         salary => 40000);

     $cook.cook( 'pizza' ); # Cooking pizza

     my $baker = Baker.new(
         utensils => 'self cleaning oven',
         cookbooks => "The Baker's Apprentice",
         salary => 50000);

     $baker.cook('brioche'); # Baking a tasty brioche

Because the dispatcher will see the cook method on Baker before it moves up to the parent class the Baker's cook method will be called.

As a side note, you might have wondered how passing strings to an array attribute worked. Array assignment is coercive, so the assignment turns the new value into an array. This mechanism is also used for initializing attributes.

## 7.7.2 Multiple inheritance

As mentioned before, a class can inherit from multiple classes. When a class inherits from multiple classes the dispatcher knows to look at both classes when looking up a method to search for. Perl 6 uses the C3 algorithm to linearize multiple inheritance hierarchies, which is a significant improvement over Perl 5's default approach (depth-first search) to handling multiple inheritance.

    class GeekCook is Programmer is Cook {
         method new( *%params ) {
             push( %params&lt;cookbooks>, "Cooking for Geeks" );
             return self.bless(|%params);
         }
     }

     my $geek = GeekCook.new(
         books           => 'Learning Perl 6',
         utensils        => ('stainless steel pot', 'knife', 'calibrated oven'),
         favorite_editor => 'MacVim',
         known_languages => &lt;Perl6>
     );

     $geek.cook('pizza');
     $geek.code_to_solve('P =? NP');

Now all the methods made available to the Programmer and the Cook classes are available from the GeekCook class.

While multiple inheritance is a useful concept to know and occasionally use, it is important to understand that there are more useful OOP concepts. When reaching for multiple inheritance it is good practice to consider whether the design wouldn't be better realized by using roles, which are generally safer because they force the class author to explicitly resolve conflicting method names. For more information on roles see Roles.

## 7.7.3 The also declarator

Classes to be inherited from can be listed in the class declaration body by prefixing the is trait with also. This also works for the role composition trait does.

    class GeekCook {
        also is Programmer;
        also is Cook;
        # ...
    }

    role A {};
    role B {};
    class C { also does A; also does B }

# 7.8 Introspection

Introspection is the process of gathering information about some objects in your program, not by reading the source code, but by querying the object (or a controlling object) for some properties, such as its type.

Given an object $o, and the class definitions from the previous sections, we can ask it a few questions:

    if $o ~~ Employee { say "It's an employee" };
    if $o ~~ GeekCook { say "It's a geeky cook" };
    say $o.WHAT;
    say $o.perl;
    say $o.^methods(:local).join(', ');
    say $o.^name;

The output can look like this:

    It's an employee
    (Programmer)
    Programmer.new(known_languages => ["Perl", "Python", "Pascal"],
            favorite_editor => "gvim", salary => "too small")
    code_to_solve, known_languages, favorite_editor
    Programmer

The first two tests each smart-match against a class name. If the object is of that class, or of an inheriting class, it returns true. So the object in question is of class Employee or one that inherits from it, but not GeekCook.

The .WHAT method returns the type object associated with the object $o, which tells us the exact type of $o: in this case Programmer.

$o.perl returns a string that can be executed as Perl code, and reproduces the original object $o. While this does not work perfectly in all cases

For example closures cannot easily be reproduced this way; if you don't know what a closure is don't worry. Also current implementations have problems with dumping cyclic data structures this way, but they are expected to be handled correctly by .perl at some point.
, it is very useful for debugging simple objects.

$o.^methods(:local) produces a list of Methods that can be called on $o. The :local named argument limits the returned methods to those defined in the Employee class and excludes the inherited methods.

The syntax of calling a method with .^ instead of a single dot means that it is actually a method call on its meta class, which is a class managing the properties of the Employee class -- or any other class you are interested in. This meta class enables other ways of introspection too:

    say $o.^attributes.join(', ');
    say $o.^parents.map({ $_.^name }).join(', ');

Finally $o.^name calls the name method on the meta object, which unsurprisingly returns the class name.

Introspection is very useful for debugging, and for learning the language and new libraries. When a function or method returns an object you don't know about, finding its type with .WHAT, seeing a construction recipe for it with .perl, and so on, you'll get a good idea of what its return value is. With .^methods you can learn what you can do with the class.

But there are other applications too: a routine that serializes objects to a bunch of bytes needs to know the attributes of that object, which it can find out via introspection.

# 8 Concurrency

Concurrency and Asynchronous Programming

In common with most modern programming languages, Perl 6 is designed to support concurrency (allowing more than one thing to happen at the same time) and asynchronous programming (sometimes called event driven or reactive programming - that is an event or change in some part of a program may lead to an event or change in some other part of the program asynchronously to the program flow).

The aim of the Perl concurrency design is to provide a high-level, composable, consistent interface, regardless of how a virtual machine may implement it for a particular operating system, through layers of facilities as described below.

I'm not quite clear which specific features should be included below hyper-operators, autothreading junctions?

Additionally, certain Perl features may implicitly operate in an asynchronous fashion, so in order to ensure predictable interoperation with these features, user code should, where possible, avoid the lower level concurrency APIs (i.e. Thread and Scheduler ) and use the higher-level interfaces.

# 8.1 High-level APIs

## 8.1.1 Promises

A Promise (also called future in other programming environments) encapsulates the result of a computation that may not have completed or even started at the time the promise is obtained. It provides much of the functionality that user code needs to operate in a concurrent or asynchronous manner.

    my $p1 = Promise.new;
     say $p1.status;         # Planned;
     $p1.keep('result');
     say $p1.status;         # Kept
     say $p1.result;         # result

     my $p2 = Promise.new;
     $p2.break('oh no');
     say $p2.status;         # Broken
     say $p2.result;         # dies with "oh no"

Promises gain much of their power by being composable, for example by chaining:

    my $promise1 = Promise.new();
    my $promise2 = $promise1.then(
        -> $v { say $v.result; "Second Result"}
    );
    $promise1.keep("First Result");
    say $promise2.result;   # First Result \n Second Result

Here the then method schedules code to be executed when the first Promise is kept or broken, itself returning a new Promise which will be kept with the result of the code when it is executed (or broken if the code fails.) keep changes the status of the promise to Kept setting the result to the positional argument. result blocks the current thread of execution until the promise is kept or broken, if it was kept then it will return the result (that is the value passed to keep, ) otherwise it will throw an exception based on the value passed to break. The latter behaviour is illustrated with:

    my $promise1 = Promise.new();
    my $promise2 = $promise1.then(-> $v { say "Handled but : "; say $v.result});
    $promise1.break("First Result");
    try $promise2.result;
    say $promise2.cause;        # Handled but : \n First Result

Here the break will cause the code block of the then to throw an exception when it calls the result method on the original promise that was passed as an argument, which will subsequently cause the second promise to be broken, raising an exception in turn when its result is taken. The actual Exception object will then be available from cause. If the promise had not been broken cause would raise a X::Promise::CauseOnlyValidOnBroken exception.

A Promise can also be scheduled to be automatically kept at a future time:

    my $promise1 = Promise.in(5);
    my $promise2 = $promise1.then(-> $v { say $v.status; 'Second Result' });
    say $promise2.result;

The method in creates a new promise and schedules a new task to call keep on it no earlier than the supplied number of seconds, returning the new Promise object.

A very frequent use of promises is to run a piece of code, and keep the promise once it returns successfully, or break it when the code dies. The start method provides a shortcut for that:

    my $promise = Promise.start(
        { my $i = 0; for 1 .. 10 { $i += $_ }; $i}
    );
    say $promise.result;    # 55

Here the result of the promise returned is the value returned from the code. Similarly if the code fails (and the promise is thus broken), then cause will be the Exception object that was thrown:

    my $promise = Promise.start({ die "Broken Promise" });
    try $promise.result;
    say $promise.cause;

This is considered to be such a commonly required pattern that it is also provided as subroutines:

    my $promise = start {
        my $i = 0;
        for 1 .. 10 {
            $i += $_
        }
        $i
    }
    my $result = await $promise;
    say $result;

await is almost equivalent to calling result on the promise object returned by start but it will also take a list of promises and return the result of each:

    my $p1 = start {
        my $i = 0;
        for 1 .. 10 {
            $i += $_
        }
        $i
    };
    my $p2 = start {
        my $i = 0;
        for 1 .. 10 {
            $i -= $_
        }
        $i
    };
    my @result = await $p1, $p2;
    say @result;            # 55 -55

In addition to await, two class methods combine several Promise objects into a new promise: allof returns a promise that is kept when all the original promises are kept or broken:

    my $promise = Promise.allof(
        Promise.in(2),
        Promise.in(3)
    );

    await $promise;
    say "All done"; # Should be not much more than three seconds later

And anyof returns a new promise that will be kept when any of the original promises is kept or broken:

    my $promise = Promise.anyof(
        Promise.in(3),
        Promise.in(8600)
    );

    await $promise;
    say "All done"; # Should be about 3 seconds later

Unlike await however the results of the original kept promises are not available without referring to the original, so these are more useful when the completion or otherwise of the tasks is more important to the consumer than the actual results, or when the results have been collected by other means. You may, for example, want to create a dependent Promise that will examine each of the original promises:

    my @promises;
    for 1..5 -> $t {
        push @promises, start {
            sleep $t;
            Bool.pick;
        };
    }
    say await Promise.allof(@promises).then({ so all(@promises>>.result) });

Which will give True if all of the promises were kept with True, False otherwise.

If you are creating a promise that you intend to keep or break yourself then you probably don't want any code that might receive the promise to inadvertently (or otherwise,) keep or break the promise before you do. For this purpose there is the method vow, which returns a Vow object which becomes the only mechanism by which the promise can be kept or broken. If an attempt to keep or break the Promise is made directly then the exception X::Promise::Vowed will be thrown, as long as the vow object is kept private, the status of the promise is safe:

    sub get_promise {
        my $promise = Promise.new;
        my $vow = $promise.vow;
        Promise.in(10).then({$vow.keep});
        $promise;
    }

    my $promise = get_promise();

    # Will throw an exception
    # "Access denied to keep/break this Promise; already vowed"
    $promise.keep;

The methods that return a promise that will be kept or broken automatically such as in or start will do this, so it is not necessary to do it for these.

## 8.1.2 Supplies

A Supply is an asynchronous data streaming mechanism that can be consumed by one or more consumers simultaneously in a manner similar to "events" in other programming languages and can be seen as enabling "Event Driven" or reactive designs.

At its simplest, a Supply is a message stream that can have multiple subscribers created with the method tap on to which data items can be placed with emit.

The Supply can either be live or on-demand. A live supply is like a TV broadcast: those who tune in don't get previously emitted values. An on-demand broadcast is like Netflix: everyone who starts streaming a movie (taps a supply), always starts it from the beginning (gets all the values), regardless of how many people are watching it right now. Note that no history is kept for on-demand supplies, instead, the supply block is run for each tap of the supply.

A live Supply is created by the Supplier factory, each emitted value is passed to all the active tappers as they are added:

    my $supplier = Supplier.new;
    my $supply   = $supplier.Supply;

    $supply.tap( -> $v { say $v });

    for 1 .. 10 {
        $supplier.emit($_);
    }

Note that the tap is called on a Supply object created by the Supplier and new values are emitted on the Supplier.

Or alternatively as an on-demand Supply created by the supply keyword:

    my $supply = supply {
        for 1 .. 10 {
            emit($_);
        }
    }
    $supply.tap( -> $v { say $v });

In this case the code in the supply block is executed every time the Supply returned by supply is tapped, as demonstrated by:

    my $supply = supply {
        for 1 .. 10 {
            emit($_);
        }
    }
    $supply.tap( -> $v { say "First : $v" });
    $supply.tap( -> $v { say "Second : $v" });

The tap method returns a Tap object which can be used to obtain information about the tap and also to turn it off when we are no longer interested in the events:

    my $supplier = Supplier.new;
    my $supply   = $supplier.Supply;

    my $tap = $supply.tap( -> $v { say $v });

    $supplier.emit("OK");
    $tap.close;
    $supplier.emit("Won't trigger the tap");

Calling done on the supply object calls the done callback that may be specified for any taps, but does not prevent any further events being emitted to the stream, or taps receiving them.

The method interval returns a new on-demand supply which periodically emits a new event at the specified interval. The data that is emitted is an integer starting at 0 that is incremented for each event. The following code outputs 0 .. 5 :

    my $supply = Supply.interval(2);
    $supply.tap(-> $v { say $v });
    sleep 10;

This could also be written using the react keyword:

    react {
        whenever Supply.interval(2) -> $v {
            say $v;
            done() if $v == 4;
        }
    }

Here the whenever keyword creates a tap on the Supply from the provided block. The react block is exited when done() is called in one of the taps.

A second argument can be supplied to interval which specifies a delay in seconds before the first event is fired. Each tap of a supply created by interval has its own sequence starting from 0, as illustrated by the following:

    my $supply = Supply.interval(2);
    $supply.tap(-> $v { say "First $v" });
    sleep 6;
    $supply.tap(-> $v { say "Second $v"});
    sleep 10;

An on-demand Supply can also be created from a list of values that will be emitted in turn, thus the first on-demand example could be written as:

    react {
        whenever Supply.from-list(1..10) -> $v {
            say $v;
        }
    }

An existing supply object can be filtered or transformed, using the methods grep and map respectively, to create a new supply in a manner like the similarly named list methods: grep returns a supply such that only those events emitted on the source stream for which the grep condition is true is emitted on the second supply:

    my $supplier = Supplier.new;
    my $supply = $supplier.Supply;
    $supply.tap(-> $v { say "Original : $v" });
    my $odd_supply = $supply.grep({ $_ % 2 });
    $odd_supply.tap(-> $v { say "Odd : $v" });
    my $even_supply = $supply.grep({ not $_ % 2 });
    $even_supply.tap(-> $v { say "Even : $v" });
    for 0 .. 10 {
        $supplier.emit($_);
    }

map returns a new supply such that for each item emitted to the original supply a new item which is the result of the expression passed to the map is emitted:

    my $supplier = Supplier.new;
    my $supply = $supplier.Supply;
    $supply.tap(-> $v { say "Original : $v" });
    my $half_supply = $supply.map({ $_ / 2 });
    $half_supply.tap(-> $v { say "Half : $v" });
    for 0 .. 10 {
        $supplier.emit($_);
    }

If you need to have an action that runs when the supply finishes, you can do so by setting the done and quit options in the call to tap:

    $supply.tap: { ... },
        done => { say 'Job is done.' },
        quit => {
            when X::MyApp::Error { say "App Error: ", $_.message }
        };

The quit block works very similar to a CATCH. If the exception is marked as seen by a when or default block, the exception is caught and handled. Otherwise, the exception continues to up the call tree (i.e., the same behavior as when quit is not set).

If you are using the react or supply block syntax with whenever, you can add phasers within your whenever blocks to handle the done and quit messages from the tapped supply:

    react {
        whenever $supply {
            ...; # your usual supply tap code here
            LAST { say 'Job is done.' }
            QUIT { when X::MyApp::Error { say "App Error: ", $_.message } }
        }
    }

The behavior here is the same as setting done and quit on tap.

## 8.1.3 Channels

A Channel is a thread-safe queue that can have multiple readers and writers that could be considered to be similar in operation to a "fifo" or named pipe except it does not enable inter-process communication. It should be noted that, being a true queue, each value sent to the Channel will only be available to a single reader on a first read, first served basis: if you want multiple readers to be able to receive every item sent you probably want to consider a Supply.

An item is queued onto the Channel with the method send, and the method receive removes an item from the queue and returns it, blocking until a new item is sent if the queue is empty:

    my $channel = Channel.new;
    $channel.send('Channel One');
    say $channel.receive;  # 'Channel One'

If the channel has been closed with the method close then any send will cause the exception X::Channel::SendOnClosed to be thrown, and a receive will throw a X::Channel::ReceiveOnClosed if there are no more items on the queue.

The method list returns all the items on the Channel and will block until further items are queued unless the channel is closed:

    my $channel = Channel.new;
    await (^10).map: -> $r {
        start {
            sleep $r;
            $channel.send($r);
        }
    }
    $channel.close;
    for $channel.list -> $r {
        say $r;
    }

There is also the non-blocking method poll which returns an available item from the channel or Nil if there is no item or the channel is closed, this does of course mean that the channel must be checked to determine whether it is closed:

    my $c = Channel.new;

    start {
        my $closed = $c.closed;
        loop {
            if $c.poll -> $item {
                say $item;
            }
            elsif $closed {
                last;
            }
        }
    }

    await (^10).map: -> $r {
        start {
            sleep $r;
            $c.send($r);
        }
    }
    $c.close;

The method closed returns a Promise that will be kept (and consequently will evaluate to True in a boolean context,) when the channel is closed.

Channels can be used in place of the Supply in the whenever of a react block described earlier:

    my $channel = Channel.new;
    my $p = start {
        react {
            whenever $channel {
                say $_;
            }
        }
    }

    await (^10).map: -> $r {
        start {
            sleep $r;
            $channel.send($r);
        }
    }

    $channel.close;
    await $p;

It is also possible to obtain a Channel from a Supply using the Supply method which returns a Channel which is fed by a tap on the Supply:

    my $supplier = Supplier.new;
    my $supply   = $supplier.Supply;
    my $channel = $supply.Channel;

    my $p = start {
        react  {
            whenever $channel -> $item {
                say "via Channel: $item";
            }
        }
    }

    await (^10).map: -> $r {
        start {
            sleep $r;
            $supplier.emit($r);
        }
    }

    $supplier.done;
    await $p;

Channel will return a different Channel fed with the same data each time it is called. This could be used, for instance, to fan-out a Supply to one or more Channels to provide for different interfaces in a program.

## 8.1.4 Proc::Async

Proc::Async builds on the facilities described to run and interact with an external program asynchronously:

    my $proc = Proc::Async.new('echo', 'foo', 'bar');

    $proc.stdout.tap(-> $v { print "Output: $v" });
    $proc.stderr.tap(-> $v { print "Error:  $v" });

    say "Starting...";
    my $promise = $proc.start;

    await $promise;
    say "Done.";

    # Output:
    # Starting...
    # Output: foo bar
    # Done.

The path to the command as well as any arguments to the command are supplied to the constructor. The command will not be executed until start is called, which will return a Promise that will be kept when the program exits. The standard output and standard error of the program are available as Supply objects from the methods stdout and stderr respectively which can be tapped as required.

If you want to write to the standard input of the program you can supply the :w adverb to the constructor and use the methods write, print or say to write to the opened pipe once the program has been started:

    my $proc = Proc::Async.new(:w, 'grep', 'foo');

    $proc.stdout.tap(-> $v { print "Output: $v" });

    say "Starting...";
    my $promise = $proc.start;

    $proc.say("this line has foo");
    $proc.say("this one doesn't");

    $proc.close-stdin;
    await $promise;
    say "Done.";

    # Output:
    # Starting...
    # Output: this line has foo
    # Done.

Some programs (such as grep without a file argument in this example, ) won't exit until their standard input is closed so close-stdin can be called when you are finished writing to allow the Promise returned by start to be kept.

# 8.2 Low-level APIs

## 8.2.1 Threads

The lowest level interface for concurrency is provided by Thread. A thread can be thought of as a piece of code that may eventually be run on a processor, the arrangement for which is made almost entirely by the virtual machine and/or operating system. Threads should be considered, for all intents, largely un-managed and their direct use should be avoided in user code.

A thread can either be created and then actually run later:

    my $thread = Thread.new(code => { for  1 .. 10  -> $v { say $v }});
    # ...
    $thread.run;

Or can be created and run at a single invocation:

    my $thread = Thread.start({ for  1 .. 10  -> $v { say $v }});

In both cases the completion of the code encapsulated by the Thread object can be waited on with the finish method which will block until the thread completes:

    $thread.finish;

Beyond that there are no further facilities for synchronization or resource sharing which is largely why it should be emphasised that threads are unlikely to be useful directly in user code.

## 8.2.2 Schedulers

The next level of the concurrency API is supplied by classes that implement the interface defined by the role Scheduler. The intent of the scheduler interface is to provide a mechanism to determine which resources to use to run a particular task and when to run it. The majority of the higher level concurrency APIs are built upon a scheduler and it may not be necessary for user code to use them at all, although some methods such as those found in Proc::Async, Promise and Supply allow you to explicitly supply a scheduler.

The current default global scheduler is available in the variable $*SCHEDULER.

The primary interface of a scheduler (indeed the only method required by the Scheduler interface) is the cue method:

    method cue(:&amp;code, Instant :$at, :$in, :$every, :$times = 1; :&amp;catch)

This will schedule the Callable in &code to be executed in the manner determined by the adverbs (as documented in Scheduler) using the execution scheme as implemented by the scheduler. For example:

    my $i = 0;
    my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );
    sleep 20;

Assuming that the $*SCHEDULER hasn't been changed from the default, will print the numbers 0 to 10 approximately (i.e with operating system scheduling tolerances) every two seconds. In this case the code will be scheduled to run until the program ends normally, however the method returns a Cancellation object which can be used to cancel the scheduled execution before normal completion:

    my $i = 0;
    my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );
    sleep 10;
    $cancellation.cancel;
    sleep 10;

should only output 0 to 5,

Despite the apparent advantage the Scheduler interface provides over that of Thread all of functionality is available through higher level interfaces and it shouldn't be necessary to use a scheduler directly, except perhaps in the cases mentioned above where a scheduler can be supplied explicitly to certain methods.

A library may wish to provide an alternative scheduler implementation if it has special requirements, for instance a UI library may want all code to be run within a single UI thread, or some custom priority mechanism may be required, however the implementations provided as standard and described below should suffice for most user code.

### 8.2.2.1 ThreadPoolScheduler

The ThreadPoolScheduler is the default scheduler, it maintains a pool of threads that are allocated on demand, creating new ones as necessary up to maximum number given as a parameter when the scheduler object was created (the default is 16.) If the maximum is exceeded then cue may queue the code until such time as a thread becomes available.

Rakudo allows the maximum number of threads allowed in the default scheduler to be set by the environment variable RAKUDO_MAX_THREADS at the time the program is started.

### 8.2.2.2 CurrentThreadScheduler

The CurrentThreadScheduler is a very simple scheduler that will always schedule code to be run straight away on the current thread. The implication is that cue on this scheduler will block until the code finishes execution, limiting its utility to certain special cases such as testing.

## 8.2.3 Locks

The class Lock provides the low level mechanism that protects shared data in a concurrent environment and is thus key to supporting thread-safety in the high level API, this is sometimes known as a "Mutex" in other programming languages. Because the higher level classes (Promise, Supply and Channel,) use a Lock where required it is unlikely that user code will need to use a Lock directly.

The primary interface to Lock is the method protect which ensures that a block of code (commonly called a "critical section",) is only executed in one thread at a time:

    my $lock = Lock.new;

    my $a = 0;

    await (^10).map: {
        start {
                $lock.protect({
                    my $r = rand;
                    sleep $r;
                    $a++;
                });
        }
    }

    say $a; # 10

protect returns whatever the code block returns.

Because protect will block any threads that are waiting to execute the critical section the code should be as quick as possible.

# 8.3 Safety Concerns

Some shared data concurrency issues are less obvious than others. For a good general write-up on this subject see this blog post.

One particular issue of note is when container autovivification or extension takes place. When an Array or a Hash entry is initially assigned the underlying structure is altered and that operation is not async safe. For example, in this code:

    my @array;
    my $slot := @array[20];
    $slot = 'foo';

The third line is the critical section as that is when the array is extended. The simplest fix is to use a <Lock> to protect the critical section . A possibly better fix would be to refactor the code so that sharing a container is not necessary.

# 9 Containers

A low-level explanation of Perl 6 containers

This article started as a conversation on IRC explaining the difference between the Array and the List type in Perl 6. It explains the levels of indirection involved in dealing with variables and container elements.

# 9.1 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 run time, 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.

# 9.2 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;         # 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;         # 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;       # Int
    say $x.VAR.^name;   # Scalar

And is rw on a parameter requires the presence of a writable Scalar container:

    sub f($x is rw) { say $x };
    f 42;   # Parameter '$x' expected a writable container, but got Int value

# 9.3 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:

    $ perl6 -e 'my $x := 42; $x = 23'
    Cannot modify an immutable value
       in block  at -e:1

You can also bind variables to other variables:

    my $a = 0;
    my $b = 0;
    $a := $b;
    $b = 42;
    say $a;         # 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 also bind by default and so do parameters with the trait is raw.

    my $a = 42;
    my \b = $a;
    b++;
    say $a;         # 43

    sub f($c is raw) { $c++ }
    f($a);
    say $a;         # 44

# 9.4 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;    # 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;                 # 23
    ($x, 1, 2)[1] = 23;     # Error: Cannot modify an immutable value

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, so 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;         # 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.

An Array also has methods that can change the number of elements, notably push, pop, shift, unshift and splice.

# 9.5 Assigning and binding to array variables

Assigning to a scalar variable and to an array variable both do basically 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;   # Int
    my @a = 42; say @a.^name;   # 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.WHAT;                # (List)

# 9.6 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;                     # 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 (you cannot expand the lexpad at run time).

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;    # This is not allowed and will fail.

Operations that mix Lists and Arrays generally protect against such a thing happening accidentally.

# 9.7 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

Contrary to earlier versions of Perl 6, and to Perl 5, @-sigiled variables do not flatten in list context:

    my @a = 1, 2, 3;
    my @b = @a, 4, 5;
    say @b.elems;               # 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;  # 5

    sub f(*@x) { @x.elems };
    say f @a, 4, 5;             # 5

As hinted above, scalar containers prevent that flattening:

    sub f(*@x) { @x.elems };
    say f $@a, 4, 5;            # 3

The @ character can also be used as a prefix to remove a scalar container:

    my $x = (1, 2, 3);
    .say for @$x;               # 3 iterations

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.

# 9.8 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 => '-Inf..12, 14..Inf').throw
                    if $new-value == 13;
                $c-value = $new-value;
            }
        );
    }

    my Int $a := lucky(Int);
    say $a = 12;
    say $a = 'FOO'; # X::TypeCheck::Binding
    say $a = 13; # X::OutOfRange

# 10 Contributors

List of contributors to Perl 6 over the years

The following people contributed to the development of Perl 6, as could be determined from the logs of all the various projects that make up Perl 6. If you think you are missing from this list, or for any reason would not like to appear on this list, or need a correction, please submit a Pull Request with the required change(s).

# 10.1 A

    Gisle Aas
    abcxyzp
    Chuck Adams
    Colin Paul Adams
    Rod Adams
    C.J. Adams-Collier
    David H. Adler
    Chirag Agrawal
    Amir E. Aharoni
    Bilal Akhtar
    Julian Albo
    Alekssasho
    alexghacker
    Paco Alguacil
    Brandon S Allbery
    Geir Amdal
    Markus Amsler
    Paul C. Anagnostopoulos
    Nikolay Ananiev
    anatolyv
    andras
    Saleem Ansari
    Joji Antony
    Tomoki Aonuma
    Syed Uzair Aqeel
    arathorn
    Arcterus
    Kodi Arfer
    Daniel Arbelo Arrocha
    ash
    Ted Ashton
    Arnaud Assad
    atroxaper
    Ori Avtalion אורי אבטליון
    Auzon

# 10.2 B

    Greg Bacon
    Ivan Baidakou
    Alex Balhatchet
    Szabó
    Balázs
    Amir Livine Bar-On עמיר ליבנה בר-און
    Luca Barbato
    Mattia Barbon
    Ann Barcomb
    Christian Bartolomäus
    Alex "Skud" Bayley
    bcmb
    Jody Belka
    Shachaf Ben-Kiki
    Andrei Benea
    benedikth
    Zev Benjamin
    benmorrow
    Kevan Benson
    Martin Berends
    Anton Berezin
    Arthur Bergman
    Anders Nor Berle
    bestian
    Peter Bevan
    Mark Biggar
    Carlin Bingham
    Ævar Arnfjörð Bjarmason
    J. David Blackstone
    Ronald Blaschke
    Ingo Blechschmidt
    bloonix
    blwood
    Kristof Bogaerts
    Dan Bolser
    Конрад Боровски
    Christopher Bottoms
    Gonéri Le Bouder
    Jos Boumans
    Brad Bowman
    Matt Boyle
    bpetering
    H.Merijn Brand
    Terrence Brannon
    Gwern Branwen
    Stig Brautaset
    Herbert "lichtkind" Breunung
    bri
    brian_d_foy
    Fernando Brito
    Geoffrey Broadwell
    Leon Brocard
    Benjamin Brodfuehrer
    Samuel Bronson
    Dan Brook
    Nathan C. Brown
    Roger Browne
    Philippe Bruhat (BooK)
    David Brunton
    Corwin Brust
    Klaus Brüssel
    Lucas Buchala
    buchetc
    Christoph Buchetmann
    Norbert Buchmuller
    Buddha Buck
    Alexandre Buisse
    Tim Bunce
    Bryan Burgers
    Sean M. Burke
    Matthew Byng-Maddick
    András Bártházi
    Jürgen Bömmels

# 10.3 C

    Caelum
    Aldo Calpini
    Edward Cant
    David Cantrell
    Carlin
    Michael Cartmell
    Hezekiah Carty
    Nuno 'smash' Carvalho
    Marcelo Serra Castilhos
    Piers Cawley
    cdavaz
    cdpruden
    Gianni Ceccarelli
    cfourier
    Marc Chantreux
    Mitchell N Charity
    Oliver Charles
    Vasily Chekalkin
    Yuan-Chen Cheng 鄭原真
    Daniel Chetlin
    Hsin-Chan Chien 簡信昌
    N. Hao Ching
    Joshua Choi
    Elizabeth Cholet
    David Christensen
    chuck
    cjeris
    Nicholas Clark
    Steve Clark
    Jeff Clites
    cmarcelo
    cmeyer
    Paul Cochrane
    Daniel Colascione
    Jason Cole
    Will "Coke" Coleda
    Sylvain Colinet
    cono
    Tim Conrow
    Géraud Continsouzas
    Damian Conway
    Neil Conway
    Stuart Cook
    David Corbin
    Deven T. Corzine
    cosmicnet
    Timothy Covell
    Beau E. Cox
    Simon Cozens
    Philip Crow
    cspenser
    Franck Cuny
    Tyler Curtis
    David Czech

# 10.4 D

    Daenyth
    Dagur
    Ritz Daniel
    darkwolf
    Chris Davaz
    David Warring
    Justin DeVuyst
    Daniel Dehennin
    Akim Demaille
    Detonite
    Lars "daxim" Dieckow 迪拉斯
    Matt Diephouse
    Bob Diertens
    Wendy "woolfy" van Dijk
    Jeffrey Dik
    John M. Dlugosz
    dimid
    diotalevi
    Hans van Dok
    Chris Dolan
    Mark Dominus
    Bryan Donlan
    Andy Dougherty
    Dave Doyle
    drKreso
    dr_df0
    dudley
    Jonathan Scott Duff
    dug
    Lee Duhem
    Darren Duncan

# 10.5 E

    Andrew Egeler
    Havard Eidnes
    Nelson Elhage
    Ran Eliam
    Fitz Elliott
    Alex Elsayed
    Jay Emerson
    Aankhola Encorporated
    ennio
    Enveigler
    Jon Ericson
    Shae Matijs Erisson
    Eryq
    Mike Eve
    Pat Eyler

# 10.6 F

    Aaron Faanes
    Kevin Falcone
    David Farrell
    Angel Faus
    Jason Felds
    Paul Fenwick
    Jose Rodrigo Fernandez
    Nelson Ferraz
    Adriano Ferreira
    João Fernando Ferreira
    Chris Fields
    Caio Marcelo de Oliveira Filho
    Steve Fink
    Shlomi "rindolf" Fish שלומי פיש
    Mark Leighton Fisher
    Scott Fitzenrider
    Dudley Flanders
    Richard Foley
    Vincent Foley
    Julian Fondren
    Ruben Fonseca
    David Formosa
    Karl Forner
    Solomon Foster
    Chaddaï Fouché
    Lloyd Fournier
    Michael Fowler
    Matt Fowles
    franck
    Austin Frank
    Carl Franks
    Kent Fredric
    Chaim Frenkel
    Piotr Fusik

# 10.7 G

    gabriele
    John Gabriele
    Christoph Gärtner
    Martin von Gagern
    Felix Gallo
    Salvador Ortiz Garcia
    Rafaël Garcia-Suarez
    Joshua Gatcomb
    Jerry Gay
    gcomnz
    Jonathan Gentle
    iVAN Georgiev
    Brian Gernhardt
    Bram Geron
    Alessandro Ghedini
    Imran Ghory
    Peter Gibbs
    Tanton Gibbs
    Brad Gilbert (b2gills)
    Karl Glazebrook
    Nick Glencross
    Mark Glines
    Flávio S. Glock
    Jason Gloudon
    Simon Glover
    gnuvince
    Garrett Goebel
    Jeffrey Goff
    Mikhael Goikhman
    Benjamin Goldberg
    Arcady Goldmints-Orlov
    Dimitry Golubovsky
    Gerard Goossen
    Goplat
    Alex Gough
    Léo Grange
    Chad "Exodist" Granum
    Kenneth A Graves
    Bruce Gray
    Nathan Gray
    Mark Grimes
    Lucien Grondin
    Rolf Grossmann
    David Grove
    Marcel Grünauer
    Daniel Grunblatt
    Uri Guttman
    gwern

# 10.8 H

    Swaroop C H
    Richard Hainsworth
    Roger Hale
    John "ab5tract" Haltiwanger
    Nigel Hamilton
    Eric Hanchrow
    Sterling Hanenkamp
    Ask Bjørn Hansen
    Christian "chansen" Hansen
    Eirik Berg Hanssen
    Samuel Harrington
    Trey Harris
    John Harrison
    Carsten Hartenfels
    Richard Hartmann
    Kyle Hasselbacher
    Austin Hastings
    Carl Hayter
    Florian Helmberger
    Gordon Henriksen
    Felix Herrmann
    Peter Heslin
    Fred Heutte
    Jarkko Hietaniemi
    Michael H. Hind
    Joshua Hoblitt
    Zack Hobson
    Eric Hodges
    Rob Hoelz
    Masahiro Honma
    Lyle Hopkins
    JD Horelick
    Jeff Horwitz
    Chris Hostetter
    Laurens Van Houtven
    Jeremy Howard
    Yiyi Hu 鹄驿懿
    Benedikt Huber
    Brad Hughes
    Sterling Hughes
    Tom Hughes
    Tristan Hume
    Donald Hunter
    Douglas Hunter
    Juan Francisco Cantero Hurtado
    Kay-Uwe 'kiwi' Hüll

# 10.9 I

    Alin Iacob
    Ibotty
    ibrown
    ihrd
    Roland Illing
    Jan Ingvoldstad
    Joshua Isom
    isop
    Ivan_A_Frey
    ivanoff

# 10.10 J

    Akash Manohar J
    jafelds
    Robert G. Jakabosky
    jamesrom
    S. A. Janet
    jani
    Heiko Jansen
    Stuart Jansen
    Jarrod
    Jedai
    Chris Jepeway
    Chris Jeris
    Dagur Valberg Johannsson
    Erik Johansen
    Paul Johnson
    johnspurr
    Isaac Jones
    Norman Nunley Jr
    Yoshikuni Jujo
    Brian S. Julin
    Josh Juran
    Michal Jurosz

# 10.11 K

    David Koenig
    Prakash Kailasa
    Shoichi Kaji
    Daniel Kang
    Isis Kang
    Chia-Liang Kao 高嘉良
    Dmitry Karasik
    Luben Karavelov
    Amir Karger
    Offer Kaye
    Bruce Keeler
    James E Keenan
    Cole Keirsey
    Adam Kennedy
    Matt Kennedy
    Shane Kerr
    khairul
    Mikhail Khorkov
    Krzysztof Kielak
    Andres Kievsky
    Daehyub Kim
    Rob Kinyon
    Oleg Kiselyov
    Oolley kj
    Martin Kjeldsen
    Thomas "domm" Klausner
    Zohar "lumi" Kelrich זהר קלריך/卡卓哈
    Damian Miles Knopp
    Dan Kogai 小飼弾
    Yuval "nothingmuch" Kogman יובל קוג'מן
    Tomasz Konojacki
    Vadim Konovalov
    Nick Kostirya
    Matt Kraai
    Thomas Kratz
    Adrian Kreher
    John van Krieken
    Matthias Krull
    Bradley M. Kuhn
    Bob Kuo
    Colin Kuskie
    Kamil Kułaga

# 10.12 L

    Sage LaTorra
    Brent Laabs
    laben
    Johannes Laire
    Markus Laire
    Fayland Lam 林道
    Mike Lambert
    lanny
    Leo Lapworth
    last.of.the.careless.men
    Bart Lateur
    Jia-Hong Lee
    Lola Lee
    Jonathan Leffler
    Tobias Leich
    lembark
    Mark Lentczner
    Moritz A Lenz
    Jean-Louis Leroy
    Andy Lester
    Jonathan "Duke" Leto
    Vladimir Lettiev
    Mike Li 李曉光
    Stefan Lidman
    Yung-Chung Lin 林永忠
    Glenn Linderman
    Vladimir Lipsky
    Zach Lipton
    Stevan Little
    Kang-Min Liu 劉康民
    Skip Livingston
    David M. Lloyd
    Daniel Lo
    Peter Lobsinger
    Andres Löh
    Nick Logan
    Eric Lubow
    Nolan Lum
    Peter Lunicks
    LylePerl
    Ian Lynagh
    lysdexsik

# 10.13 M

    Kiran Kumar M.
    Jerry MacClure
    Noel Maddy
    Christopher J. Madsen
    Abhijit A. Mahabal
    Max Maischein
    Peter Makholm
    Ujwal Reddy Malipeddi
    malon
    Christopher Malon
    Dagfinn Ilmari Mannsåker
    Michael Maraist
    Roie Marianer רועי מריאנר
    markmont
    Simon Marlow
    martin
    Paolo Martini
    Ilya Martynov
    Jaume Martí
    James Mastros
    Michael J. Mathews
    Vyacheslav Matjukhin
    Tokuhiro Matsuno
    mattc
    Mike Mattie
    Elizabeth "lizmat" Mattijsen
    Вячеслав Матюхин
    Markus Mayr
    Josh McAdams
    Martin McCarthy
    Mark McConnell
    Steven McDougall
    John McNamara
    Scott McWhirter
    mdinger
    Olivier "dolmen" Mengué
    Kevin Metcalf
    Patrick R. Michaud
    mimir
    mjreed
    Tom Moertel
    Michael Mol
    Paolo Molaro
    Shawn M Moore
    Brandon Michael Moore
    Alexander Moquin
    Ion Alexandru Morega
    Dino Morelli
    Kolia Morev
    Zach Morgan
    mr_ank
    Alex Munroe
    muraiki
    Paweł Murias
    mvuets
    Steve Mynott
    mzedeler
    Carl Mäsak

# 10.14 N

    naesten
    Tim Nelson
    Ailin Nemui
    Ingy döt Net 應吉大聶
    David Nicol
    Faye Niemeyer
    Nigelsandever
    Karl Rune Nilsen
    Salve J. Nilsen
    Per Christian Nodtvedt
    Ben Noordhuis
    Paweł Nowak
    Norman Nunley

# 10.15 O

    Tony O'Dell
    יהושע "שי" אוחיון
    Clayton O'Neill
    Stefan O'Rear
    Sean O'Rourke
    Matt Oates
    Tony Olekshy
    Martin Olsen
    Dmitriy Olshevskiy
    Dave Olszewski
    Nelo Onyiah
    William Orr
    Jon Orwant
    Andrei Osipov
    Christoph Otto

# 10.16 P

    Pawel Pabian
    Walter Pallestrong
    Luke Palmer
    Bartłomiej Palmowski
    Pancake
    Paolo
    Marton Papp
    Andrew Parker
    Roman M. Parparov
    Anthony Parsons
    Mike Pastore
    Nova Patch
    Timo Paulssen
    Tony Payne
    Stéphane "cognominal" Payrard
    Slava Pechenin
    Gael Pegliasco
    Stéphane Peiry
    Felipe Pena
    Nayden Pendov
    Wenzel P. P. Peppmeyer
    François Perrad
    Markus Peter
    Ben Petering
    Steve Peters
    Tim Peterson
    Ronny Pfannschmidt
    Clinton A. Pierce
    Jerrad Pierce
    Thilo Planz
    plunix
    pmakholm
    Curtis 'Ovid' Poe
    Gerd Pokorra
    Peter Polacik
    Flavio Poletti
    Kevin Polulak
    John Porter
    Ryan W. Porter
    Stephen P. Potter
    Philip Potter
    Adam Preble
    premshree
    Klāvs Priedītis
    Adam Prime
    Richard Proctor
    Christopher Pruden
    Kevin Puetz
    Gregor N. Purdy
    purl

# 10.17 Q

    Hongwen Qiu
    Jerome Quelin
    quester

# 10.18 R

    Gerhard R.
    Peter Rabbitson
    Florian Ragwitz
    raiph
    Matt Rajca
    Marcus Ramberg
    Claudio Ramirez
    Prog Rammer
    Allison Randal
    David Ranvig
    Lars Balker Rasmussen
    Curtis Rawls
    raydiak
    Robin Redeker
    Ted Reed
    Jens Rehsack
    Charles Reiss
    Gabriele Renzi
    Kenneth C. Rich
    Jason Richmond
    Ryan Richter
    Sebastian Riedel
    Dennis Rieks
    Jens Rieks
    Lanny Ripple
    John Rizzo
    rkhill
    Andrew Robbins
    Amos Robinson
    Jonathan Rockway
    Stefano Rodighiero
    Andrew Rodland
    Lindolfo Rodrigues
    Bob Rogers
    Dave Rolsky
    David Romano
    ron
    Eric J. Roode
    Garret Rooney
    Garrett Rooney
    David Ross
    Andreas Rottmann
    Brent Royal-Gordon
    Shmarya Rubenstein
    Sam Ruby
    Simon Ruderich
    Daniel Ruoso
    Jake Russo
    ruz
    Joseph Ryan
    Gilbert Röhrbein

# 10.19 S

    Sam S
    s1n
    sahadev
    Patrick Abi Salloum
    salty_horse
    Chip Salzenberg
    Shrivatsan Sampathkumar
    Igor Rafael Sanchez-Puls
    Hugo van der Sanden
    Thomas Sandlaß
    Yun SangHo
    sanug
    Siddhant Saraf
    Sasho
    Andrew Savige
    John Saylor
    Matt Schallert
    Bernhard Schmalhofer
    Arthur Axel Schmidt
    Ronald Schmidt
    Michael Schroeder
    Steven Schubiger
    Steve "thundergnat" Schulze
    Andreas Schwab
    Randal L. Schwartz
    Pepe Schwarz
    Frederik Schwarzer
    Calvin Schwenzfeier
    Michael G. Schwern
    Steffen Schwigon
    Tom Scola
    Ariel Scolnicov
    Michael Scott
    Peter Scott
    Rick Scott
    Stefan Seifert
    Austin Seipp
    Mark Senn
    Filip Sergot
    Seth Gold (Sgeo)
    William Shallum
    Kris Shannon
    shenyute
    Aaron Sherman
    Mark Shoulson
    Ryan Siemens
    Ricardo Signes
    Hinrik Örn Sigurðsson
    Jonathan Sillito
    Miroslav Silovic
    Steve Simmons
    Alberto Manuel Brandao Simoes
    John Siracusa
    Arne Skjærholt
    Barrie Slaymaker
    Radek Slupik
    Mike Small
    Benjamin Smith
    Melvin Smith
    Tim Smith
    Adrian White aka
    snarkyboojum
    Richard Soderberg
    SolidState
    Vishal Soni
    Syloke Soong
    Shawn Sorichetti
    Tadeusz Sośnierz
    sue spence
    Cory Spencer
    Robert Spier
    Michael Stapelberg
    Edwin Steiner
    stephenpollei
    Michael Stevens
    Don Stewart
    Radu Stoica
    Klaas-Jan Stol
    Alek Storm
    David Storrs
    Mark Stosberg
    Jonathan Stowe
    Cosimo Streppone
    Jonathan Strickland
    Pascal Stumpf
    Su-Shee
    Sue
    Laye Suen
    Dan Sugalski
    Mark Summerfield
    Simon Sun
    Cheng-Lung Sung 宋政隆
    Sunnavy
    Samuel Sutch
    svatsan
    svn
    Andrew Sweger
    sygi
    Sebastian Sylvan
    Gábor Szabó
    Bálint Szilakszi
    Marek Šuppa

# 10.20 T

    TOGoS
    Arvindh Rajesh Tamilmani
    Audrey Tang 唐鳳
    Bestian Tang 唐宗浩
    Adrian Taylor
    Jesse Taylor
    Philip Taylor
    Kevin Tew
    the_dormant
    Marcus Thiesen
    Adam Thomason
    Richard Tibbetts
    Carey Tilden
    Marcel Timmerman
    Leon Timmermans
    tkob
    John Tobey
    Frank Tobin
    Bennett Todd
    Graham Todd
    Leopold Tötsch
    Daniel Toma
    Nathan Torkington
    Timothy Totten
    Itsuki Toyota
    John J. Trammell
    Matt S. Trout
    Nat Tuck
    Adam Turoff
    Ben Tyler

# 10.21 U

    ujwal
    Bernd Ulmann
    Reini Urban
    parrot user
    uzair

# 10.22 V

    VZ
    Ilmari Vacklin
    vamped
    Wim Vanderbauwhede
    vendethiel
    David Vergin
    Ted Vessenes
    Sam Vilain
    Cédric Vincent
    Jesse Vincent
    Jos Visser
    John van Vlaanderen
    vmax
    Jeremy Voorhis
    Martin Vorländer
    Johan Vromans
    Maxim Vuets

# 10.23 W

    Juerd Waalboer
    Mariano Wahlmann
    Kevin Walker
    Gloria Wall
    Larry Wall
    Lewis Wall
    Michal J Wallace
    John Paul Wallington
    walter
    Matthew Walton
    Ting Wang
    Xinyuan Wang
    Andy Wardley
    Bryan C. Warnock
    wayland
    Stephen Weeks
    Zhen-Bang Wei
    Nick Wellnhofer
    Shu-Chun Weng
    Danny Werner
    Brian Wheeler
    David E. Wheeler
    Dave Whipp
    Adrian White
    Andrew Whitworth
    Bart Wiegmans
    Nathan Wiger
    Brock Wilcox
    Edwin Wiles
    Bob Wilkinson
    Chris 'BinGOs' Williams
    Greg Williams
    Josh Wilmes
    Matthew Wilson
    Ashley Winters
    Brian Wisti
    Dave Woldrich
    Helmut Wollmersdorfer
    Kevin J. Woolley
    Jonathan Worthington
    Kuang-Che Wu 吳光哲

# 10.24 X

    xenu
    Liang-Qi Xie 謝良奇
    Xtreak

# 10.25 Y

    Gaal Yahas גל יחס
    Thomas Yandell
    Alvis Yardley
    Thomas Yeh 葉志宏
    Natan Yellin
    yiyihu
    Matt Youell
    Tony Young
    Shen Yu-Teh

# 10.26 Z

    Ilya Zakharevich
    Ruslan Zakirov
    Ahmad M. Zawawi
    Michael A. D. Zedeler
    zengargoyle
    zeriod
    Agent Zhang 章亦春
    Jimmy Zhuo
    Ziggy6
    Rob Zinkov
    Zoffix Znet

# 11 Control Flow

Statements used to control the flow of execution

# 11.1 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";

# 11.2 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;                    # says "1"
    { say 2; say 3 };         # says "2" then says "3"
    say 4;                    # says "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 }                #-> says "42"
    { 43.say }                #-> says "43"
    { 42.say }; { 43.say }    #-> says "42" then says "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.

# 11.3 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 }  ; #-> 3, 2
    3,   (if 1 { 2 }) ; #-> 3, 2
    3,    if 1 { 2 }  ; # Syntax error

...which brings us to if.

# 11.4 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"

## 11.4.1 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" }    ; # syntax error, space is 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"

## 11.4.2 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)"

## 11.4.3 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:

    without $answer { fail "Got: $_" }

There are also with and without statement modifiers:

    return 42 with $answer;
    .throw without $answer;

# 11.5 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.

    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.

    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.

    for @foo.kv -> $idx, $val { say "$idx: $val" }
     for %hash.kv -> $key, $val { say "$key => $val" }
     for 1, 1.1, 2, 2.1 { say "$^x &lt; $^y" }  # says "1 &lt; 1.1" then says "2 &lt; 2.1"

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 {...}

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.

    for @cars &lt;-> $_ {...}

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;              # says "(2 4 6)"
     my @a = do for 1, 2, 3 { $_ * 2 }; @a.say; # says "[2 4 6]"
     my @a = (for 1, 2, 3 { $_ * 2 }); @a.say;  # same thing

# 11.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;          # 1, 5, 42

gather/take generates values lazily, so the gather block generally runs only until it hits the first take. Code after the first take is executed as soon as the next value is consumed from the returned sequence.

For example

    my \vals = gather {
        take 1;
        say "Produced a value";
        take 2;
    }
    say vals[0];
    say 'between consumption of two values';
    say vals[1];

produces this 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(&lt;a b c>, :direction&lt;backward> );          # (c b a)

# 11.7 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:

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

The given statement is often used alone:

    given EXPR { .say; .Numeric; }

This is a lot more understandable than:

    { .say; .Numeric; }(EXPR)

## 11.7.1 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 {
        when Int { .say }
        default  { say "Not an Int" }
    }
    #-> 42 43 Not an Int 44

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?" }
    }
    #-> 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?" }
    }
    #-> 42

when statements can smart match against Signatures.

## 11.7.2 proceed and 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.

    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?" }
    }
    # -> Int
    # -> 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 }
    }
    #-> Int
    #-> 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 shortcircuits 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?" }
    }
    #-> 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;
    }

## 11.7.3 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",
            &lt;Mo Tu We Th Fr Sa Su>[.day-of-week],
            .day,
            .month,
            .year
        given DateTime.now;
    # OUTPUT«Sa 03.06.2016»

# 11.8 loop

The loop statement is the C-style for loop in disguise:

    loop (my $i = 0; $i &lt; 10; $i++) {
        ...
    }

As in C, the parentheses are required if you supply the 3-part spec; however, the 3-part loop spec may be entirely omitted to write an infinite loop. That is,

    loop {...}

is equivalent to the C-ish idiom:

    loop (;;) {...}

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++ &lt; 3;) { $i * 2 }).say;               #-> "(2 4 6)"
    my @a = (loop ( my $i = 0; $i++ &lt; 3;) { $i * 2 }); @a.say;   #-> "[2 4 6]"
    my @a = do loop ( my $i = 0; $i++ &lt; 3;) { $i * 2 }); @a.say; # same thing

Unlike a for loop, one should not rely on whether returned values are produced lazily, for now. 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 &lt; 1;) { "heads".say })
    }

# 11.9 while, until

The while statement executes the block as long as its condition is true. So

    my $x = 1;
     while $x &lt; 4 {
     print $x++;
     }
     print "\n";

produces

    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";

again produces

    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.

    $x++ while $x &lt; 12

Also see repeat/while and repeat/until below.

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

# 11.10 repeat/while, repeat/until

Executes the block at least once and, if the condition allows, repeats that execution.

    repeat {
        # Execute this block. Then, execute it again and again, until $x >= 10
    } while $x &lt; 10;

    repeat {
        # Execute this block. Then, execute it again and again, while $x &lt; 10
    } until $x >= 10;

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

# 11.11 return

The routine return will stop execution of a subroutine or method, run all relevant phasers and provide the given return value to the caller. The default return value is Nil. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

TODO add link to section in /language/function that shows how return values are produces/handled

# 11.12 return-rw

The routine return will return values, not containers. Those are immutable and will lead to runtime errors when attempted to be mutated.

    sub s(){ my $a = 41; return $a };
    say ++s();
    CATCH { dd $_ };
    # OUTPUT«X::Multi::NoMatch.new(dispatcher …

To return a mutable container, use return-rw.

    sub s(){ my $a = 41; return-rw $a };
    say ++s();
    # OUTPUT«42␤»

The same rules as for return reguarding phasers and control exceptions apply.

# 11.13 fail

Leaves the current routine and returns the provided Exception or Str wrapped inside a Failure, after all relevant phasers are executed.

    sub f { fail "WELP!" };
    dd f;
    # OUTPUT«Failure.new(exception => X::AdHoc.new(payload => "wut?"),
    # backtrace => Backtrace.new)␤»

# 11.14 once

A block prefix with once will be executed exactly once, even if placed inside a loop or a recursive routine.

    my $guard = 3;
    loop {
        last if $guard-- &lt;= 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.

# 11.15 quietly

A quietly block will suppress warnings.

    quietly { warn 'kaput!' };
    warn 'still kaput!';
    OUTPUT«still kaput! [...]␤»

# 11.16 LABELs

while, until, 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 lines() -> $line {
            last OUTAHERE if $line ~~ /^$/;
        }
    }

# 11.17 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".

# 11.18 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".

# 11.19 redo

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

    {
         my $x = prompt("Enter a number");
         redo unless is_a_number($x)
     }

# 11.20 samewith

The samewith allows one to call a multisub of the same name as the current sub.

    multi indent-say ( 'test' )
     {
         samewith 'ABCD';
     }

     multi indent-say ( Str $string )
     {
         say "\t$string";
     }

# 12 Exceptions

Using exceptions in Perl 6

Exceptions in Perl 6 are a special kind of object used to signify when something has gone wrong, for instance, unexpected data was received, a network connection is no longer available, or a file is missing which was expected to exist.

All built-in exceptions inherit from Exception, which provides some basic behavior, such as storing a backtrace and providing an interface for the backtrace printer.

# 12.1 Ad-hoc exceptions

Ad-hoc exceptions work just like in traditional Perl 5, one can simply use die with a message as to what went wrong:

    die "oops, something went wrong";
    #!> oops, something went wrong in block &lt;unit> at /tmp/0IeSX_XSWO:1

# 12.2 Typed exceptions

Typed exceptions provide more information about the kind of error that occurred within the exception object itself. For instance, if while executing .zombie copy on an object the path foo/bar is unavailable (and was expected to be available), then one could raise an X::IO::DoesNotExist exception like so:

    die X::IO::DoesNotExist.new(:path("foo/bar"), :trying("zombie copy"))
    #!> Failed to find 'foo/bar' while trying to do '.zombie copy'
    #!> in block &lt;unit> at /tmp/BgTfZOotgc:1

Note how the object has provided the backtrace with information about what went wrong so that hopefully the user of the code can find and correct the issue more easily.

# 12.3 Catching exceptions

It is 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 { say "some kind of IO exception was caught!" }
    }
    #!> 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 displayed.

A CATCH block uses smart matching similarly to how given/when smart matches on options, thus it is possible to catch various categories of exceptions and handle them appropriately inside a when block.

To handle all exceptions use a default statement.

    CATCH {
         default {
             say .WHAT.perl, do given .backtrace[0] { .file, .line, .subname }
         }
    }

# 12.4 try blocks

To contain an exception use a try block. 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 exception not handled will be rethrown.

    class E is Exception { method message() { "Just stop already!" } }

    try {
        E.throw.new; # 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!";
    }

Output:

    I'm alive!
    No, I expect you to DIE Mr. Bond!
    I'm immortal.
    Just stop already!
      in block &lt;unit> at exception.p6 line 21

A try-block is a normal block and as such treats it's last statement as the return value of itself. We can therefore use it as a RHS.

    say try { +"99999" } // "oh no"
    say try { +"hello" } // "oh no"
    # OUTPUT«99999␤oh no␤»

# 12.5 Throwing exceptions

One can also explicitly throw exceptions via the .throw method on 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&lt;foo>).throw;
        "OHAI".say;
        CATCH {
            when X::AdHoc { .resume }
        }
    }
    "OBAI".say;
    #-> 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&lt;foo>).throw;
        "OHAI".say;
        CATCH {  }
    }
    "OBAI".say;
    #!> foo
    #!> in block &lt;unit> at /tmp/FbtB60dxVO:1

This example doesn't resume from the point of the exception, however it continues after the enclosing block, since the exception was caught, and control continues after the CATCH block.

    {
        X::AdHoc.new(:payload&lt;foo>).throw;
        "OHAI".say;
        CATCH {
            when X::AdHoc { }
        }
    }
    "OBAI".say;
    #-> 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.

# 12.6 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

# 12.7 Uncaught Exceptions

If an exception is thrown and not caught, it causes the program to exit with a non-zero status code, and typically prints a message to the standard error stream of the program. This message is obtained by calling the gist method on the exception object. You can use this to suppress the default behavior of printing a backtrace along with the message:

    class X::WithoutLineNumber is X::AdHoc {
        multi method gist(X::WithoutLineNumber:D:) {
                $.payload
        }
    }
    die X::WithoutLineNumber.new(payload => "message")
        # prints "message\n" to $*ERR and exits, no backtrace

# 13 FAQ

Frequently Asked Questions about Perl 6

# 13.1 General

## 13.1.1 What's the difference between Rakudo and Perl 6?

Rakudo is an implementation of Perl 6. It's currently the most developed, but there have been other implementations in the past and should be others in the future. Perl 6 is the definition of the language. Many times the two names will be used loosely and interchangeably.

## 13.1.2 Is there going to be a Perl 6 version 6.0.0?

The version of the first stable language version is called v6.c, not 6.0.0. The different naming scheme makes it unlikely that there'll ever be a release of the language with the exact version 6.0.0.

It was first implemented by the Rakudo Perl 6 compiler version 2015.12 and is likely to be supported by subsequent releases for the foreseeable future by use of the 'use 6.c' pragma..

## 13.1.3 As a Perl 6 beginner what should I install?

Linux or Mac users probably want to download Rakudo Star and install via compilation (a simple process) the MoarVM based version available from http://rakudo.org/downloads/star/.

Compilation needs a C compiler and Perl 5 installed.

Or there is an official rakudo star docker image at https://hub.docker.com/_/rakudo-star/

If you are a Windows 32 or 64 bit user then Rakudo Star binaries are also available at the rakudo site. You will need Windows Git to use panda.

To use panda (see below) to install library modules you will need git and Perl 5's Test::Harness.

There should be Linux and Mac binaries available shortly from vendors and third parties. Although vendor versions may be outdated.

## 13.1.4 As an intermediate to advanced user I want to track Rakudo development.

Install rakudobrew which resembles Perl 5's perlbrew and the equivalent Python and Ruby tools.

## 13.1.5 Where can I find good documentation on Perl 6?

The most reliable information is to be found either under the perl6.org domains or directly linked from it.

https://www.perl6.org/documentation/ with https://docs.perl6.org/ as the canonical technical reference.

There is much good recent material on YouTube but be careful to check any dates on webpages since much of the Perl 6 information on random websites found by Google is often outdated.

You could also try searching the Freenode #perl6 IRC channel log via Google

## 13.1.6 What is the Perl 6 spec?

The "spec" refers to the official test suite for Perl 6. It's called roast and hosted on github. It is the measure of how complete a Perl 6 implementation is.

## 13.1.7 Is there a glossary of Perl 6 related terms?

Yes, see glossary.

## 13.1.8 I'm a Perl 5 programmer. Where is a list of differences between Perl 5 and 6?

See the pod with the 5to6- prefix under https://docs.perl6.org/language.html

# 13.2 Modules

## 13.2.1 Is there a CPAN for Perl 6?

There isn't yet a module repository for Perl 6 as sophisticated as CPAN. But modules.perl6.org has a list of known Perl 6 modules called the "ecosystem" hosted on github, and panda can install those that work with rakudo.

Support for installing Perl 6 modules from the Perl 5 CPAN is on its way.

## 13.2.2 Can I use Perl 5 modules from Perl 6?

Yes, with Inline::Perl5, which works well with most Perl 5 modules. It can even run Perl 5 Catalyst and DBI.

## 13.2.3 Can I use C and C++ from Perl 6?

Nativecall makes this particularly easy.

## 13.2.4 Nativecall can't find libfoo.so and I only have libfoo.so.1.2!

This is commonly seen on Debian-like systems. You need to install "libfoo-dev" to set a sym link for the missing file.

## 13.2.5 Where have all the traditional UNIX library functions gone?

It's very easy to use Nativecall to access them.

A ecosystem module POSIX is also available.

## 13.2.6 Does Rakudo have a core standard library?

Rakudo is a compiler release with minimal batteries included (Test and Nativecall etc.) rather like the linux kernel itself.

Rakudo Star is a distribution of rakudo which ships with some useful modules and many more can be installed from the ecosystem.

## 13.2.7 Is there something like B::Deparse/how can I get hold of the AST?

Use perl6 --target=ast -e 'very-short-example()' to get hold of the AST of a compilation unit.

# 13.3 Language Features

## 13.3.1 How can I dump Perl 6 data structures (like Perl 5 Data::Dumper and similar)?

Examples:

    my $foo="bar"
    dd $foo # Str $foo = "bar"
    say :$foo.perl # :foo("bar")
    say :$foo.gist # foo => bar

There are also modules in the ecosystem to do this, like Data::Dump, which uses color.

## 13.3.2 How can I get command line history in the Perl 6 prompt (REPL)?

Install Linenoise from the ecosystem.

An alternative on UNIX like systems is to install rlwrap. This can be done on Debian-ish systems by "apt-get install rlwrap".

## 13.3.3 Why is the Rakudo compiler sometimes more apologetic?

If SORRY! is present in the output the error is a compile time error otherwise it's runtime.

Example:

    say 1/0 # Attempt to divide 1 by zero using div

    sub foo( Int $a, Int $b ) {...}
    foo(1) # ===SORRY!=== Error while compiling ...

## 13.3.4 What is (Any)?

Any is a top level class used as a default superclass for new classes. It is often seen in a context where a variable has been defined but not assigned where it loosely resembles the undef or null values in other languages.

Example:

    my $foo
    say $foo # (Any) note the parens indicate type object
    say $foo.^name # Any

(Any) shouldn't be used to check for definedness. In Perl 6, definedness is a property of an object. Usually instances are defined and type objects are undefined.

    say 1.defined # True
    say (Any).defined # False

## 13.3.5 What is so?

so is a loose precedence operator that coerces to Bool.

It has the same semantics as the ? prefix operator, just like and is the low-precedence version of &&.

Example usage:

    say so 1|2 == 2;    # Bool::True

In this example, the result of the comparison (which is a Junction), is converted to Bool before being printed.

## 13.3.6 What are those :D and :U things in signatures?

In Perl 6, classes and other types are objects, and pass type checks of their own type.

For example if you declare a variable

    my Int $x = 42;

then not only can you assign integers (that is, instances of class Int) to it, but the Int type object itself:

    $x = Int

If you want to exclude type objects, you can append the :D type smiley, which stands for "definite":

    my Int:D $x = 42;
    $x = Int;   # dies with:
                # Type check failed in assignment to $x;
                # expected Int:D but got Int

Likewise :U constrains to undefined values, that is, type objects.

To explicitly allow either type objects or instances, you can use :_.

## 13.3.7 What is the --> thing in the signature?

--> is a return constraint, either a type or a definite value.

Example of a type constraint:

    sub divide-to-int( Int $a, Int $b --> Int ) {
            return ($a / $b).narrow;
    }

    divide-to-int(3, 2)
    # Type check failed for return value; expected Int but got Rat

Example of a definite return value:

    sub discard-random-number( --> 42 ) { rand }
    say discard-random-number
    # 42

In this case the final value is thrown away because the return value is already specified.

## 13.3.8 How can I extract the values from a Junction?

If you want to extract the values (eigenstates) from a Junction, you are probably doing something wrong, and should be using a Set instead.

Junctions are meant as matchers, not for doing algebra with them.

If you want to do it anyway, you can abuse autothreading for that:

    sub eigenstates(Mu $j) {
        my @states;
        -> Any $s { @states.push: $s }.($j);
        @states;
    }

    say eigenstates(1|2|3).join(', ');
    # prints 1, 2, 3 or a permutation thereof

## 13.3.9 If Str is immutable, how does s/// work? if Int is immutable, how does $i++ work?

In Perl 6, values of many basic types are immutable, but the variables holding them are not. The s/// operator works on a variable, into which it puts a newly created string object. Likewise $i++ works on the $i variable, not just on the value in it.

See the documentation on containers for more information.

## 13.3.10 What's up with array references and automatic dereferencing? Do I still need the @ sigil?

In Perl 6, nearly everything is a reference, so talking about taking references doesn't make much sense. Unlike Perl 5, scalar variables can also contain arrays directly:

    my @a = 1, 2, 3;
    say @a;                 # "1 2 3\n"
    say @a.WHAT;            # (Array)

    my $scalar = @a;
    say $scalar;            # "1 2 3\n"
    say $scalar.WHAT;       # (Array)

The big difference is that arrays inside a scalar act as one value in list context, whereas arrays will be happily iterated over.

    my @a = 1, 2, 3;
    my $s = @a;

    for @a { ... }          # loop body executed 3 times
    for $s { ... }          # loop body executed only once

    my @flat = flat @a, @a;
    say @flat.elems;        # 6

    my @nested = flat $s, $s;
    say @nested.elems;      # 2

You can force flattening with @( ... ) or by calling the .list method on an expression, and item context (not flattening) with $( ... ) or by calling the .item method on an expression.

## 13.3.11 Why sigils? Couldn't you do without them?

There are several reasons:

- they make it easy to interpolate variables into strings

- they form micro-namespaces for different variables and twigils, thus avoiding name clashes

- they allow easy single/plural distinction

- they work like natural languages that use mandatory noun markers, so our brains are built to handle it

- they aren't mandatory, since you can declare sigilless names (if you don't mind the ambiguity)

## 13.3.12 "Type Str does not support associative indexing."

You likely tried to mix string interpolation and HTML.

    my $foo = "abc";
    say "$foo&lt;html-tag>";

Perl 6 thinks $foo to be a Hash and <html-tag> to be a string literal hash key. Use a closure to help it to understand you.

    my $foo = "abc";
    say "{$foo}&lt;html-tag>";

## 13.3.13 Does Perl 6 have coroutines? What about yield?

Perl 6 has no yield statement like python does, but it does offer similar functionality through lazy lists. There are two popular ways to write routines that return lazy lists:

    # first method, gather/take
    my @values = gather while have_data() {
        # do some computations
        take some_data();
        # do more computations
    }

    # second method, use .map or similar method
    # on a lazy list
    my @squares = (1..*).map(-> \x { x² });

## 13.3.14 Why can't I initialize private attributes from the new method, and how can I fix this?

Code like

    class A {
        has $!x;
        method show-x {
            say $!x;
        }
    }
    A.new(x => 5).show-x;

does not print 5. Private attributes are private, which means invisible to the outside. If the default constructor could initialize them, they would leak into the public API.

If you still want it to work, you can add a submethod BUILD that initializes them:

    class B {
        has $!x;
        submethod BUILD(:$!x) { }
        method show-x {
            say $!x;
        }
    }
    A.new(x => 5).show-x;

BUILD is called by the default constructor (indirectly, see Object Construction for more details) with all the named arguments that the user passes to the constructor. :$!x is a named parameter with name x, and when called with a named argument of name x, its value is bound to the attribute $!x.

But don't do that. If the name is public, there is no downside to declaring it that way with $.x since the external view is readonly by default, and you can still access it internally with $!x.

## 13.3.15 How and why do say, put and print differ?

The most obvious difference is that say and put append a newline at the end of the output, and print does not.

But there is another difference: print and put converts its arguments to a string by calling the Str method on each item passed to, say uses the gist method instead. The former is meant for computers, the latter for human interpretation.

Or phrased differently, $obj.Str gives a string representation, $obj.gist a short summary of that object suitable for fast recognition by the programmer, and $obj.perl gives a Perlish representation.

Example: type objects, also known as "undefined values", stringify to an empty string and warn, whereas the gist method returns the name of the type, followed by an empty pair of parenthesis (to indicate there's nothing in that value except the type).

    my Date $x;     # $x now contains the Date type object
    print $x;       # empty string plus warning
    say $x;         # (Date)\n

So say is optimized for debugging and display to people, print and put is more suitable for producing output for other programs to consume.

put is thus sort of a hybrid between print and say; like print, its output is suitable for other programs, and like say, it adds a newline at the end of the output.

## 13.3.16 What's the difference between token and rule ?

regex, token and rule all three introduce regexes, but with slightly different semantics.

token implies the :ratchet or :r modifier, which prevents the rule from backtracking.

rule implies both the :ratchet and :sigspace (short :s) modifier, which means a rule doesn't backtrace, and it treats whitespace in the text of the regex as <.ws> calls (ie matches whitespace, which is optional except between two word characters). Whitespace at the start of the regex and at the start of each branch of an alternation is ignored.

regex declares a plain regex without any implied modifiers.

## 13.3.17 What's the difference between die and fail?

die throws an exception.

fail returns a Failure object. (If the caller has declared use fatal; in the calling lexical scope, fail throws an exception instead of returning.)

A Failure is an "unthrown" or "lazy" exception. It is an object that contains the exception, and throws the exception if you try to use the Failure as an ordinary object, or ignore it in sink context.

A Failure returns False from a defined check, and you can extract the exception with the exception method.

## 13.3.18 Why is wantarray or want gone? Can I return different things in different contexts?

Perl 5 has the wantarray function that tells you whether it is called in void, scalar or list context. Perl 6 has no equivalent construct, because context does not flow inwards, i.e. a routine would need time travel to know which context it is called in because context is lazy, known only when the results are used later.

For example, Perl 6 has multiple dispatch, so in a code example like

    multi w(Int $x) { say 'Int' }
    multi w(Str $x) { say 'Str' }
    w(f());

there is no way to determine if the caller of sub f wants a string or an integer, because it is not yet known what the caller is. In general this requires solving the halting problem, which even Perl 6 compiler writers have trouble with.

One way to achieve context sensitivity in Perl 6 is to return an object that knows how to respond to method calls that are typical for a context. In Perl 6 this is actually a lot easier than it may sound, and other features of the language either mitigate the need to do so in the first place, or make it possible to cover most of the use cases of wantarray.

For example regex matches return Match objects that know how to respond to list indexing, hash indexing, and that can turn into the matched string.

## 13.3.19 What's the difference between Pointer and OpaquePointer?

OpaquePointer is deprecated and has been replaced with Pointer.

# 13.4 Perl 6 Implementation

## 13.4.1 What Perl 6 Implementations are available?

Currently the best developed is Rakudo (using multiple Virtual Machine backends). Historic implementations include Niecza (.NET) and Pugs (Haskell). Others are listed at Perl 6 Compilers

## 13.4.2 What language is Rakudo written in?

A short answer is that Rakudo is written almost entirely in Perl 6. A more detailed answer is that Rakudo is written in a mixture of Perl 6 and NQP ("Not Quite Perl"). NQP is a lightweight Perl 6-like environment for virtual machines; it's designed to be a high-level way to create compilers and libraries for virtual machines (such as MoarVM and JVM) using Perl 6 syntax.

## 13.4.3 What language is NQP written in?

NQP is a mixture of (1) NQP code, (2) whatever language the underlying virtual machine is using, (3) some third-party C and Java libraries, and (4) some bootstrapping files created by earlier runs of the build process.

# 13.5 Meta Questions and Advocacy

## 13.5.1 When will Perl 6 be ready? Is it ready now?

Readiness of programming languages and their compilers is not a binary decision. As they (both the language and the implementations) evolve, they grow steadily more usable. Depending on your demands on a programming language, Perl 6 and its compilers might or might not be ready for you.

That said, version 6c (Christmas 2015) is the first official release of Perl 6 as a language, along with a validation suite and a compiler that passes it.

## 13.5.2 Why should I learn Perl 6? What's so great about it?

Perl 6 unifies many great ideas that aren't usually found in other programming languages. While several other languages offer some of these features, none of them offer all.

- Perl 6 offers procedural, object-oriented AND functional programming methodologies.

- Easy to use consistent syntax, using invariable sigils for data-structures.

- Full grapheme based Unicode support, including Annex #29.

- Regular expressions are cleaned up, made more readable, taken to the next level of usability, with a lot more functionality. Named regular expressions are made possible for ease of use.

- Junctions allowing easy checking of multiple possibilities, e.g. $a == 1|3|42 (meaning is $a equal to 1 or 3 or 42).

- Dynamic variables provide a lexically scoped alternative to global variables.

- Emphasis on composability and lexical scoping to prevent “action at a distance”. For example, imports are always lexically scoped.

- Easy to understand consistent scoping rules and closures.

- Powerful object orientation, with classes and roles (everything can be seen as an object). Inheritance. Subtyping. Code-reuse.

- Introspection into objects and meta-objects (turtles all the way down).

- Meta Object Protocol allowing for meta-programming without needing to generate / parse code.

- Subroutine and method signatures for easy unpacking of positional and named parameters.

- Multi dispatch on identically named subroutines/methods with different signatures, based on arity, types and optional additional code.

- Compile time error reporting on unknown subroutines / impossible dispatch.

- Optional gradual type-checking at no additional runtime cost. With optional type annotations.

- Advanced error reporting based on introspection of the compiler/runtime state. This means more useful, more precise error messages.

- Phasers (like BEGIN / END) allow code to be executed at scope entry / exit, loop first / last / next and many more special contexts.

- High level concurrency model, both for implicit as well as explicit multi-processing, which goes way beyond primitive threads and locks. Perl 6's concurrency offers a rich set of (composable) tools.

- Multiple-core computers are getting used more and more, and with Perl 6 these can be used thanks to parallelism, both implicit (e.g. with the >>. method) and explicit ( start { code } ). This is important, because Moore's Law is ending.

- Structured language support is provided to enable programming for asynchronous execution of code.

- Supplies allow code to be executed when something happens (like a timer, or a signal, or a file-system event).

- react / whenever / supply keywords allows easy construction of interactive, event driven applications.

- Lazy evaluation when possible, eager evaluation when wanted or necessary. This means, for example, lazy lists, and even infinite lazy lists, like the Fibonacci sequence, or all prime numbers.

- Native data types for faster, closer to the metal, processing.

- Interfacing to external libraries in C / C++ are trivially simple with NativeCall.

- Interfacing with Perl 5 (CPAN) / Python modules trivially simple with Inline::Perl5 and Inline::Python.

- Can have multiple versions of a module installed and loaded simultaneously.

- System administration simplified due to simpler update/upgrade policies.

- Simple numeric computation without precision loss because of Rats (rational numbers).

- Extensible grammars for parsing data or code (which Perl 6 uses to parse itself).

- Perl 6 is a very mutable language (define your own functions, operators, traits and data-types, which modify the parser for you).

- Large selection of data-types, plus the possibility to create your own types.

- Multi-dimensional shaped and/or native arrays with proper bounds checking.

- Execute code at any time during parsing of a grammar, or when a certain match occurred.

- Adding a custom operator or adding a trait is as simple as writing a subroutine.

- Automatic generation of hyper-operators on any operator (system or custom added).

- Runs on a variety of back-ends. Currently MoarVM & JVM, JavaScript in development, more may follow.

- Runtime optimization of hot code paths during execution (JIT).

- Runs on small (e.g. Raspberry Pi) and large multi-processor hardware.

- Garbage collection based: no timely destruction, so no ref-counting necessary. Use phasers for timely actions.

- Methods can be mixed into any instantiated object at runtime, e.g. to allow adding out-of-band data.

- Easy command-line interface accessible by MAIN subroutine with multiple dispatch and automated usage message generation.

- Fewer lines of code allow for more compact program creation. Huffman-coding of names allows for better readability.

- Lazy lists defined with a simple iterator interface, which any class can supply by minimally supplying a single method.

- Perl 6's motto's remain the same as they have been for Perl all along: “Perl is different. In a nutshell, Perl is designed to make the easy jobs easy, without making the hard jobs impossible.” and “There Is More Than One Way To Do It”. Now with even more -Ofun added.

Please see the feature comparison matrix for an overview of implemented features.

## 13.5.3 Is Perl 6 fast enough for me?

That depends on what you are doing. Rakudo has been developed with the philosophy of "make it work right then make it work fast". It's fast for some things already but needs work on others. Since the Christmas 2015 release stabilized the definition of the language, we're spending much of our effort on optimizing in 2016. Since Perl 6 provides lots of clues to the JIT that other dynamic languages don't, we think we'll have a lot of headroom for performance improvements. Some things already run faster than Perl 5.

Perl 5 programmers should be aware that Perl 6 comes with more built-in functionality. Simple benchmarks will be misleading unless you include things like Moose, type checking modules etc. in your Perl 5 script.

The following crude benchmarks, with all the usual caveats about such things, can show Perl 6 can be faster than Perl 5 for some similar common tasks if the big weaponry is included, but at the same time Perl 5 can be much faster if only the bare bones are included.

Try it on your system you may be pleasantly surprised!

Examples:

    # Perl 6 version
    use v6;

    class Foo { has $.i is rw };

    for (1..1_000_000) -> $i {
        my $obj = Foo.new;
        $obj.i = $i;
    }

    # Perl 5 version
    package Foo;
    use Moose;

    has i => (is => 'rw');

    __PACKAGE__->meta->make_immutable;

    for my $i (1..1_000_000) {
        my $obj = Foo->new;
        $obj->i($i);
    }

    1;

    # Another Perl 5 version that offers bare-bones set of features
    # compared to Moose/Perl 6's version but those are not needed in this
    # specific, simple program anyway.
    package Foo;
    use Mojo::Base -base;

    has 'i';

    for my $i (1..1_000_000) {
        my $obj = Foo->new;
        $obj->i($i);
    }

    1;

    # A perl program which works under both perl5 (with perl -Mbigint)
    # and perl6

    my ($prev, $current) = (1, 0);

    for (0..100_000) {
        ($prev, $current) = ($current, $prev + $current);
    }
    print $current;

# 14 Functions

Functions and Functional Programming in Perl 6

Routines are the smallest means of code reuse in Perl 6. 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 short subs, which exist 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 also the return value.

Introspection on subroutines is provided via Routine .

# 14.1 Defining/Creating/Using Functions

## 14.1.1 Subroutines

To create a function, often all that's needed is to define a subroutine using the sub declarator:

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

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

    sub exclaim  <b>($phrase)</b>  {
         say $phrase  <a href="~">~</a>  "!!!!"
     }
     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[&lt;-alpha -digit>] = "\\$/" given $str
     }

     say escape 'foo#bar?'; # foo\#bar\?

     {
         sub escape($str) {
             # Writes each non-alphanumeric character in its hexadecimal escape
             S:g[&lt;-alpha -digit>] = "\\x[{ $/.ord.base(16) }]" given $str
         }

         say escape 'foo#bar?' # foo\x[23]bar\x[3F]
     }

     # Back to original escape function
     say escape 'foo#bar?'; # foo\#bar\?

Subroutines don't have to be named; in this case they're called anonymous.

    say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # 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.

## 14.1.2 Blocks and Lambdas

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;
    }

    12
    34

They can also be used on their own as anonymous blocks of code.

    say { $^a ** 2 + $^b ** 2}(3, 4) # 25

For details about the syntax of blocks, see the documentation for the Block type.

## 14.1.3 Signatures

The parameters that a function accepts are described in its signature.

    sub format <b>(Str $s)</b>  { ... }
     ->  <b>$a, $b</b>  { ... }

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

### 14.1.3.1 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 that the same time.

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

capture, destructuring,

## 14.1.4 Arguments

Arguments are supplied as a comma separated list. To disambiguate nested calls parentheses or adverbial form can be used.

    sub f(&amp;c){ c() * 2 }; # call the function reference c with empty parameter list
    sub g($p){ $p - 2 };
    say(g(42)); # nest call to g in call to say
    f: { say g(666) }; # call f with a block

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 is considered good form to place named arguments after positional arguments. Inside the argument list of a function call, some special syntax is supported:

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

    f :dest&lt;/tmp/foo> :src&lt;/tmp/bar> :lines(512)
    f :32x :50y :110z   # This flavor of "adverb" works, too
    f :a:b:c            # The spaces are also optional.

## 14.1.5 Multi-dispatch

Perl 6 allows you to write several routines with the same name, but different signatures. When the routine is called by name, the runtime environment decides which is the best match, and calls that candidate. You declare each candidate with the multi declarator.

    multi congratulate($name) {
        say "Happy birthday, $name";
    }
    multi congratulate($name, $age) {
        say "Happy {$age}th birthday, $name";
    }

    congratulate 'Larry';       # Happy birthday, Larry
    congratulate 'Bob', 45;     # Happy 45th birthday, Bob

Dispatch can happen on the number of arguments (the arity), but also on the type:

    multi as-json(Bool $d) { $d ?? 'true' !! 'false'; }
    multi as-json(Real $d) { ~$d }
    multi as-json(@d)      { sprintf '[%s]', @d.map(&amp;as-json).join(', ') }

    say as-json([True, 42]);    # [true, 42]

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'); #-> Hooray for your promotion, Cindy
    $congrats.congratulate('birthday','Bob');    #-> Happy birthday, Bob

### 14.1.5.1 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 -- you 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

All multi congratulate will conform to the basic signature of two strings, optionally followed by further parameters. The | is an un-named Capture parameter, allowing a multi which takes additional arguments. The third call fails at compile time because the proto's signature becomes the common signature of all three, and 42 doesn't match Str.

    say &amp;congratulate.signature #-> (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 -- returns False if unsuccessful
    proto notify(Str $user,Str $msg) {
       my \hour = DateTime.now.hour;
       if hour > 8 or hour &lt; 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 be passed on.

    proto mistake-proto(Str() $str, Int $number = 42) {*}
    multi mistake-proto($str, $number) { say $str.WHAT }
    mistake-proto(7, 42);  #-> (Int) -- coercions not passed on
    mistake-proto('test'); #!> fails -- defaults not passed on

only

# 14.2 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. These produce a consistent look and feel.

## 14.2.1 Slurpy Conventions

Perhaps the most important of these 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, for example, chrs, or where there is a conflict with an established idiom, like 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:

- An Iterable inside a Scalar container does not count.

- 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);      # grab 1 grab 2
    grab((1, 2));    # grab 1 grab 2
    grab($(1, 2));   # grab 1 2
    grab((1, 2), 3); # 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));   # grab 1 grab 2 grab 3 grab 4
    grab(flat $(1, 2), $(3, 4)); # grab 1 2 grab 3 4
    grab(flat (1, 2));           # grab 1 grab 2
    grab(flat $(1, 2));          # grab 1 2

It is 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);       # grab 1 2
    my $b := (1, 2); # Binding, $b links directly to a bare (1, 2)
    grab($b);       # grab 1 grab 2
    my \c = (1, 2);  # Sigilless variables always bind, even with '='
    grab(c);        # grab 1 grab 2

# 14.3 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);    # 36

Or you can reference an existing named function by using the & in front of it.

    sub square($x) { $x * $x };

     # get hold of a reference to the function:
     my $func = &amp;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 &amp;square,  1..5;
    say join ', ', @squared;        # 1, 4, 9, 16, 25

## 14.3.1 Infix Form

To call a subroutine with 2 arguments like a infix operator, use a subroutine reference surrounded by [ and ].

    sub plus { $^a + $^b };
    say 21 [&amp;plus] 21;
    OUTPUT«42␤»

## 14.3.2 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();           # 42

Here $y is a lexical variable inside generate-sub, and the inner subroutine that is returned uses it. By the time that the inner sub is called, generate-sub has already exited. Yet the inner sub can still use $y, because it closed over the variable.

A less obvious but useful example for closures is using map to multiply a list of numbers:

    my $multiply-by = 5;
    say join ', ', map { $_ * $multiply-by }, 1..5;     # 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.

## 14.3.3 Routines

Routines are code objects that conform to type Routine, most notably Sub, Method, Regex and Submethod.

They carry additional functionality in addition to what Block supplies: they can come as multis, you can wrap them, and exit early with return:

    my $keywords = set &lt;if for unless while>;

     sub has-keyword(*@words) {
         for @words -> $word {
              <b>return</b>  True if $word (elem) $keywords;
         }
         False;
     }

     say has-keyword 'not', 'one', 'here';       # False
     say has-keyword 'but', 'here', 'for';       # True

Here return does not just leave the block inside which it was called, but the whole routine. In general, blocks are transparent to return, they attach to the outer 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(&amp;c){
        say "wrapping {&amp;c.name} with arguments {&amp;c.signature.perl}";
        &amp;c.wrap: sub (|args){
            note "calling {&amp;c.name} with {args.gist}";
            my \ret-val := callwith(|args);
            note "returned from {&amp;c.name} with return value {ret-val.perl}";
            ret-val
        }
    }

    my $testee-handler = wrap-to-debug(&amp;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»
    &amp;testee.unwrap($testee-handler);
    say testee(10, "ten");
    # OUTPUT«6.151190ten␤»

Important ones: candidates, wrap, unwrap, assuming, arity, count

# 14.4 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:&lt;+>(Int $x, "same") { 2 * $x };
     say 21 + "same";            # 42

     # defining a new operator
     sub postfix:&lt;!>(Int $x where { $x >= 0 }) { [*] 1..$x };
     say 6!;                     # 720

The operator declaration becomes available as soon as possible, so you can even recurse into a just-defined operator, if you really want to:

    sub postfix:&lt;!>(Int $x where { $x >= 0 }) {
         $x == 0 ?? 1 !! $x * ($x - 1)!
     }
     say 6!;                     # 720

Circumfix and postcircumfix operators are made of two delimiters, one opening and one closing.

    sub circumfix:&lt;START END>(*@elems) {
         "start", @elems, "end"
     }

     say START 'a', 'b', 'c' END;        # start a b c end

Postcircumfixes also receive the term after which they are parsed as an argument:

    sub postcircumfix:&lt;!! !!>($left, $inside) {
         "$left -> ( $inside )"
     }
     say 42!! 1 !!;      # 42 -> ( 1 )

Blocks can be assigned directly to operator names. Use a variable declarator and prefix the operator name with a &-sigil.

    my &amp;infix:&lt;ieq> = -> |l { [eq] l>>.fc };
    say "abc" ieq "Abc";
    # OUTPUT«True␤»

## 14.4.1 Precedence

Operator precedence in Perl 6 is specified relatively to existing operators. With is tighter(&other-operator) you can squeeze in an operator with a tighter precedence than the one you specified, but looser than the next-tighter precedence level.

For example infix:<*> has a tighter precedence than infix:<+> , and squeezing one in between works like this:

    sub infix:&lt;!!>($a, $b) is tighter(&amp;infix:&lt;+>) {
         2 * ($a + $b)
     }

     say 1 + 2 * 3 !! 4;     # 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:&lt;!!>($a, $b) is looser(&amp;infix:&lt;*>) { ... }

To put a new operator on the same precedence level as an existing operator, use is equiv(&other-operator) instead.

## 14.4.2 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

or as single call to an operator with three operands

    infix:&lt;+>(1, 2, 3); # list 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);      # 256
    say (2 ** 2) ** 3;      # 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:&lt;§>(*@a) is assoc&lt;list> {
         '(' ~ @a.join('|') ~ ')';
     }

     say 1 § 2 § 3;      # (1|2|3)

# 14.5 Traits

Traits are subroutines that are run at compile time to 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 &lt;close>;
    #                       ^^^^^^^ trait

... and also is tighter, is looser, is equiv and is assoc from the previous section.

Traits are subs of 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.

    multi sub trait_mod:&lt;is>(Routine $r, :$doubles!) {
         $r.wrap({
             2 * callsame;
         });
     }

     sub square($x) is doubles {
         $x * $x;
     }

     say square 3;       # 18

See type Routine for the documentation of built-in routine traits.

# 14.6 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.

In all those cases, you can use callwith to call the next routine in the chain with arguments of your own choice.

For example

    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;

produces this output:

    Int 1
     Any 2
     Back in Int with 5

Here a 1 calls the most specific Int candidate first, and callwith re-dispatches to the less specific Any candidate.

Very often, a re-dispatch passes the same argument along that the caller received, so there is a special routine for that: callsame.

    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;        # Int 1\n Any 1\n Back in Int with 5

Another common use case is to re-dispatch to the next routine in the chain, and not do anything else afterwards. That's why we have nextwith and nextsame, which call the next routine with arbitrary arguments (nextwith) or with the same argument as the caller received (nextsame), but never return to the caller. Or to phrase it differently, the nextsame and nextwith variants replace the current callframe with the next candidate.

    multi a(Any $x) {
         say "Any $x";
         return 5;
     }
     multi a(Int $x) {
         say "Int $x";
         nextsame;
         say "back in a";    # never executed, because 'nextsame' doesn't return
     }

     a 1;        # Int 1\n Any 1

As mentioned earlier, multi subs are not the only situation in which callwith , callsame , nextwith and nextsame can be helpful. One is for dispatching to wrapped routines:

    # enable wrapping:
     use soft;

     # function to be wrapped:
     sub square-root($x) { $x.sqrt }

     &amp;square-root.wrap(sub ($num) {
        nextsame if $num >= 0;
        1i * callwith(abs($num));
     });

     say square-root(4);     # 2
     say square-root(-4);    # 0+2i

The final use case is to re-dispatch to methods from parent classes.

    class LoggedVersion is Version {
         method new(|c) {
             note "New version object created with arguments " ~ c.perl;
             nextsame;
         }
     }

     say LoggedVersion.new('1.0.2');

If you need to make multiple calls to the wrapped code or to gain a reference to it, such as performing introspection it, you can use nextcallee.

    sub power-it($x) { $x * $x }
     sub run-it-again-and-again($x) {
         my &amp;again = nextcallee;
         again again $x;
     }

     &amp;power-it.wrap(&amp;run-it-again-and-again);
     say power-it(5);    # 625

# 14.7 Coercion Types

Coercion types can help you to have a specific type inside a routine, but accept wider input. When the routine is called, the argument is automatically converted to the narrower type.

    sub double(Int(Cool) $x) {
         2 * $x
     }

     say double '21';    # 42
     say double Any;     # Type check failed in binding $x; expected 'Cool' but got 'Any'

Here the Int is the target type to which the argument will be coerced, and Cool is the type that the routine accepts as input.

If the accepted input type is Any, you can abbreviate Int(Any) to Int().

The coercion works simply by looking for a method with the same name as the target type. So you can define coercions for your own types like so:

    class MyModule::Foo {
       has $.msg = "I'm a foo!";

       method MyModule::Bar {
          ::('MyModule::Bar').new(:msg($.msg ~ ' But I am now Bar.'));
       }
    }

    class MyModule::Bar {
       has $.msg;
    }

    sub print-bar(MyModule::Bar() $bar) {
       say $bar.WHAT; #MyModule::Bar
       say $bar.msg;  #I'm a foo! But I am now Bar.
    }

    print-bar MyModule::Foo.new;

Coercion types are supposed to work wherever types work, but Rakudo currently (2015.02) only implements them for subroutine parameters.

# 14.8 sub MAIN

The sub with the special name MAIN is executed after all relevant phasers, and its signature is the means by which command line arguments can be parsed. Multi methods are supported and a usage method is automatically generated and displayed if no command line arguments are provided. All command line arguments are also available in @*ARGS , it can be mutated before being processed by MAIN.

The return value of MAIN is ignored. To provide an exitcode other then 0, call exit.

    sub MAIN( Int :$length = 24,
               :file($data) where { .IO.f // die "file not found in $*CWD" } = 'file.dat',
               Bool :$verbose )
    {
        say $length if $length.defined;
        say $data   if $data.defined;
        say 'Verbosity ', ($verbose ?? 'on' !! 'off');

        exit 1;
    }

# 15 Glossary

Glossary of Perl 6 terminology

# 15.1 Abstract Class

The generic Computer Science term "abstract class" defines the interface or #API of a class. In Perl 6, this is implemented using roles with stubbed methods.

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

    class Dog does Canine {
        method bark { say "woof" }   # *MUST* be implemented by class
    }

# 15.2 Advent Calendar

In the context of Perl 6, a yearly set of blog posts for each day from the 1st until the 25th of December, to be found at https://perl6advent.wordpress.com.

# 15.3 Adverb

Generically, an adverb is a named argument to a function. There are also some specific syntax forms that allow adverbs to be tucked into some convenient places:

    q:w"foo bar"   # ":w" is a Quotelike form modifier adverb
    m:g/a|b|c/     # ":g" is also
    4 +> 5 :rotate # ":rotate" is an operator adverb
    @h{3}:exists   # ":exists" is also, but is known as a subscript adverb

Adverbs are usually expressed with colon pair notation, and for this reason colon pair notation is also known as the adverbial pair form:

    :a(4)          # Same as "a" => 4

Some other forms that use a colon in ways that have adverb-like semantics are called adverbial forms. One special form starts with an integer value, followed by a name (for the key):

    :20seconds     # same as seconds => 20

Also see #Colon Pair and Colon List.

# 15.4 Adverbial Pair

A generalized form of pair notation. They all start with the colon, like:

    adverbial pair  | pair notation
    ================|==============
      :foo&lt;bar>     | foo => 'bar'
      :foo(42)      | foo => 42
      :42foo        | foo => 42
      :$foo         | foo => $foo
      :foo          | foo => True
      :!foo         | foo => False

Also see #Adverb and #Colon Pair and Colon List.

# 15.5 Allomorph

A type that has two related values which may be used depending on the context. The allomorph types IntStr, NumStr, RatStr and ComplexStr may be created as a result of parsing a quoted string:

    say &lt;42>.WHAT;     # (IntStr)
    say &lt;42.1e0>.WHAT; # (NumStr)
    say &lt;42.1>.WHAT;   # (RatStr)
    say &lt;42+0i>.WHAT;  # (ComplexStr)

Or they may be created explicitly with differing string and numeric values.

# 15.6 Anonymous

A subroutine, method or submethod is called anonymous if it can't be called by name.

    # named subroutine
    sub double($x) { 2 * $x };

    # anonymous subroutine, stored in a named scalar
    my $double = sub ($x) { 2 * $x };

Note that it is still allowed to have a name, but you cannot call it by that name:

    # anonymous, but knows its own name
    my $s = anon sub triple($x) { 3 * $x }
    say $s.name;        # triple
    say triple(42);     # Undeclared routine: triple

# 15.7 API

Application Programming Interface. Ideally, someone using your system or library should be able to do so with knowledge only of the API, but not necessarily knowing anything about the internals or implementation.

See also #Abstract Class.

# 15.8 Apocalypse

A document originally written by #TimToady, in which he processed the initial barrage of RFC's that came out of the Perl community. Now only kept as an historical document for reference. See also #Exegesis and #Synopsis.

# 15.9 Arity

The number of positional operands expected by an operator, subroutine, method or callable block.

    sub infix:&lt;+>(Foo $a, Foo $b) { $a.Int + $b.Int }  # arity of "+" is 2
    sub frobnicate($x) { ... }                         # arity of 1
    sub the-answer() { 42 }                            # arity of 0
    -> $key, $value { ... }                            # arity of 2

The arity of a Callable is one of the main selectors in multi-dispatch.

# 15.10 AST

Acronym for A bstract S yntax T ree. Used in many places, including actions, #PAST, and #QAST.

# 15.11 Autothreading

Autothreading is what happens if you pass a Junction to a subroutine that expects a parameter of type #Any or a subtype thereof (such as anything #Cool). The call is then executed for each value of the junction. The result of these calls is assembled in a new junction of the same type as the original junction.

    sub f($x) { 2 * $x };
    say f(1|2|3) == 4;    # any(False, True, False)

Here f() is a sub with one parameter, and since it has no explicit type, it is implicitly typed as Any. The Junction argument causes the f(1|2|3) call to be internally executed as f(1)|f(2)|f(3), and the resulting junction is 2|4|6. These are then all compared to 4, resulting in a junction False|True|False. This process of separating junction arguments into multiple calls to a function is called autothreading.

If you use the resulting junction in a boolean context, such as with an if, it collapses into a single boolean which is True if any of the values in the junction are True.

    if f(1|2|3) == 4 {    # fires because f(2) == 4 is true
        say 'success';
    }

# 15.12 block

# 15.13 Boolean

Value of type #Bool. Apart the class itself, can be either True or False.

# 15.14 bytecode

# 15.15 Camelia

A butterfly image intended primarily to represent Perl 6, The Language.

# 15.16 Class

A basic software structure in #OOP. See the Wikipedia entry.

# 15.17 Colon Pair and Colon List

A colon pair is a shorthand syntax used to create or visually present a Pair object. The two most common forms are:

    :a(4)          # Same as "a" => 4,   same as Pair.new("a", 4)
    :a&lt;4>          # Same as "a" => "4", same as Pair.new("a", "4")

This is also known as the adverbial pair form. Note: when the part after the colon and before the brackets is not a legal identifier, other semantics apply, not all of which produce Pair objects.

Two other common forms are:

    :a             # Same as :a(True)
    :!a            # Same as :a(False)

A colon list just means that a list that contains only colon pairs, does not need commas, or even spaces:

    :a(4):c:!d:c   # Same as a => 4, c => True, d => False, c => True

Finally, if there is a variable with the same name as an intended adverbial pair, you don't have to specify the name twice, but just specify the adverb with the appropriate sigil:

    :$foo          # same as foo => $foo
    :@bar          # same as bar => @bar
    :%mapper       # same as mapper => %mapper
    :&amp;test         # same as test => &amp;test

See also #Adverb.

# 15.18 Damian Conway

Original author of the #Exegesis (among many other things). See also https://en.wikipedia.org/wiki/Damian_Conway.

# 15.19 Exegesis

A document originally written by #TheDamian, in which he tried to explain the Apocalypses to the common (wo)man. Now only kept as an historical document for reference. See also #Synopsis.

# 15.20 False

The value representing logical False of the #Bool enum.

# 15.21 fiddly

# 15.22 handles

# 15.23 iffy

# 15.24 Instance

An instance of a class is also called an object in some other programming languages. It has storage for attributes and is often the return value of a call to a method called new, or a literal.

Instances of most types are defined to be True e.g., defined($instance) is True.

    my Str $str = "hello";  ## this is with builtin types, e.g. Str
    if defined($str) {
        say "Oh, yeah. I'm defined.";
    }
    else {
        say "No. Something off? ";
    }

    ## if you wanted objects...
    class A {
        # nothing here for now.
    }

    my $an_instance = A.new;
    say $an_instance.defined.perl;# defined($an_instance) works too.

To put things another way, a class contains the blueprints of methods and attributes, and an instance carries it into the real world.

# 15.25 Interface

An interface is an abstract class.

# 15.26 IRC

Internet Relay Chat. Perl 6 developers and users usually hang out on the #perl6 channel of irc.freenode.org. Currently available bots are:

## 15.26.1 camelia

The #Bot on the #perl6 #IRC channel that evaluates code, eg:

    [16:28:27]  &lt;lizmat>  m: say "Hello world"
    [16:28:28]  &lt;+camelia>    rakudo-moar 812a48: OUTPUT«Hello world␤»

This is a handy tool for showing people if the output is (un)expected.

## 15.26.2 dalek

The #Bot on the #perl6 #IRC channel that reports changes made to various Perl 6 related repositories.

    [15:46:40] &lt;+dalek> doc: 2819f25 | lizmat++ | doc/Language/glossary.pod:
    [15:46:40] &lt;+dalek> doc: Add stubs for stuff inside the glossary already
    [15:46:40] &lt;+dalek> doc: review: https://github.com/perl6/doc/commit/2819f250

## 15.26.3 yoleaux

The #Bot on the #perl6 #IRC channel that provides various services to people logged in. Commands to yoleax (a pun on YOLO) start with a period. Some often used commands are:

### 15.26.3.1 .tell

Leave a message to another user who is currently not logged in. The message will be relayed as soon as the user says anything on the channel.

    .tell lizmat I've read the glossary

### 15.26.3.2 .u

Look up unicode codepoint information from either a codepoint, or the name of a codepoint.

    [16:35:44]  &lt;lizmat>   .u empty set
    [16:35:45]  &lt;yoleaux>  U+2205 EMPTY SET [Sm] (∅)
    [16:36:29]  &lt;lizmat>   .u ∅
    [16:36:30]  &lt;yoleaux>  U+2205 EMPTY SET [Sm] (∅)

Some #IRC clients then easily allow you to copy/paste the codepoint in question, which can be sometimes be easier than other unicode codepoint input methods.

# 15.27 IRC Lingo

The following terms are often used on the Perl 6 related #IRC channels:

## 15.27.1 ALAP

As Late As Possible

## 15.27.2 autopun

A self-referencing pun, e.g. "Are you ignorant or apathetic?" - "I don't know, and I don't care.

## 15.27.3 backlog

That part of a discussion on an #IRC channel that you've missed. If it is not or no longer available in your IRC client, you can go to sites such as http://irc.perl6.org to see what has been logged for you.

## 15.27.4 Bot

A program that does automatic tasks on one or more #IRC channels by acting like a regular user (as far as the IRC server is concerned) and performing some tasks that may involve answering to users requests. Examples are #camelia, #dalek and #yoleaux.

## 15.27.5 DWIM

Do What I Mean. A programming language designer motto.

## 15.27.6 flap

Sometimes a test will fail under some conditions, but not others; when this test passes some test runs and fails others, it's called flapping.

## 15.27.7 fossil

Something in a generally current document that is no longer true but which has not yet been fixed by correcting or removing it.

## 15.27.8 FSVO

For Some Value Of...

## 15.27.9 FTFY

Fixed That For You

## 15.27.10 IWBN

It Would Be Nice

## 15.27.11 LHF

Low Hanging Fruit. Usually used in the context of a (relatively) simple task to be performed by a (relative) newbie.

## 15.27.12 LTA

Less Than Awesome. Usually used in the context of an error message that is rather undescriptive or unrelated to the actual error.

## 15.27.13 NST

No Such Thing

## 15.27.14 Opt

Short for "optimization", usually in either the context of spesh or #JIT.

## 15.27.15 PB

Short for "problem". As in "that's not the pb".

## 15.27.16 PBP

"Perl Best Practices". The book by Damian Conway outlining best practices when programming Perl 5.

## 15.27.17 PR

See #Pull Request.

## 15.27.18 P5

Perl 5

## 15.27.19 P6

Perl 6

## 15.27.20 RSN

Real Soon Now

## 15.27.21 RT

Request Tracker (http://rt.perl.org/). The place where all the bugs related to #Rakudo live.

## 15.27.22 Thunk

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

## 15.27.23 TIMTOWTDI

An alternative form of #TMTOWTDI, explicitly including the "is" from the contraction "There's".

## 15.27.24 TMI

Too Much Information.

## 15.27.25 TMTOWTDI

"There's More Than One Way To Do It", the Perl motto.

## 15.27.26 UGT

"Universal Greeting Time" - i.e., it's always "morning".

## 15.27.27 WFM

Works For Me

## 15.27.28 WIP

Work In Progress

## 15.27.29 WP

Wikipedia

## 15.27.30 WW

Short for wrong window. When on #IRC, someone types something in a channel that was intended for another channel, or for a private message.

# 15.28 Larry Wall

Perl's benevolent dictator for life, among many other things. See also https://en.wikipedia.org/wiki/Larry_Wall.

# 15.29 Lexing

# 15.30 Literal

A literal is a piece of code that directly stands for an (often built-in) object and also refers to the object itself.

    my $x = 2;      # the 2 is a literal
    say $x;         # $x is not a literal, but a variable
    my $s = "Foo";  # the "Foo" is a literal, the $s is a variable

# 15.31 lvalue

An lvalue, or a left value, is anything that can appear on the left hand side of the assignment operator =. It is anything you can assign to.

Typical lvalues are variables, private and is rw attributes, lists of variables and lvalue subroutines.

Examples of lvalues:

    Declaration             lvalue          Comments

    my $x;                  $x
    my ($a, $b);            ($a, $b)
    has $!attribute;        $!attribute     Only inside classes
    has $.attrib is rw;     $.attrib
    sub a is rw { $x };     a()

Examples of things that are not lvalues:

    3                        # literals
    constant x = 3;          # constants
    has $.attrib;            # attributes; you can only assign to $!attrib
    sub f { }; f();          # "normal" subs are not writable
    sub f($x) { $x = 3 };    # error - parameters are read-only by default

These are typically called rvalues.

# 15.32 machine code

See Wikipedia entry

# 15.33 Mainline

The mainline is the program text that is not part of any kind of block.

    use v6;     # mainline
    sub f {
                # not in mainline, in sub f
    }
    f();        # in mainline again

You can also have the mainline of any package-like declarator, such as class, module, grammar, etc. These are typically run just after the class/module/grammar have been compiled (or when loaded from a pre-compiled file).

# 15.34 MoarVM

MoarVM is short for Metamodel On A Runtime Virtual Machine. It's a virtual machine designed specifically for #NQP and its #MOP: #6model. A document about the purpose of MoarVM. MoarVM has some similarities with the Hotspot VM so you may peruse its glossary for entries missing from the present one.

# 15.35 Multi-Dispatch

# 15.36 multi-method

# 15.37 Niecza

An implementation of Perl 6 targeting the .NET platform. No longer actively maintained.

# 15.38 Not Quite Perl

See #NQP.

# 15.39 NQP

NQP is a primitive language for writing subroutines and methods using a subset of the Perl 6 syntax. It's not intended to be a full-fledged programming language, nor does it provide a runtime environment beyond the basic VM primitives. Compilers (such as #Rakudo typically use NQP to compile action methods that convert a parse tree into its equivalent abstract syntax tree representation.

# 15.40 NYI

Not Yet Implemented

# 15.41 OOP

Object Oriented Programming, see https://en.wikipedia.org/wiki/Object-oriented_programming

# 15.42 opcode

# 15.43 Operator

An expression is made of operators and operands. More precisely it is made of an operator and operands that can be subexpressions or #values. Operators are an alternative syntax for a #multi-method. With that syntax, what would be the arguments of the function are named operands instead. Operators are classified into categories of categories. A category has a precedence, an arity, and can be #fiddly, #iffy, #diffy. Perl 6 is very creative as to what is an operator, so there are many categories. Operators are made of many tokens, possibly with a subexpression. For example, @a[0] belongs to the postcircumfix category, is broken into the operand @a and the postcircumfix operator [0] where 0 is the postcircumfixed subexpression.

The <O(I<...>)> construction gives information about an operator that completes the information provided by its category. Below %conditional is the category, :reducecheck<ternary> , which specifies calling .ternary to post-process the parse subtree and :pasttype<if> specifies the NQP #opcode generated in the #AST from the parse subtree.

    &lt;O('%conditional, :reducecheck&lt;ternary>, :pasttype&lt;if>')>

# 15.44 OS

See Wikipedia article

# 15.45 Parse Tree

# 15.46 Parameter

Parameter is a class to define parameters to subroutines, methods and a callable blocks. As opposed to the arguments you specify when calling a subroutine/method/callable block.

    sub foo($bar) { say $bar }     # $bar is a parameter
    foo(42);                       # 42 is an argument

# 15.47 Parrot

A virtual machine designed to run Perl 6 and other dynamic languages. No longer actively maintained.

# 15.48 PAST

#Parrot #AST.

# 15.49 perl

Name of the Perl 5 executor.

# 15.50 Perl

The Perl programming language in its many forms.

# 15.51 Perl Community

# 15.52 PERL

A way to describe Perl as a language, considered to be improper by many in the #Perl Community.

# 15.53 POD

Plain Ol' Documentation, a documentation format understood by Perl 6. See S26 for details.

# 15.54 Property

See #Attribute.

# 15.55 Pull Request

A feature of https://github.com that allows you to make patches to be easily applied using the Github user interface.

# 15.56 pugs

# 15.57 QAST

Successor to #QAST.

# 15.58 Rakudo

Rakudo is the name of a Perl 6 implementation that runs on #MoarVM and the #JVM. It is an abbreviation of "Rakuda-do," which, when translated from Japanese, means "The Way of the Camel". Also, in Japanese, "Rakudo" means "Paradise."

# 15.59 Regular Expression

See Regular Expression

# 15.60 regex

#Regular Expression.

# 15.61 Repository

# 15.62 roast

The Perl 6 specification tests, which live here: https://github.com/perl6/roast/. Originally developed for #pugs, it now serves all Perl 6 implementations. Why roast? It's the repository of all spec tests.

# 15.63 rule

(Used in regular expressions)

# 15.64 rvalue

A value that can be used on the right hand side of an assignment. See also #lvalue.

# 15.65 Sigil

In Perl, the sigil is the first character of a variable name. It must be either #$, #@, #%, or #& respectively for a scalar, array, hash, or code variable. See also #Twigil and #role. Also sigilled variables allow short conventions for variable interpolation in a double quoted string, or even postcircumfix expressions starting with such a variable.

# 15.66 Sigilless Variable

# 15.67 Spesh

A functionality of the #MoarVM platform that uses run-time 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.

# 15.68 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.

# 15.69 Stub

# 15.70 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 #VM level for modules generated from languages targeting these VMs. The set of #imported or exported symbols is called the symbol table.

# 15.71 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.

# 15.72 Syntax Analysis

# 15.73 test suite

The Perl 6 test suite is #roast

# 15.74 Texas operator

The ASCII variant of a non-ASCII Unicode operator or symbol. So described because "Everything's bigger in Texas." For instance, (elem) corresponds to the ∈ ("Is this an element of that set?") operator that comes from set theory. Texas operators are a workaround to the problem that people don't know how to type Unicode yet. Culturally, while we encourage people to use the Unicode symbols in a vague sort of way, we do not disparage the use of the ASCII variants. Well, maybe just a little...

# 15.75 TheDamian

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

# 15.76 TimToady

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

# 15.77 True

The value representing logical True of the #Bool enum.

# 15.78 value

# 15.79 Variable

A variable is a name for a container.

# 15.80 Variable Interpolation

# 15.81 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.

# 15.82 whitespace

# 15.83 6model

# 16 Grammars

Parsing and interpreting text

Grammars are a powerful tool used to destructure text and often to return data structures that have been created by interpreting that text.

For example, Perl 6 is parsed and executed using a Perl 6-style grammar.

An example that's more practical to the common Perl 6 user is the JSON::Tiny module, which can deserialize any valid JSON file, however the deserializing code is written in less than 100 lines of simple, extensible code.

If you didn't like grammar in school, don't let that scare you off grammars. Grammars allow you to group regexes, just as classes allow you to group methods of regular code.

# 16.1 Named Regexes

The main ingredient of grammars is named regexes. While the syntax of Perl 6 Regexes is outside the scope of this document, named regexes have a special syntax, similar to subroutine definitions:

In fact, named regexes can even take extra arguments, using the same syntax as subroutine parameter lists

    my  <b>regex number {</b>  \d+ [ \. \d+ ]?  <b>}</b>

In this case, we have to specify that the regex is lexically scoped using the my keyword, because named regexes are normally used within grammars.

Being named gives us the advantage of being able to easily reuse the regex elsewhere:

    say "32.51" ~~  <b>&amp;number</b> ;
     say "15 + 4.5" ~~ / <b> &lt;number> </b> \s* '+' \s* <b> &lt;number> </b> /

regex isn't the only declarator for named regexes -- in fact, it's the least common. Most of the time, the token or rule declarators are used. These are both ratcheting, which means that the match engine won't back up and try again if it fails to match something. This will usually do what you want, but isn't appropriate for all cases:

    my regex works-but-slow { .+ q }
     my token fails-but-fast { .+ q }
     my $s = 'Tokens won\'t backtrack, which makes them fail quicker!';
     say so $s ~~ &amp;works-but-slow; # True
     say so $s ~~ &amp;fails-but-fast; # False, the entire string get taken by the .+

The only difference between the token and rule declarators is that the rule declarator causes :sigspace to go into effect for the Regex:

    my token non-space-y { 'once' 'upon' 'a' 'time' }
     my rule space-y { 'once' 'upon' 'a' 'time' }
     say 'onceuponatime'    ~~ &amp;non-space-y;
     say 'once upon a time' ~~ &amp;space-y;

# 16.2 Creating Grammars

Group of named regexes that form a formal grammar

Grammar is the superclass that classes automatically get when they are declared with the grammar keyword instead of class. Grammars should only be used to parse text; if you wish to extract complex data, an action object is recommended to be used in conjunction with the grammar.

## 16.2.1 Protoregexes

If you have a lot of alternations, it may become difficult to produce readable code or subclass your grammar. In the Actions class below, the ternary in method TOP is less than ideal and it becomes even worse the more operations we we add:

    grammar Calculator {
        token TOP { [ &lt;add> | &lt;sub> ] }
        rule  add { &lt;num> '+' &lt;num> }
        rule  sub { &lt;num> '-' &lt;num> }
        token num { \d+ }
    }

    class Calculations {
        method TOP ($/) { make $&lt;add> ?? $&lt;add>.made !! $&lt;sub>.made; }
        method add ($/) { make [+] $&lt;num>; }
        method sub ($/) { make [-] $&lt;num>; }
    }

    say Calculator.parse('2 + 3', actions => Calculations).made;

    # OUTPUT:
    # 5

To make things better, we can use protoregexes that look like `:sym<...> adverbs on tokens:

    grammar Calculator {
        token TOP { &lt;calc-op> }

        proto rule calc-op          {*}
              rule calc-op:sym&lt;add> { &lt;num> '+' &lt;num> }
              rule calc-op:sym&lt;sub> { &lt;num> '-' &lt;num> }

        token num { \d+ }
    }

    class Calculations {
        method TOP              ($/) { make $&lt;calc-op>.made; }
        method calc-op:sym&lt;add> ($/) { make [+] $&lt;num>; }
        method calc-op:sym&lt;sub> ($/) { make [-] $&lt;num>; }
    }

    say Calculator.parse('2 + 3', actions => Calculations).made;

    # OUTPUT:
    # 5

In the grammar, the alternation has now been replaced with <calc-op> , which is essentially the name of a group of values we'll create. We do so by defining a rule prototype with proto rule calc-op. Each of our previous alternations have been replaced by a new rule calc-op definition and the name of the alternation is attached with :sym<> adverb.

In the actions class, we now got rid of the ternary operator and simply take the .made value from the $<calc-op> match object. And the actions for individual alternations now follow the name naming pattern as in the grammar: method calc-op:sym<add> and method calc-op:sym<sub> >.

The real beauty of this method can be seen when you subclass that grammar and actions class. Let's say we want to add a multiplication feature to the calculator:

    grammar BetterCalculator is Calculator {
        rule calc-op:sym&lt;mult> { &lt;num> '*' &lt;num> }
    }

    class BetterCalculations is Calculations {
        method calc-op:sym&lt;mult> ($/) { make [*] $&lt;num> }
    }

    say BetterCalculator.parse('2 * 3', actions => BetterCalculations).made;

    # OUTPUT:
    # 6

All we had to add are additional rule and action to the calc-op group and the thing works—all thanks to protoregexes.

## 16.2.2 Special Tokens

### 16.2.2.1 TOP

    grammar Foo {
        token TOP { \d+ }
    }

The TOP token is the default first token attempted to match when parsing with a grammar—the root of the tree. Note that if you're parsing with .parse method, token TOP is automatically anchored to the start and end of the string (see also: .subparse ).

Using rule TOP or regex TOP are also acceptable.

A different token can be chosen to be matched first using the :rule named argument to .parse, .subparse, or .parsefile Grammar methods.

### 16.2.2.2 ws

When rule instead of token is used, any whitespace after an atom is turned into a non-capturing call to ws. That is:

    rule entry { &lt;key> ’=’ &lt;value> }

Is the same as:

    token entry { &lt;key> &lt;.ws> ’=’ &lt;.ws> &lt;value> &lt;.ws> } # . = non-capturing

The default ws matches "whitespace", such a sequence of spaces (of whatever type), newlines, unspaces, or heredocs.

It's perfectly fine to provide your own ws token:

    grammar Foo {
        rule TOP { \d \d }
    }.parse: "4   \n\n 5"; # Succeeds

    grammar Bar {
        rule TOP { \d \d }
        token ws { \h*   }
    }.parse: "4   \n\n 5"; # Fails

### 16.2.2.3 Always Succeed Assertion

The <?> is the always succeed assertion. When used as a grammar token, it can be used to trigger an Action class method. In the following grammar we look for Arabic digits and define a succ token with the always succeed assertion.

In the action class, we use calles to the succ method to do set up (in this case, we prepare a new element in @!numbers). In the digit method, we convert an Arabic digit into a Devanagari digit and add it to the last element of @!numbers. Thanks to succ, the last element will always be the number for the currently parsed digit digits.

    grammar Digifier {
        rule TOP {
            [ &lt;.succ> &lt;digit>+ ]+
        }
        token succ   { &lt;?> }
        token digit { &lt;[0..9]> }
    }

    class Devanagari {
        has @!numbers;
        method digit ($/) { @!numbers[*-1] ~= $/.ord.&amp;[+](2358).chr }
        method succ  ($)  { @!numbers.push: ''     }
        method TOP   ($/) { make @!numbers[^(*-1)] }
    }

    say Digifier.parse('255 435 777', actions => Devanagari.new).made;
    # OUTPUT:
    # (२५५ ४३५ ७७७)

## 16.2.3 Methods in Grammar

It's fine to use methods instead of rules or tokens in a grammar, as long as they return a /type/Cursor:

    grammar DigitMatcher {
        method TOP (:$full-unicode) {
            $full-unicode ?? self.num-full !! self.num-basic;
        }
        token num-full  { \d+ }
        token num-basic { &lt;[0..9]>+ }
    }

The grammar above will attempt different matches depending on the arguments provided by parse methods:

    say +DigitMatcher.subparse: '12७१७९०९', args => \(:full-unicode);
    # OUTPUT:
    # 12717909

    say +DigitMatcher.subparse: '12७१७९०९', args => \(:!full-unicode);
    # OUTPUT:
    # 12

# 16.3 Action Objects

A successful grammar match gives you a parse tree of Match objects, and the deeper that match tree gets, and the more branches in the grammar are, the harder it becomes to navigate the match tree to get the information you are actually interested in.

To avoid the need for diving deep into a match tree, you can supply an actions object. After each successful parse of a named rule in your grammar, it tries to call a method of the same name as the grammar rule, giving it the newly created Match object as a positional argument. If no such method exists, it is skipped.

Here is a contrived example of a grammar and actions in action:

    use v6;

     grammar TestGrammar {
         token TOP { \d+ }
     }

     class TestActions {
         method TOP($/) {
             $/.make(2 + $/);
         }
     }

     my $actions = TestActions.new;
     my $match = TestGrammar.parse('40', :$actions);
     say $match;         # ｢40｣
     say $match.made;    # 42

An instance of TestActions is passed as named argument actions to the parse call, and when token TOP has matched successfully, it automatically calls method TOP, passing the match object as an argument.

To make it clear that the argument is a match object, the example uses $/ as a parameter name to the action method, though that's just a handy convention, nothing intrinsic. $match would have worked too. (Though using $/ does give the advantage of providing $<capture> as a shortcut for $/<capture> ).

A slightly more involved example follows:

    use v6;

     grammar KeyValuePairs {
         token TOP {
             [&lt;pair> \n+]*
         }
         token ws { \h* }

         rule pair {
             &lt;key=.identifier> '=' &lt;value=.identifier>
         }
         token identifier {
             \w+
         }
     }

     class KeyValuePairsActions {
         method identifier($/) { $/.make: ~$/                          }
         method pair      ($/) { $/.make: $&lt;key>.made => $&lt;value>.made }
         method TOP       ($/) { $/.make: $&lt;pair>».made                }
     }

     my  $res = KeyValuePairs.parse(q:to/EOI/, :actions(KeyValuePairsActions)).made;
         second=b
         hits=42
         perl=6
         EOI

     for @$res -> $p {
         say "Key: $p.key()\tValue: $p.value()";
     }

This produces the following output:

    Key: second     Value: b
     Key: hits       Value: 42
     Key: perl       Value: 6

Rule pair, which parsed a pair separated by an equals sign, aliases the two calls to token identifier to separate capture names to make them available more easily and intuitively. The corresponding action method constructs a Pair object, and uses the .made property of the sub match objects. So it (like the action method TOP too) exploits the fact that action methods for submatches are called before those of the calling/outer regex. So action methods are called in post-order.

The action method TOP simply collects all the objects that were .made by the multiple matches of the pair rule, and returns them in a list.

Also note that KeyValuePairsActions was passed as a type object to method parse, which was possible because none of the action methods use attributes (which would only be available in an instance).

In other cases, action methods might want to keep state in attributes. Then of course you must pass an instance to method parse.

Note that token ws is special: when :sigspace is enabled (and it is when we are using rule), it replaces certain whitespace sequences. This is why the spaces around the equals sign in rule pair work just fine and why the whitespace before closing } does not gobble up the newlines looked for in token TOP.

# 17 Input/Output

File-related operations

Here we present a quick overview of the file-related input/output operations. Details can be found in the documentation for the IO role, as well as the IO::Handle and IO::Path types.

# 17.1 Reading from files

One way to read the contents of a file is to open the file via the open function with the :r (read) file mode option and slurp in the contents:

    my $fh = open "testfile", :r;
    my $contents = $fh.slurp-rest;
    $fh.close;

Here we explicitly close the file handle using the close method on the IO::Handle object. This is a very traditional way of reading the contents of a file. However, the same can be done more easily and clearly like so:

    my $contents = "testfile".IO.slurp;
    # or in procedural form:
    my $contents = slurp "testfile"

By adding the IO role to the file name string, we are effectively able to refer to the string as the file object itself and thus slurp in its contents directly. Note that the slurp takes care of opening and closing the file for you.

## 17.1.1 Line by line

Of course, we also have the option to read a file line-by-line. The new line separator (i.e., $*IN.nl-in) will be excluded.

    for 'huge-csv'.IO.lines -> $line {
        # Do something with $line
    }

    # or if you'll be processing later
    my @lines = 'huge-csv'.IO.lines;

# 17.2 Writing to files

To write data to a file, again we have the choice of the traditional method of calling the open function -- this time with the :w (write) option -- and printing the data to the file:

    my $fh = open "testfile", :w;
    $fh.print("data and stuff\n");
    $fh.close;

Or equivalently with say, thus the explicit newline is no longer necessary:

    my $fh = open "testfile", :w;
    $fh.say("data and stuff");
    $fh.close;

We can simplify this by using spurt to open the file in write mode, writing the data to the file and closing it again for us:

    spurt "testfile", "data and stuff\n";

By default all (text) files are written as UTF-8, however if necessary, an explicit encoding can be specified via the :enc option:

    spurt "testfile", "latin1 text: äöüß", enc => "latin1";

To append to a file, specify the :a option when opening the file handle explicitly,

    my $fh = open "testfile", :a;
    $fh.print("more data\n");
    $fh.close;

or equivalently with say, thus the explicit newline is no longer necessary,

    my $fh = open "testfile", :a;
    $fh.say("more data");
    $fh.close;

or even simpler with the :append option in the call to spurt:

    spurt "testfile", "more data\n", :append;

To explicitly write binary data to a file, open it with the :bin option. The input/output operations then will take place using the Buf type instead of the Str type.

# 17.3 Checking files and directories

Use the e method on an IO::Handle object to test whether the file or directory exists.

    if "nonexistent_file".IO.e {
        say "file exists";
    }
    else {
        say "file doesn't exist";
    }

It is also possible to use the colon pair syntax to achieve the same thing:

    if "path/to/file".IO ~~ :e {
        say 'file exists';
    }

    my $file = "path/to/file";
    if $file.IO ~~ :e {
        say 'file exists';
    }

Similarly to the file existence check, one can also check to see if a path is a directory. For instance, assuming that the file testfile and the directory lib exist, we would obtain from the existence test method e the same result, namely that both exist:

    say "testfile".IO.e;  # True
    say "lib".IO.e;       # True

However, since only one of them is a directory, the directory test method d will give a different result:

    say "testfile".IO.d;  # False
    say "lib".IO.d;       # True

Naturally the tables are turned if we check to see if the path is a file via the file test method f:

    say "testfile".IO.f;  # True
    say "lib".IO.f;       # False

# 17.4 Getting a directory listing

To list the contents of the current directory, use the dir function. It returns a list of IO::Path objects.

    say dir;    # "/path/to/testfile".IO "/path/to/lib".IO

To list the files and directories in a given directory, simply pass a path as an argument to dir:

    say dir "/etc/";    # "/etc/ld.so.conf".IO "/etc/shadow".IO ....

# 17.5 Creating and removing directories

To create a new directory, simply call the mkdir function with the directory name as its argument:

    mkdir "newdir";

The function returns the name of the created directory on success and Nil on failure. Thus the standard Perl idiom works as expected:

    mkdir "newdir" or die "$!";

Use rmdir to remove empty directories:

    rmdir "newdir" or die "$!";

TODO: base on https://github.com/perl6/specs/blob/master/S32-setting-library/IO.pod? TODO: https://docs.perl6.org/type/IO::Handle has close but no open

# 18 Inter-Process Communication

Programs running other programs and communicating with them

# 18.1 running

Many programs need to be able to run other programs. Running a program in Perl 6 is as easy as:

    run 'git', 'status';

This line runs the program named "git" and passes "git" and "status" to its command-line. It will find the program using the %*ENV<PATH> setting.

If you would like to run a program by sending a command-line to the shell, there's a tool for that as well. All shell meta characters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on.

    shell 'ls -lR | gzip -9 > ls-lR.gz';

Caution should be taken when using shell with user input.

# 18.2 proc

Both run and shell return a Proc object, which can be used to communicate with the process in more detail.

    my $git = run 'git', 'log', '--oneline', :out;
    for $git.out.lines -> $line {
        my ($sha, $subject) = $line.split: ' ', 2;
        say "$subject [$sha]";
    }

You can tell the Proc object to capture output as a file handle by passing the :out and :err flags. You may also pass input via the :in flag.

    my $echo = run 'echo', 'Hello, world', :out;
    my $cat  = run 'cat', '-n', :in($echo.out), :out;
    say $cat.out.get;

You may also use Proc to capture the PID, send signals to the application, and check the exitcode.

    my $crontab = run 'crontab' '-l';
    if $crontab.exitcode == 0 {
        say 'crontab -l ran ok';
    }
    else {
        say 'something went wrong';
    }

# 18.3 async

When you need more control over the communication with and from another process, you will want to make use of Proc::Async. This class provides support for asynchronous communication with a program, as well as the ability to send signals to that program.

    # Get ready to run the program
    my $log = Proc::Async.new('tail', '-f',  '/var/log/system.log');
    $log.stdout.tap(-> $buf { print $buf });
    $log.stderr.tap(-> $buf { $*ERR.print $buf });

    # Start the program
    my $done = $proc.start;
    sleep 10;

    # Tell the program to stop
    $log.kill('QUIT');

    # Wait for the program to finish
    await $done;

Here is a small program that uses the "tail" program to print out the contents of the log named system.log for 10 seconds and then tells the program to stop with a QUIT signal.

Whereas Proc provides access to output using IO::Handles, Proc::Async provides access using asynchronous supplies (see Supply).

If you want to run a program and do some work while you wait for the original program to finish, the start routine returns a Promise, which is kept when the program quits.

Use the write method to pass data into the program.

# 19 Lists, Sequences, and Arrays

Positional data constructs

Lists have been a central part of computing since before there were computers, during which time many devils have taken up residence in their details. They were actually one of the hardest parts of Perl 6 to design, but through persistence and patience, Perl 6 has arrived with an elegant system for handling them.

# 19.1 Literal Lists

Literal List s are created with commas and semicolons not with parentheses, so:

    1, 2        # This is two-element list
    (1, 2)      # This is also a List, in parentheses
    (1; 2)      # same List
    (1)         # This is not a List, just a 1 in parentheses
    (1,)        # This is a one-element List

Parentheses can be used to mark the beginning and end of a List, so:

    (1, 2), (1, 2) # This is a list of two lists.

Multidimensional literal Lists are created combining comma and semicolon. They can be used in routine argument lists and subscripts.

    say so (1,2; 3,4) eqv ((1,2), (3,4));
    # OUTPUT«True␤»
    say('foo';); # a list with one element and the empty list
    # OUTPUT«(foo)()␤»

Individual elements can be pulled out of a list using a subscript. The first element of a list is at index number zero:

    say (1, 2)[0];  # says 1
    say (1, 2)[1];  # says 2
    say (1, 2)[2];  # says Nil
    say (1, 2)[-1]; # Error

# 19.2 The @ sigil

Variables in Perl 6 whose names bear the @ sigil are expected to contain some sort of list-like object. Of course, other variables may also contain these objects, but @-sigiled variables always do, and are expected to act the part.

By default, when you assign a List to an @-sigiled variable, you create an Array. Those are described below. If, instead you want to put an actual List into an @-sigiled variable, you can use binding with := instead.

    my @a := 1, 2, 3;

Assigning Lists of Lists to @-sigiled variables does not provide the same shortcut. In this case the outer List becomes the first element of the Array.

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

One of the ways @-sigiled variables act like lists is by always supporting positional subscripting. Anything bound to a @-sigiled value must support the Positional role which guarantees this:

    my @a := 1; # Type check failed in binding; expected Positional but got Int

# 19.3 Reset a List Container

To remove all elements from a Positional container assign Empty , the empty list () or a Slip of the empty list to the container.

    my @a = 1, 2, 3;
    @a = ();
    @a = Empty;
    @a = |();

# 19.4 Iteration

All lists may be iterated, which means taking each element from the list in order and stopping after the last element:

    for 1, 2, 3 { .say } # says 1, then says 2, then says 3

# 19.5 Testing for Elements

To test for elements convert the List or Array to a Set or use a Set operator.

    my @a = &lt;foo bar buzz>;
    say @a.Set&lt;bar buzz>; # OUTPUT«(True True)␤»
    say so 'bar' ∈ @a;    # OUTPUT«True␤»

## 19.5.1 Sequences

Not all lists are born full of elements. Some only create as many elements as they are asked for. These are called sequences, which are of type Seq. As it so happens, loops return Seqs.

    (loop { 42.say })[2] # says 42 three times

So, it is fine to have infinite lists in Perl 6, just so long as you never ask them for all their elements. In some cases, you may want to avoid asking them how long they are too -- Perl 6 will try to return Inf if it knows a sequence is infinite, but it cannot always know.

TODO link or describe C<...>

Although the Seq class does provide some positional subscripting, it does not provide the full interface of Positional, so an @-sigiled variable may not be bound to a Seq.

    my @s := (loop { 42.say }); # Error expected Positional but got Seq

This is because the Seq does not keep values around after you have used them. This is useful behavior if you have a very long sequence, as you may want to throw values away after using them, so that your program does not fill up memory. For example, when processing a file of a million lines:

    for 'filename'.IO.lines -> $line {
        do-something-with($line);
    }

You can be confident that the entire content of the file will not stay around in memory, unless you are explicitly storing the lines somewhere.

On the other hand, you may want to keep old values around in some cases. It is possible to hide a Seq inside a List, which will still be lazy, but will remember old values. This is done by calling the .list method. Since this List fully supports Positional, you may bind it directly to an @-sigiled variable.

    my @s := (loop { 42.say }).list;
    @s[2]; # Says 42 three times
    @s[1]; # does not say anything
    @s[4]; # Says 42 two more times

You may also use the .cache method instead of .list, depending on how you want the references handled. See the page on Seq for details.

TODO document .iterator

## 19.5.2 Slips

Sometimes you want to insert the elements of a list into another list. This can be done with a special type of list called a Slip.

    say (1, (2, 3), 4) eqv (1, 2, 3, 4);         # says False
    say (1, Slip.new(2, 3), 4) eqv (1, 2, 3, 4); # says True
    say (1, slip(2, 3), 4) eqv (1, 2, 3, 4);     # also says True

Another way to make a Slip is with the | prefix operator. Note that this has a tighter precedence than the comma, so it only affects a single value, but unlike the above options, it will break Scalars.

    say (1, |(2, 3), 4) eqv (1, 2, 3, 4);        # says True
    say (1, |$(2, 3), 4) eqv (1, 2, 3, 4);       # also says True
    say (1, slip($(2, 3)), 4) eqv (1, 2, 3, 4);  # says False

# 19.6 Lazy Lists

Lists can be lazy, what means that their values are computed on demand and stored for later use. To create a lazy list use gather/take or the sequence operator. You can also write a class that implements the role Iterable and returns True on a call to lazy. Please note that some methods like elems may cause the entire list to be computed what will fail if the list is also infinite.

    my @l = 1,2,4,8...Inf;
    say @l[0..16];
    # OUTPUT«(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536)␤»

# 19.7 Immutability

The lists we have talked about so far (List, Seq and Slip) are all immutable. This means you cannot remove elements from them, or re-bind existing elements:

    (1, 2, 3)[0]:delete; # Error Can not remove elements from a List
    (1, 2, 3)[0] := 0;   # Error Cannot use bind operator with this left-hand side
    (1, 2, 3)[0] = 0;    # Error Cannot modify an immutable Int

However, if any of the elements is wrapped in a Scalar you can still change the value which that Scalar points to:

    my $a = 2;
    (1, $a, 3)[1] = 42;
    $a.say;            # says 42

...that is, it is only the list structure itself -- how many elements there are and each element's identity -- that is immutable. The immutability is not contagious past the identity of the element.

# 19.8 List Contexts

So far we have mostly dealt with lists in neutral contexts. Lists are actually very context sensitive on a syntactical level.

## 19.8.1 List Assignment Context

When a list appears on the right hand side of an assignment into a @-sigiled variable, it is "eagerly" evaluated. This means that a Seq will be iterated until it can produce no more elements. This is one of the places you do not want to put an infinite list, lest your program hang and, eventually, run out of memory:

    my $i = 3;
    my @a = (loop { $i.say; last unless --$i }); # Says 3 2 1
    say "take off!";

## 19.8.2 Flattening "Context"

When you have a list that contains sub-lists, but you only want one flat list, you may flatten the list to produce a sequence of values as if all parentheses were removed. This works no matter how many levels deep the parentheses are nested.

    say (1, (2, (3, 4)), 5).flat eqv (1, 2, 3, 4, 5) # says True

This is not really a syntactical "context" as much as it is a process of iteration, but it has the appearance of a context.

Note that Scalar s around a list will make it immune to flattening:

    for (1, (2, $(3, 4)), 5).flat { .say } # says 1, then 2, then (3 4), then 5

...but an @-sigiled variable will spill its elements.

    my @l := 2, (3, 4);
    for (1, @l, 5).flat { .say };      # says 1, then 2, then 3, then 4, then 5
    my @a = 2, (3, 4);                 # Arrays are special, see below
    for (1, @a, 5).flat { .say };      # says 1, then 2, then (3 4), then 5

## 19.8.3 Argument List (Capture) Context

When a list appears as arguments to a function or method call, special syntax rules are at play: the list is immediately converted into a Capture. A Capture itself has a List (.list) and a Hash (.hash). Any Pair literals whose keys are not quoted, or which are not parenthesized, never make it into .list. Instead, they are considered to be named arguments and squashed into .hash. See the page on Capture for the details of this processing.

Consider the following ways to make a new Array from a List. These ways place the List in an argument list context and because of that, the Array only contains 1 and 2 but not the Pair :c(3), which is ignored.

    Array.new(1, 2, :c(3));
    Array.new: 1, 2, :c(3);
    new Array: 1, 2, :c(3);

In contrast, these ways do not place the List in argument list context, so all the elements, even the Pair :c(3), are placed in the Array.

    Array.new((1, 2, :c(3)));
    (1, 2, :c(3)).Array;
    my @a = 1, 2, :c(3); Array.new(@a);
    my @a = 1, 2, :c(3); Array.new: @a;
    my @a = 1, 2, :c(3); new Array: @a;

In argument list context the | prefix operator applied to a Positional will always slip list elements as positional arguments to the Capture, while a | prefix operator applied to an Associative will slip pairs in as named parameters:

    my @a := 2, "c" => 3;
    Array.new(1, |@a, 4);    # Array contains 1, 2, :c(3), 4
    my %a = "c" => 3;
    Array.new(1, |%a, 4);    # Array contains 1, 4

## 19.8.4 Slice Indexing Context

From the perspective of the List inside a slice subscript, is only remarkable in that it is unremarkable: because adverbs to a slice are attached after the ], the inside of a slice is not an argument list, and no special processing of pair forms happens.

Most Positional types will enforce an integer coercion on each element of a slice index, so pairs appearing there will generate an error, anyway:

    (1, 2, 3)[1, 2, :c(3)] # Method 'Int' not found for invocant of class 'Pair'

...however this is entirely up to the type -- if it defines an order for pairs, it could consider :c(3) a valid index.

Indices inside a slice are usually not automatically flattened, but neither are sublists usually coerced to Int. Instead, the list structure is kept intact, causing a nested slice operation that replicates the structure in the result:

    say ("a", "b", "c")[(1, 2), (0, 1)] eqv (("b", "c"), ("a", "b")) # says True

## 19.8.5 Range as Slice

A Range is a container for a lower and a upper boundary. Generating a slice with a Range will include any index between those bounds, including the bounds. For infinite upper boundaries we agree with mathematicians that Inf equals Inf-1.

    my @a = 1..5;
    say @a[0..2]; # OUTPUT«(1 2 3)␤»
    say @a[0..^2]; # OUTPUT«(1 2)␤»
    say @a[0..*];  # OUTPUT«(1 2 3 4 5)␤␤»
    say @a[0..^*]; # OUTPUT«(1 2 3 4 5)␤»
    say @a[0..Inf-1]; # OUTPUT«(1 2 3 4 5)␤»

## 19.8.6 Array Constructor Context

Inside an Array Literal, the list of initialization values is not in capture context and is just a normal list. It is, however, eagerly evaluated just as in assignment.

    [ 1, 2, :c(3) ] eqv Array.new((1, 2, :c(3))) # says True
    [while $++ &lt; 2 { 42.say; 43 }].map: *.say;   # says 42 twice then 43 twice
    (while $++ &lt; 2 { 42.say; 43 }).map: *.say;   # says "42" then "43"
                                                 # then "42" then "43"

Which brings us to Arrays...

# 19.9 Arrays

Arrays differ from lists in three major ways: Their elements may be typed, they automatically itemize their elements, and they are mutable. Otherwise they are Lists and are accepted wherever lists are.

    say Array ~~ List     # says True

A fourth, more subtle, way they differ is that when working with Arrays, it can sometimes be harder to maintain laziness or work with infinite sequences.

## 19.9.1 Typing

Arrays may be typed such that their slots perform a typecheck whenever they are assigned to. An Array that only allows Int values to be assigned is of type Array[Int] and one can create one with Array[Int].new. If you intend to use an @-sigiled variable only for this purpose, you may change its type by specifying the type of the elements when declaring it:

    my Int @a = 1, 2, 3;              # An Array that contains only Ints
    my @b := Array[Int].new(1, 2, 3); # Same thing, but the variable is not typed
    say @b eqv @a;                    # says True.
    my @c = 1, 2, 3;                  # An Array that can contain anything
    say @b eqv @c;                    # says False because types do not match
    say @c eqv (1, 2, 3);             # says False because one is a List
    say @b eq @c;                     # says True, because eq only checks values
    say @b eq (1, 2, 3);              # says True, because eq only checks values

    @a[0] = 42;                       # fine
    @a[0] = "foo";                    # error: Type check failed in assignment

In the above example we bound a typed Array object to a @-sigil variable for which no type had been specified. The other way around does not work -- you may not bind an Array that has the wrong type to a typed @-sigiled variable:

    my @a := Array[Int].new(1, 2, 3);     # fine
    @a := Array[Str].new("a", "b");       # fine, can be re-bound
    my Int @b := Array[Int].new(1, 2, 3); # fine
    @b := Array.new(1, 2, 3);             # error: Type check failed in binding

When working with typed arrays, it is important to remember that they are nominally typed. This means the declared type of an array is what matters. Given the following sub declaration:

    sub mean(Int @a) {
        @a.sum / @a.elems
    }

Calls that pass an Array[Int] will be successful:

    my Int @b = 1, 3, 5;
    say mean(@b);                       # @b is Array[Int]
    say mean(Array[Int].new(1, 3, 5));  # Anonymous Array[Int]
    say mean(my Int @ = 1, 3, 5);       # Another anonymous Array[Int]

However, the following calls will all fail, due to passing an untyped array, even if the array just happens to contain Int values at the point it is passed:

    my @c = 1, 3, 5;
    say mean(@c);                       # Fails, passing untyped Array
    say mean([1, 3, 5]);                # Same
    say mean(Array.new(1, 3, 5));       # Same again

Note that in any given compiler, there may be fancy, under-the-hood, ways to bypass the type check on arrays, so when handling untrusted input, it can be good practice to perform additional type checks, where it matters:

    for @a -> Int $i { $_++.say };

However, as long as you stick to normal assignment operations inside a trusted area of code, this will not be a problem, and typecheck errors will happen promptly during assignment to the array, if they cannot be caught at compile time. None of the core functions provided in Perl 6 for operating on lists should ever produce a wonky typed Array.

Nonexistent elements (when indexed), or elements to which Nil has been assigned, will assume a default value. This default may be adjusted on a variable-by-variable basis with the is default trait. Note that an untyped @-sigiled variable has an element type of Mu, however its default value is an undefined Any:

    my @a;
    @a.of.perl.say;                 # says "Mu"
    @a.default.perl.say;            # says "Any"
    @a[0].say;                      # says "(Any)"
    my Numeric @n is default(Real);
    @n.of.perl.say;                 # says "Numeric"
    @n.default.perl.say;            # says "Real"
    @n[0].say;                      # says "(Real)"

## 19.9.2 Fixed Size Arrays

To limit the dimensions of an Array provide the dimensions separated by , or ; in brackets after the name of the array container. The values of such an Arrays will default to Any. The shape can be accessed at runtime via the shape method.

    my @a[2,2];
    dd @a;
    # OUTPUT«Array.new(:shape(2, 2), [Any, Any], [Any, Any])␤»
    say @a.shape;
    # OUTPUT«(2 2)␤»

Assignment to a fixed size Array will promote a List of Lists to an Array of Arrays.

    my @a[2;2] = (1,2; 3,4);
    @a[1;1] = 42;
    dd @a;
    # OUTPUT«Array.new(:shape(2, 2), [1, 2], [3, 42])␤»

## 19.9.3 Itemization

For most uses, Arrays consist of a number of slots each containing a Scalar of the correct type. Each such Scalar, in turn, contains a value of that type. Perl 6 will automatically type-check values and create Scalars to contain them when Arrays are initialized, assigned to, or constructed.

This is actually one of the trickiest parts of Perl 6 list handling to get a firm understanding of.

First, be aware that because itemization in Arrays is assumed, it essentially means that $(…)s are being put around everything that you assign to an array, if you do not put them there yourself. On the other side, Array.perl does not put $ to explicitly show scalars, unlike List.perl:

    ((1, 2), $(3, 4)).perl.say; # says "((1, 2), $(3, 4))"
    [(1, 2), $(3, 4)].perl.say; # says "[(1, 2), (3, 4)]"
                                # ...but actually means: "[$(1, 2), $(3, 4)]"

It was decided all those extra dollar signs and parentheses were more of an eye sore than a benefit to the user. Basically, when you see a square bracket, remember the invisible dollar signs.

Second, remember that these invisible dollar signs also protect against flattening, so you cannot really flatten the elements inside of an Array with a normal call to flat or .flat.

    ((1, 2), $(3, 4)).flat.perl.say; # (1, 2, $(3, 4)).Seq
    [(1, 2), $(3, 4)].flat.perl.say; # ($(1, 2), $(3, 4)).Seq

Since the square brackets do not themselves protect against flattening, you can still spill the elements out of an Array into a surrounding list using flat.

    (0, [(1, 2), $(3, 4)], 5).flat.perl.say; # (0, $(1, 2), $(3, 4), 5).Seq

...the elements themselves, however, stay in one piece.

This can irk users of data you provide if you have deeply nested Arrays where they want flat data. Currently they have to deeply map the structure by hand to undo the nesting:

    say gather [0, [(1, 2), [3, 4]], $(5, 6)].deepmap: *.take; # 1 2 3 4 5 6

...future versions of Perl 6 might find a way to make this easier. However, not returning Arrays or itemized lists from functions, when non-itemized lists are sufficient, is something that one should consider as a courtesy to their users:

- use Slips when you want to always merge with surrounding lists

- use non-itemized lists when you want to make it easy for the user to flatten

- use itemized lists to protect things the user probably will not want flattened

- use Arrays as non-itemized lists of itemized lists, if appropriate,

- use Arrays if the user is going to want to mutate the result without copying it first.

The fact that all elements of an array are itemized (in Scalar containers) is more a gentleman's agreement than a universally enforced rule, and it is less well enforced that typechecks in typed arrays. See the section below on binding to Array slots.

## 19.9.4 Literal Arrays

Literal Arrays are constructed with a List inside square brackets. The List is eagerly iterated (at compile time if possible) and values in the list are each type-checked and itemized. The square brackets themselves will spill elements into surrounding lists when flattened, but the elements themselves will not spill due to the itemization.

## 19.9.5 Mutability

Unlike lists, Arrays are mutable. Elements may deleted, added, or changed.

    my @a = "a", "b", "c";
    @a.say;                  # [a b c]
    @a.pop.say;              # says "c"
    @a.say;                  # says "[a b]"
    @a.push("d");
    @a.say;                  # says "[a b d]"
    @a[1, 3] = "c", "c";
    @a.say;                  # says "[a c d c]"

### 19.9.5.1 Assigning

Assignment of a list to an Array is eager. The list will be entirely evaluated, and should not be infinite or the program may hang. Assignment to a slice of an Array is, likewise, eager, but only up to the requested number of elements, which may be finite:

    my @a;
    @a[0, 1, 2] = (loop { 42 });
    @a.say;                     # says "[42 42 42]"

During assignment, each value will be typechecked to ensure it is a permitted type for the Array. Any Scalar will be stripped from each value and a new Scalar will be wrapped around it.

### 19.9.5.2 Binding

Individual Array slots may be bound the same way $-sigiled variables are:

    my $b = "foo";
    my @a = 1, 2, 3;
    @a[2] := $b;
    @a.say;          # says '[1 2 "foo"]'
    $b = "bar";
    @a.say;          # says '[1 2 "bar"]'

...but binding Array slots directly to values is strongly discouraged. If you do, expect surprises with built-in functions. The only time this would be done is if a mutable container that knows the difference between values and Scalar-wrapped values is needed, or for very large Arrays where a native-typed array cannot be used. Such a creature should never be passed back to unsuspecting users.

# 20 Module Development Utilities

What can help you write/test/improve your module(s)

Here is a list of modules that you can find in the Perl 6 ecosystem which aim to make the experience of developing Perl 6 modules more fun.

# 20.1 Module builder and Authoring tools

Some modules and tools to help you with generating files that are part of a module distribution.

- App::Mi6 Minimal authoring tool for Perl6

- META6 Do things with Perl 6 META files

- Module::Skeleton Generate a skeleton module

- p6doc Generate documentation end-products

# 20.2 Tests

Some tests of module quality.

- Test::META Test your META6.json file

- Test::Output Test the output to STDOUT and STDERR your program generates

- Test::Screen Use GNU screen to test fullscreen VT applications

- Test::When Control when your tests are run (author testing, online testing, etc.)

# 20.3 NativeCall

Here some modules to help you work with NativeCall.

- NativeHelpers::Array Provides routines to deal with CArray

- App::GPTrixie Generate NativeCall code from C headers file

- NativeCall::TypeDiag Provides routines to test your CStruct

# 20.4 Sample modules

Modules that exist only as minimalist examples, tests for installers, or skeletons.

- Foo A module with two distributions of different versions

# 21 Modules

How to create, use and distribute Perl 6 modules

# 21.1 Creating and Using Modules

A module is usually a source file or set of source files

Technically a module is a set of compunits which are usually files but could come from anywhere as long as there is a compunit repository that can provide it. See S11 .
that expose Perl 6 constructs. These are typically packages (classes, roles, grammars), subroutines, and sometimes variables. In Perl 6 module can also refer to a type of package declared with the module keyword (see example below) but here we mostly mean "module" as a set of source files in a namespace.

## 21.1.1 Basic Structure

Module distributions (in the set of related source files sense) in Perl 6 have the same structure as any distribution in the Perl family of languages: there is a main project directory containing a README and a LICENSE file, a lib directory for the source files—which may be individually referred to as modules and/or may themselves define modules with the module keyword

As synopsis S11 says: Confusing? Yes it is.
, a t directory for tests, and possibly a bin directory for executable programs and scripts.

Source files generally use the standard .pm extension, and scripts or executables use .pl. However, if you wish to highlight that the file is written in Perl 6 you can use the .pm6 extension for modules, and the .p6 extension for scripts. Test files still use the normal .t extension.

## 21.1.2 Loading and Basic Importing

Loading a module makes the packages in the same namespace declared within available in the file scope of the loader. Importing from a module makes the symbols exported available in the lexical scope of the importing statement.

### 21.1.2.1 need

need loads a compunit at compile time.

    need MyModule;

Any packages in the namespace defined within will also be available.

    # MyModule.pm
    unit module MyModule;

    class MyModule::Class { ... }

MyModule::Class will be defined when MyModule is loaded.

class Class { ... } won't get exported automatically on loading...not sure if bug or..

### 21.1.2.2 use

use loads and then imports from a compunit at compile time.

    use MyModule;

It is equivalent to:

     <a href="#_language_modules.pod6-need">need</a>  MyModule;
     import MyModule;

### 21.1.2.3 require

require loads a compunit and imports definite symbols at runtime.

    sub load-mymodule {
       say "loading MyModule";
       require MyModule;
    }

    load-mymodule();

The compunit name can be in a runtime variable if you put it inside an indirect lookup.

    sub load-a-module($name){
       require ::($name);
    }

    load-a-module('MyModule');

To import symbols you must define them at compile time.

    sub do-something {
       require MyModule &lt;&amp;something>;
       something() # &amp;something will be defined here
    }

    do-something();
    # &amp;something will not be defined here

If MyModule doesn't export &something then it will fail.

## 21.1.3 Exporting and Selective Importing

### 21.1.3.1 is export

Packages, subroutines, variables, constants and enums are exported by marking them with the is export trait.

    unit module MyModule;
     our $var is export = 3;
     sub foo is export { ... };
     constant $FOO is export = "foobar";
     enum FooBar is export &lt;one two three>;

     # Packages like classes can be exported too
     class MyClass is export {};

     # If a subpackage is in the namespace of the current package
     # it doesn't need to be explicitly exported
     class MyModule::MyClass {};

As with all traits, if applied to a routine, "is export" should appear after any argument list.

    sub foo(Str $string) is export { ... }

You can pass named parameters to is export to group symbols for exporting so that the importer can pick and choose. There are three predefined tags: ALL, DEFAULT and MANDATORY.

    # lib/MyModule.pm
     unit module MyModule;
     sub bag        is export             { ... }
     sub pants      is export(:MANDATORY) { ... }
     sub sunglasses is export(:day)       { ... }
     sub torch      is export(:night)     { ... }
     sub underpants is export(:ALL)       { ... }

    # main.pl
     use lib 'lib';
     use MyModule;          #bag, pants
     use MyModule :DEFAULT; #the same
     use MyModule :day;     #pants, sunglasses
     use MyModule :night;   #pants, torch
     use MyModule :ALL;     #bag, pants, sunglasses, torch, underpants

### 21.1.3.2 UNIT::EXPORT::*

Beneath the surface, is export is adding the symbols to a UNIT scoped package in the EXPORT namespace. For example, is export(:FOO) will add the target to the UNIT::EXPORT::FOO package. This is what Perl 6 is really using to decide what to import.

    unit module MyModule;

     sub foo is export { ... }
     sub bar is export(:other) { ... }

Is the same as:

    unit module MyModule;

     my package EXPORT::DEFAULT {
         our sub foo { ... }
     }

     my package EXPORT::other {
         our sub bar { ... }
     }

For most purposes is export is sufficient but the EXPORT packages are useful when you want to produce the exported symbols dynamically. For example:

    # lib/MyModule.pm
     unit module MyModule;

     my package EXPORT::DEFAULT {
        for &lt;zero one two three four>.kv -> $number, $name {
           for &lt;sqrt log> -> $func {
              OUR::{'&amp;' ~ $func ~ '-of-' ~ $name } := sub { $number."$func"() };
           }
        }
     }

    # main.pl
     use MyModule;
     say sqrt-of-four; #-> 2
     say log-of-zero;  #-> -Inf

### 21.1.3.3 EXPORT

You can export arbitrary symbols with an EXPORT sub. EXPORT must return a Map, where the keys are the symbol names and the values are the desired values. The names should include the sigil (if any) for the associated type.

    # lib/MyModule.pm

     class MyModule::Class { ... }

     sub EXPORT {
         {
          '$var'   => 'one',
          '@array' => &lt;one two three>,
          '%hash'  => { one => 'two', three => 'four' },
          '&amp;doit'   => sub { ... },
          'ShortName' => MyModule::Class
         }
     }

    # main.pl
     use lib 'lib';
     use MyModule;
     say $var;
     say @array;
     say %hash;
     doit();
     say ShortName.new; #-> MyModule::Class.new

Note, EXPORT can't be declared inside a package because presently Rakudo (2015.09) seems to treat EXPORT as part of the compunit rather than the package.

Whereas UNIT::EXPORT packages deal with the named parameters passed to use, the EXPORT sub handles positional parameters. If you pass positional parameters to use they will be passed to EXPORT. If a positional is passed the module no longer exports default symbols. You may still import them explicitly by passing :DEFAULT to use along with your positional parameters.

    # lib/MyModule

     class MyModule::Class {}

     sub EXPORT($short_name?) {
         {
           do $short_name => MyModule::Class if $short_name
         }
     }

     sub always is export(:MANDATORY) { say "works" }

     #import with :ALL or :DEFAULT to get
     sub shy is export { say "you found me!" }

    # main.pl
     use lib 'lib';
     use MyModule 'foo';
     say foo.new(); #MyModule::Class.new
     always();      #OK   - is imported
     shy();         #FAIL - won't be imported

You can combine `EXPORT` with type captures for interesting effect. This example creates a `?` postfix which will only work on Cools.

    # lib/MakeQuestionable.pm
     sub EXPORT(::Questionable) {
         my multi postfix:&lt;?>(Questionable $_) { .so };
         {
           '&amp;postfix:&lt;?>' => &amp;postfix:&lt;?>,
         }
     }

    use MakeQuestionable Cool;
     say 0?, 1?, {}?, { a => "b" }?; # False True False True

## 21.1.4 Introspection

To list exported symbols of a module first query the export tags supported by the module.

    use URI::Escape;$
    dd URI::Escape::EXPORT::.keys;$
    # OUTPUT«("DEFAULT", "ALL").Seq»

Then use the tag you like and pick the symbol by it's name.

    dd URI::Escape::EXPORT::DEFAULT::.keys;
    # OUTPUT«("\&amp;uri-escape", "\&amp;uri_escape", "\&amp;uri-unescape", "\&amp;uri_unescape").Seq»
    my &amp;escape-uri = URI::Escape::EXPORT::DEFAULT::&lt;&amp;uri_escape>;

## 21.1.5 Finding Modules

A user may have a collection of modules not found in the normal ecosystem but needed regularly. Instead of using the lib pragma one can use the PERL6LIB environment variable to point to module locations. For example:

    export PERL6LIB=/path/to/my-modules,/path/to/more/modules

Note that the comma (',') is used as the directory separator (instead of the colon (':') as with Perl 5 for PERL5LIB or PERLLIB).

# 21.2 Distributing Modules

If you've written a Perl 6 module and would like to share it with the community, we'd be delighted to have it listed in the Perl 6 modules directory. :)

For now, the process requires that you use git for your module's version control.

The instructions herein assume that you have a GitHub account so that your module can be shared from its GitHub repository, however another provider such as GitLab should work as long as it works in a similar way.

To share your module, do the following:

- Create a project directory named after your module. For example, if your module is Vortex::TotalPerspective, then create a project directory named Vortex-TotalPerspective. This project directory name will also be used as the GitHub repo name.

- Make your project directory look like this:

      Vortex-TotalPerspective/
      |-- lib
      |   `-- Vortex
      |       `-- TotalPerspective.pm
      |-- doc
      |   `-- Vortex
      |       `-- TotalPerspective.pod6
      |-- LICENSE
      |-- META6.json
      |-- README.md
      `-- t
          `-- basic.t

  If your project contains other modules that help the main module do its job, they should go in your lib directory like so:

      lib
      `-- Vortex
          |-- TotalPerspective.pm
          `-- TotalPerspective
              |-- FairyCake.pm
              `-- Gargravarr.pm

- If you have any additional files (such as templates or a dynamic library) that you wish to have installed so you can access them at runtime, they should be placed in a resources sub-directory of your project.

- The README.md file is a markdown-formatted text file, which will later be automatically rendered as HTML by GitHub.

- Regarding the LICENSE file, if you have no other preference, you might just use the same one that Rakudo Perl 6 uses. Just copy/paste the raw form of its license into your own LICENSE file.

- If you don't yet have any tests, you can leave out the t directory and basic.t file for now. For more info on how to write tests (for now), you might have a look at how other modules use Test. It's quite similar to Perl 5's Test::More.

- To document your modules, use Perl 6 Pod markup inside your modules. Module documentation is most appreciated and will be especially important once the Perl 6 module directory (or some other site) begins rendering Pod docs as HTML for easy browsing.

  Note, described above is a minimal project directory. If your project contains scripts that you'd like distributed along with your module(s), put them in a bin directory. If you have extra docs (in addition to the Pod docs in your module(s)), create a doc directory for them. If you'd like a graphical logo to appear next to your module at the module directory, create a logotype directory and put into it a logo_32x32.png file. At some point, you might also consider adding CONTRIBUTORS , NEWS , TODO , or other files.

- Make your META6.json file look something like this:

          {
               "perl" : "6.c",
               "name" : "Vortex::TotalPerspective",
               "version" : "0.1.0",
               "description" : "Wonderful simulation to get some perspective.",
               "authors" : [ " <var class="replaceable">Your Name</var> " ],
               "provides" : {
                   "Vortex::TotalPerspective" : "lib/Vortex/TotalPerspective.pm"
               },
               "depends" : [ ],
               "resources" : [ ],
               "source-url" : "git://github.com/ <var class="replaceable">you</var> /Vortex-TotalPerspective.git"
           }

  For choosing a version numbering scheme, perhaps use "major.minor.patch" (see the spec on versioning for further details). If the version number doesn't matter to you or your users right now, you can just put in an asterisk (*) for the version.

  The authors section includes a list of all the module authors. In the case there is only one author, a single element list must be supplied.

  In the provides section, include all the namespaces provided by your distribution and that you wish to be installed, only module files that are explicitly included here will be installed and available with use or require in other programs.

  Set perl version to the minimum perl version your module works with.

  The resources section is optional, but, if present, should contain a list of the files in your resources directory that you wish to be installed, these will be installed with hashed names alongside your library files and their installed location can be determined through the %?RESOURCES Hash indexed on the name provided.

  The Test::META module can help you check the correctness of the META6.json file.

- Put your project under git version control if you haven't done so already.

- Once you're happy with your project, create a repo for it at GitHub. See GitHub's help docs if necessary. Your GitHub repo should be named the same as your project directory. Immediately after creating the GitHub repo, GitHub shows you how to configure your local repo to know about your GitHub repo.

- Push your project to GitHub.

- Consider setting up automated testing (see https://docs.travis-ci.com/user/languages/perl6).

- Create a PR on ecosystem adding your module to META.list, or ping someone on IRC (#perl6 at freenode) to get help having it added.

- After the pull request has been accepted, wait for an hour. If your module doesn't show up on https://modules.perl6.org/, please view the log file at https://modules.perl6.org/update.log to see if it identifies an error with your module or meta file.

That's it! Thanks for contributing to the Perl 6 community!

If you'd like to try out installing your module, use the panda module installer tool which is included with Rakudo Star Perl 6:

    panda install Vortex::TotalPerspective

This will download your module to its own working directory (~/.panda), build it there, and install the module into ~/.perl6.

To use Vortex::TotalPerspective from your scripts, just write use Vortex::TotalPerspective, and your Perl 6 implementation will know where to look for the module file(s).

# 21.3 Modules and Tools related to module authoring

You can find a list of modules and tools that aim to improve the experience of writing/test modules at Modules Extra

# 21.4 The Future of Ecosystem

https://modules.perl6.org and github-based infrastructure is temporary. The plan is to establish something similar to Perl 5's PAUSE/CPAN/MetaCPAN infrastructure. Volunteers needed!

The rough plan is:

    1. fix EVAL precomp bug (nine)
    2. get Repository API straight
    3. get zef up to speed
    4. continue with the metacpan fork for perl6 (jdv79)

The repository with jdv's fork can be found at https://github.com/jdv/metacpan-web

You can also already upload your Perl 6 modules to Perl 5's PAUSE, selecting `Perl6` directory during the upload. That will ensure your module is indexed in Perl 6's space and not Perl 5's.

## 21.4.1 Contact Information

To help out or learn more, join the dedicated channel #perl6-toolchain on irc.freenode.net (channel logs). A repository to discuss tooling issues is also available at https://github.com/perl6/toolchain-bikeshed

# 22 Meta-Object Protocol

Introspection and the Perl 6 Object System

Perl 6 is built on a meta object layer. That means that there are objects (the meta objects) that control how various object-oriented constructs (such as classes, roles, methods, attributes, enums, ...) behave.

To get a feeling for the meta object for class, here is the same example twice: once as normal declarations in Perl 6, and once expressed through the meta model:

    class A {
        method x() { say 42 }
    }

    A.x();

corresponds to:

    constant A := Metamodel::ClassHOW.new_type( name => 'A' );  # class A {
    A.^add_method('x', my method x(A:) { say 42 });             # method x() .. .
    A.^compose;                                                 # }

    A.x();

(except that the declarative form runs at compile time, and the latter form does not).

The meta object behind an object can be obtained with $obj.HOW, where HOW stands for Higher Order Workings (or, HOW the *%@$ does this work?).

Here, the calls with .^ are calls to the meta object, so A.^compose is a shortcut for A.HOW.compose(A). The invocant is passed in the parameter list as well, to make it possible to support prototype-style type systems, where there is just one meta object (and not one meta object per type, as standard Perl 6 does it).

As the example above demonstrates, all object oriented features are available to the user, not just to the compiler. In fact the compiler just uses such calls to meta objects.

# 22.1 Metamethods

These are introspective macros that resemble method calls.

Metamethods are generally named with ALLCAPS, and it is considered good style to avoid creating your own methods with ALLCAPS names. This will avoid conflicts with any metamethods that may appear in future versions of the language. Note that if you really must use a method which has an ALLCAPS name, use quotes around the method name to safely call it indirectly:

    #| THIS IS A CLASS FOR SHOUTING THINGS
    class MY-CLASSES-ARE-ALL-CAPS {
        method WHY { "I DON'T KNOW" }
    }
    my $c = MY-CLASSES-ARE-ALL-CAPS.new;
    say $c.WHY      # "THIS IS A CLASS FOR SHOUTING THINGS"
    say $c."WHY"()  # "I DON'T KNOW"

## 22.1.1 WHAT

The type object of the type.

For example 42.WHAT returns the Int type object.

## 22.1.2 WHICH

The object's identity value. This can be used for hashing and identity comparison, and is how the === infix operator is implemented.

## 22.1.3 WHO

The package supporting the object.

## 22.1.4 WHERE

The memory address of the object. Note that this is not stable in implementations with moving/compacting garbage collectors. Use WHICH for a stable identity indicator.

## 22.1.5 HOW

The metaclass object: "Higher Order Workings".

## 22.1.6 WHY

The attached Pod value.

## 22.1.7 DEFINITE

The object has a valid concrete representation.

Returns True for instances and False for type objects.

## 22.1.8 VAR

Returns the underlying Scalar object, if there is one.

The presence of a Scalar object indicates that the object is "itemized".

    .say for (1, 2, 3); # not itemized, so "1\n2\n3\n"
    .say for [1, 2, 3]; # itemized, so "1 2 3\n"
    say (1, 2, 3).VAR ~~ Scalar; # False
    say [1, 2, 3].VAR ~~ Scalar; # True

# 22.2 Structure of the meta object system

Note: this documentation largely reflects the meta object system as implemented by the Rakudo Perl 6 compiler, since the design documents are very light on details.

For each type declarator keyword, such as class, role, enum, module, package, grammar or subset, there is a separate meta class in the Metamodel:: namespace. (Rakudo implements them in the Perl6::Metamodel:: namespace, and then maps Perl6::Metamodel to Metamodel).

Many of the these meta classes share common functionality. For example roles, grammars and classes can all contain methods and attributes, as well as being able to do roles. This shared functionality is implemented in roles which are composed into the appropriate meta classes. For example role Metamodel::RoleContainer implements the functionality that a type can hold roles and Metamodel::ClassHOW, which is the meta class behind the class keyword, does this role.

Most meta classes have a compose method that you must call when you're done creating or modifying a meta object. It creates method caches, validates things and so on, and weird behavior ensues if you forget to call it, so don't :-).

## 22.2.1 Bootstrapping concerns

You might wonder how Metamodel::ClassHOW can be a class, when being a class is defined in terms of Metamodel::ClassHOW, or how the roles responsible for role handling can be roles. The answer is by magic.

Just kidding. Bootstrapping is implementation specific. Rakudo does it by using the object system of the language in which itself is implemented, which happens to be (nearly) a subset of Perl 6: NQP, Not Quite Perl. NQP has a primitive, class-like kind called knowhow, which is used to bootstrap its own classes and roles implementation. knowhow is built on primitives that the virtual machine under NQP provides.

Since the object model is bootstrapped in terms of lower-level types, introspection can sometimes return low-level types instead of the ones you expect, like an NQP-level routine instead of a normal Routine object, or a bootstrap-attribute instead of Attribute.

## 22.2.2 Composition time and static reasoning

In Perl 6, a type is constructed as it is parsed, so in the beginning, it must be mutable. However if all types were always mutable, all reasoning about them would get invalidated at any modification of a type. For example the list of parent types and thus the result of type checking can change during that time.

So to get the best of both worlds, there is a time when a type transitions from mutable to immutable. This is called composition, and for syntactically declared types, it happens when the type declaration is fully parsed (so usually when the closing curly brace is parsed).

If you create types through the meta-object system directly, you must call .^compose on them before they become fully functional.

Most meta classes also use composition time to calculate some properties like the method resolution order, publish a method cache, and other house-keeping tasks. Meddling with types after they have been composed is sometimes possible, but usually a recipe for disaster. Don't do it.

## 22.2.3 Power and Responsibility

The meta object protocol offers much power that regular Perl 6 code intentionally limits, such as calling private methods on classes that don't trust you, peeking into private attributes, and other things that usually simply aren't done.

Regular Perl 6 code has many safety checks in place; not so the meta model. It is close to the underlying virtual machine, and violating the contracts with the VM can lead to all sorts of strange behaviors that, in normal code, would obviously be bugs.

So be extra careful and thoughtful when writing meta types.

## 22.2.4 Power, Convenience and Pitfalls

The meta object protocol is designed to be powerful enough to implement the Perl 6 object system. This power occasionally comes at the cost of convenience.

For example, when you write my $x = 42 and then proceed to call methods on $x, most of these methods end up acting on the integer 42, not on the scalar container in which it is stored. This is a piece of convenience found in ordinary Perl 6. Many parts of the meta object protocol cannot afford to offer the convenience of automatically ignoring scalar containers, because they are used to implement those scalar containers as well. So if you write my $t = MyType; ... ; $t.^compose you are composing the Scalar that the $-sigiled variable implies, not MyType.

The consequence is that you need to have a rather detailed understanding of the subtleties of Perl 6 in order to avoid pitfalls when working with the MOP, and can't expect the same "do what I mean" convenience that ordinary Perl 6 code offers.

# 23 Native Calling Interface

Call into dynamic libraries that follow the C calling convention

# 23.1 Getting Started

The simplest imaginable use of NativeCall would look something like this:

    use NativeCall;
    sub some_argless_function() is native('something') { * }
    some_argless_function();

The first line imports various traits and types. The next line looks like a relatively ordinary Perl 6 sub declaration - with a twist. We use the "native" trait in order to specify that the sub is actually defined in a native library. The platform-specific extension (e.g., '.so' or '.dll'), as well as any customary prefixes (e.g., 'lib') will be added for you.

The first time you call "some_argless_function", the "libsomething" will be loaded and the "some_argless_function" will be located in it. A call will then be made. Subsequent calls will be faster, since the symbol handle is retained.

Of course, most functions take arguments or return values - but everything else that you can do is just adding to this simple pattern of declaring a Perl 6 sub, naming it after the symbol you want to call and marking it with the "native" trait.

# 23.2 Changing names

Sometimes you want the name of your Perl subroutine to be different from the name used in the library you're loading. Maybe the name is long or has different casing or is otherwise cumbersome within the context of the module you are trying to create.

NativeCall provides a "symbol" trait for you to specify the name of the native routine in your library that may be different from your Perl subroutine name.

    module Foo;
    use NativeCall;
    our sub init() is native('foo') is symbol('FOO_INIT') { * }

Inside of "libfoo" there is a routine called "FOO_INIT" but, since we're creating a module called Foo and we'd rather call the routine as Foo::init, we use the "symbol" trait to specify the name of the symbol in "libfoo" and call the subroutine whatever we want ("init" in this case).

# 23.3 Passing and Returning Values

Normal Perl 6 signatures and the returns trait are used in order to convey the type of arguments a native function expects and what it returns. Here is an example.

    sub add(int32, int32) returns int32 is native("calculator") { * }

Here, we have declared that the function takes two 32-bit integers and returns a 32-bit integer. Here are some of the other types that you may pass (this will likely grow with time).

    int8           (int8_t in C, also used for char)
    int16          (int16_t in C, also used for short)
    int32          (int32_t in C, also used for int)
    int64          (int64_t in C)
    uint8          (uint8_t in C, also used for unsigned char)
    uint16         (uint16_t in C, also used for unsigned short)
    uint32         (uint32_t in C, also used for unsigned int)
    uint64         (uint64_t in C)
    long           (long in C)
    longlong       (long long in C, at least 64-bit)
    num32          (float in C)
    num64          (double in C)
    Str            (C string)
    CArray[int32]  (int* in C, an array of ints)
    Pointer[void]  (void* in C, can point to all other types)
    bool           (bool from C99)
    size_t         (size_t in C)

Don't use Perl 6 native types like int or num, as they don't have to correspond to the local C equivalent (e.g., Perl 6's int can be 8 bytes but C's int is only 4 bytes).

Note that the lack of a returns trait is used to indicate void return type. Do not use the 'void' type anywhere except in the Pointer parameterization.

For strings, there is an additional "encoded" trait to give some extra hints on how to do the marshaling.

    sub message_box(Str is encoded('utf8')) is native('gui') { * }

To specify how to marshal string return types, just apply this trait to the routine itself.

    sub input_box() returns Str is encoded('utf8') is native('gui') { * }

Note that a null string can be passed by passing the Str type object; a null return will also be represented by the type object.

If the C function requires the lifetime of a string to exceed the function call, the argument must be manually encoded and passed as CArray[uint8]:

    # C prototype is void set_foo(const char *)
    sub set_foo(CArray[uint8]) is native('foo') { * }
    # C prototype is void use_foo(void)
    sub use_foo() is native('foo') { * } # will use pointer stored by set_foo()

    my $string = "FOO";
    # The lifetime of this variable must be equal to the required lifetime of
    # the data passed to the C function.
    my $array = CArray[uint8].new($string.encode.list);

    set_foo($array);
    # ...
    use_foo();
    # It's fine if $array goes out of scope starting from here.

# 23.4 Basic use of Pointers

When the signature of your native function needs a pointer to some native type (int32, uint32, etc.) all you need to do is declare the argument is rw :

    # C prototype is void my_version(int *mayor, int *minor)
    sub my_version(int32 is rw, int32 is rw) is native('foo') { * }
    my_version(my int32 $mayor, my int32 $minor); # Pass a pointer to

Sometimes you need to get a pointer (for example, a library handle) back from a C library. You don't care about what it points to - you just need to keep hold of it. The Pointer type provides for this.

    sub Foo_init() returns Pointer is native("foo") { * }
    sub Foo_free(Pointer) is native("foo") { * }

This works out OK, but you may fancy working with a type named something better than Pointer. It turns out that any class with the representation "CPointer" can serve this role. This means you can expose libraries that work on handles by writing a class like this:

    class FooHandle is repr('CPointer') {
        has $!initialized;

        # Here are the actual NativeCall functions.
        sub Foo_init() returns FooHandle is native("foo") { * }
        sub Foo_free(FooHandle) is native("foo") { * }

        # Here are the methods we use to expose it to the outside world.
        method new() {
            Foo_init();
            $!initialized = True;
        }
        method free() {
            if $!initialized {
                Foo_free(self);
                $!initialized = False; # prevent double frees
            }
        }

        # Free data when the object is garbage collected.
        method DESTROY() {
            self.free;
        }
    }

Note that the CPointer representation can do nothing more than hold a C pointer. This means that your class cannot have extra attributes. However, for simple libraries this may be a neat way to expose an object oriented interface to it.

Of course, you can always have an empty class:

    class DoorHandle is repr('CPointer') { }

And just use the class as you would use Pointer, but with potential for better type safety and more readable code.

Once again, type objects are used to represent nulls.

# 23.5 Function Pointers

C libraries can expose pointers to C functions as return values of functions and as members of Structures like, e.g., structs and unions.

Example of invoking a function pointer "$fptr" returned by a function "f", using a signature defining the desired function parameters and return value:

    sub f() returns Pointer is native('mylib') { * }

    my $fptr    = f();
    my &amp;newfunc = nativecast(:(Str, size_t --> int32), $fptr);

    say newfunc("test", 4);

# 23.6 Arrays

NativeCall has some support for arrays. It is constrained to work with machine-size integers, doubles and strings, sized numeric types, arrays of pointers, arrays of structs, and arrays of arrays.

Perl 6 arrays, which support amongst other things laziness, are laid out in memory in a radically different way to C arrays. Therefore, the NativeCall library offers a much more primitive CArray type, which you must use if working with C arrays.

Here is an example of passing a C array.

    sub RenderBarChart(Str, int32, CArray[Str], CArray[num]) is native("chart") { * }
    my @titles := CArray[Str].new;
    @titles[0]  = 'Me';
    @titles[1]  = 'You';
    @titles[2]  = 'Hagrid';
    my @values := CArray[num].new;
    @values[0]  = 59.5e0;
    @values[1]  = 61.2e0;
    @values[2]  = 180.7e0;
    RenderBarChart('Weights (kg)', 3, @titles, @values);

Note that binding was used to @titles, not assignment! If you assign, you are putting the values into a Perl 6 array, and it will not work out. If this all freaks you out, forget you ever knew anything about the @ sigil and just use $ all the way when using NativeCall. :-)

    my $titles = CArray[Str].new;
    $titles[0] = 'Me';
    $titles[1] = 'You';
    $titles[2] = 'Hagrid';

Getting return values for arrays works out just the same.

Some library APIs may take an array as a buffer that will be populated by the C function and, for instance, return the actual number of items populated:

    sub get_n_ints(CArray[int32], int32) returns int32 is native('ints') { * }

In these cases it is important that the CArray has at least the number of elements that are going to be populated before passing it to the native subroutine, otherwise the C function may stomp all over Perl's memory leading to possibly unpredictable behaviour:

    my $ints = CArray[int32].new;
    my $number_of_ints = 10;
    $ints[$number_of_ints - 1] = 0; # extend the array to 10 items

    my $n = get_n_ints($ints, $number_of_ints);

The memory management of arrays is important to understand. When you create an array yourself, then you can add elements to it as you wish and it will be expanded for you as required. However, this may result in it being moved in memory (assignments to existing elements will never cause this, however). This means you'd best know what you're doing if you twiddle with an array after passing it to a C library.

By contrast, when a C library returns an array to you, then the memory can not be managed by NativeCall, and it doesn't know where the array ends. Presumably, something in the library API tells you this (for example, you know that when you see a null element, you should read no further). Note that NativeCall can offer you no protection whatsoever here - do the wrong thing, and you will get a segfault or cause memory corruption. This isn't a shortcoming of NativeCall, it's the way the big bad native world works. Scared? Here, have a hug. Good luck! :-)

# 23.7 Structs

Thanks to representation polymorphism, it's possible to declare a normal looking Perl 6 class that, under the hood, stores its attributes in the same way a C compiler would lay them out in a similar struct definition. All it takes is a quick use of the "repr" trait:

    class Point is repr('CStruct') {
        has num64 $.x;
        has num64 $.y;
    }

The attributes can only be of the types that NativeCall knows how to marshal into struct fields. Currently, structs can contain machine-sized integers, doubles, strings, and other NativeCall objects (CArrays, and those using the CPointer and CStruct reprs). Other than that, you can do the usual set of things you would with a class; you could even have some of the attributes come from roles or have them inherited from another class. Of course, methods are completely fine too. Go wild!

CStruct objects are passed to native functions by reference and native functions must also return CStruct objects by reference. The memory management rules for these references are very much like the rules for arrays, though simpler since a struct is never resized. When you create a struct, the memory is managed for you and when the variable(s) pointing to the instance of a CStruct go away, the memory will be freed when the GC gets to it. When a CStruct-based type is used as the return type of a native function, the memory is not managed for you by the GC.

NativeCall currently doesn't put object members in containers, so assigning new values to them (with =) doesn't work. Instead, you have to bind new values to the private members: $!struct-member := StructObj.new;

As you may have predicted by now, a null is represented by the type object of the struct type.

## 23.7.1 CUnions

Likewise, it is possible to declare a Perl 6 class that stores its attributes the same way a C compiler would lay them out in a similar union definition; using the CUnion representation:

    class MyUnion is repr('CUnion') {
        has int32 $.flags32;
        has int64 $.flags64;
    }

    say nativesizeof(MyUnion.new);  # 8, ie. max(sizeof(MyUnion.flags32), sizeof(MyUnion.flags64))

## 23.7.2 Embedding CStructs and CUnions

CStructs and CUnions can be in turn referenced by -- or embedded into -- a surrounding CStruct and CUnion. To say the former we use has as usual, and to do the latter we use use the HAS declarator instead:

    class MyStruct is repr('CStruct') {
        has Point $.point;  # referenced
        has int32 $.flags;
    }

    say nativesizeof(MyStruct.new);  # 16, ie. sizeof(struct Point *) + sizeof(int32_t)

    class MyStruct2 is repr('CStruct') {
        HAS Point $.point;  # embedded
        has int32 $.flags;
    }

    say nativesizeof(MyStruct2.new);  # 24, ie. sizeof(struct Point) + sizeof(int32_t)

# 23.8 Typed Pointers

TODO

TBD more

You can type your Pointer by passing the type as a parameter. It works with the native type but also with CArray and CStruct defined types. NativeCall will not implicitly alloc the memory for it even when calling new on them. It's mostly useful in the case of a C routine returning a pointer, or if it's a pointer embedded in a CStruct.

You have to call .deref on it to access the embedded type.

    my Pointer[int32] $p; #For a pointer on int32;
    my Pointer[MyCstruct] $p2 = some_c_routine();
    my MyCstruct $mc = $p2.deref;
    say $mc.field1;

# 23.9 Buffers and Blobs

TODO

TBD

# 23.10 Function arguments

NativeCall also supports native functions that take functions as arguments. One example of this is using function pointers as callbacks in an event-driven system. When binding these functions via NativeCall, one need only provide the equivalent signature as a constraint on the code parameter:

    # void SetCallback(int (*callback)(const char *))
    my sub SetCallback(&amp;callback (Str --> int32)) is native('mylib') { * }

Note: the native code is responsible for memory management of values passed to Perl 6 callbacks this way. In other words, NativeCall will not free() strings passed to callbacks.

# 23.11 Library Paths and Names

TODO

TBD more

The native trait accepts the library name or the full path.

    constant LIBMYSQL = 'mysqlclient';
    constant LIBFOO = '/usr/lib/libfoo.so.1';
    # and later
    sub mysql_affected_rows( .. ) returns int32 is native(LIBMYSQL);
    sub bar is native(LIBFOO);

You can also put an incomplete path like './foo' and NativeCall will automatically put the right extension according to the platform specification.

BE CAREFUL: the native trait and constant are evaluated at compile time. Don't write a constant that depends on a dynamic variable like:

    constant LIBMYSQL = %*ENV&lt;P6LIB_MYSQLCLIENT> || 'mysqlclient';

This will keep the value given at compile time. A module will be precompiled and LIBMYSQL will keep the value it acquires when the module gets precompiled.

## 23.11.1 ABI/API Version

If you write native('foo') NativeCall will search libfoo.so under Unix like system (libfoo.dynlib on OS X, foo.dll on win32). In most modern system it will require you or the user of your module to install the development package because it's recommended to always provide an API/ABI version to a shared library, so libfoo.so ends often being a symbolic link provided only by a devel package.

To avoid that, the native trait allows you to specify the API/ABI version. It can be a full version or just a part of it. (Try to stick to Major version, some BSD code does not care for Minor.)

    sub foo is native('foo', v1); # Will try to load libfoo.so.1
    sub foo is native('foo', v1.2.3); # Will try to load libfoo.so.1.2.3

    my List $lib = ('foo', 'v1');
    sub foo is native($lib);

## 23.11.2 Routine

The native trait also accepts a Callable as argument, allowing you to provide your own way to handle the way it will find the library file to load.

    sub foo is native(sub {'libfoo.so.42'});

It will only be called at the first invocation of the sub.

## 23.11.3 Calling into the standard library

If you want to call a C function that's already loaded, either from the standard library or from your own program, you can pass the Str type object as the argument to is native, so is native(Str).

For example on a UNIX-like operating system, you could use the following code to print the home directory of the current user:

    use NativeCall;
    my class PwStruct is repr('CStruct') {
        has Str $.pw_name;
        has Str $.pw_passwd;
        has uint32 $.pw_uid;
        has uint32 $.pw_gid;
        has Str $.pw_gecos;
        has Str $.pw_dir;
        has Str $.pw_shell;
    }
    sub getuid()              returns uint32   is native(Str) { * };
    sub getpwuid(uint32 $uid) returns PwStruct is native(Str) { * };

    say getpwuid(getuid()).pw_dir;

Though of course $*HOME is a much easier way :-)

# 23.12 Exported variables

Variables exported by a library -- also named "global" or "extern" variables -- can be accessed using cglobal. For example:

    my $var := cglobal('libc.so.6', 'errno', int32)

This code binds to $var a new Proxy object that redirects all its accesses to the integer variable named "errno" as exported by the "libc.so.6" library.

# 23.13 C++ Support

NativeCall offers support to use classes and methods from C++ as shown in https://github.com/rakudo/rakudo/blob/nom/t/04-nativecall/13-cpp-mangling.t (and its associated C++ file). Note that at the moment it's not as tested and developed as C support.

# 23.14 Helper Functions

The NativeCall library exports several subroutines to help you work with data fron native libraries.

## 23.14.1 sub nativecast

    sub nativecast($target-type, $source) is export(:DEFAULT)

This will cast the Pointer $source to an object of $target-type. The source pointer will typically have been obtained from a call to a native subroutine that returns a pointer or as a member of a struct, this may be specified as void * in the C library definition for instance, but you may also cast from a pointer to a less specific type to a more specific one.

As a special case, if a Signature is supplied as $target-type then a subroutine will be returned which will call the native function pointed to by $source in the same way as a subroutine declared with the native trait. This is described in Function Pointers.

## 23.14.2 sub cglobal

    sub cglobal($libname, $symbol, $target-type) is export is rw

This returns a Proxy object that provides access to the extern named $symbol that is exposed by the specified library. The library can be specified in the same ways that they can be to the native trait.

## 23.14.3 sub nativesizeof

    sub nativesizeof($obj) is export(:DEFAULT)

This returns the size in bytes of the supplied object, it can be thought of as being equivalent to sizeof in C. The object can be a builtin native type such as int64 or num64, a CArray or a class with the repr CStruct, CUnion or CPointer.

# 23.15 Examples

The zavolaj git repository (where NativeCall was originally developed) hosts various examples of how to use NativeCall.

More examples can be found in the DBIsh repository.

## 23.15.1 MySQL

TODO Do we really need this here? Seems like this info should just go along-side that example in the git repo, rather than replicated on p6doc.

There is an example of using the MySQL client library. There is a project https://github.com/mberends/minidbi that wraps these functions with a DBI compatible interface. You'll need that library to hand; on Debian-esque systems it can be installed with something like:

    sudo apt-get install libmysqlclient

Prepare your system along these lines before trying out the examples:

    $ mysql -u root -p
    CREATE DATABASE zavolaj;
    CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'testpass';
    GRANT CREATE         ON zavolaj.* TO 'testuser'@'localhost';
    GRANT DROP           ON zavolaj.* TO 'testuser'@'localhost';
    GRANT INSERT         ON zavolaj.* TO 'testuser'@'localhost';
    GRANT DELETE         ON zavolaj.* TO 'testuser'@'localhost';
    GRANT SELECT         ON zavolaj.* TO 'testuser'@'localhost';
    GRANT LOCK TABLES    ON zavolaj.* TO 'testuser'@'localhost';
    GRANT SELECT         ON   mysql.* TO 'testuser'@'localhost';
    # or maybe otherwise
    GRANT ALL PRIVILEGES ON zavolaj.* TO 'testuser'@'localhost';

You can look at the results via a normal mysql connection:

    $ mysql -utestuser -ptestpass
    USE zavolaj;
    SHOW TABLES;
    SELECT * FROM nom;

## 23.15.2 Microsoft Windows

The win32-api-call.p6 script shows an example Windows API call done from Perl 6. See https://github.com/jnthn/zavolaj/tree/master/examples

# 24 Object Orientation

Object Orientation in Perl 6

Perl 6 is an object oriented language at its core, even though it allows you to write programs in other programming styles.

Perl 6 comes with a wealth of predefined types, which can be classified in two categories: normal and native types.

Native types are used for low-level types (like uint64). They do not have the same capabilities as objects, though if you call methods on them, they are boxed into normal objects.

Everything that you can store in a variable is either a native value or an object. That includes literals, types (type objects), code and containers.

# 24.1 Using Objects

You can use objects by calling methods on them. To call a method on an expression, add a dot, followed by the method name:

     <a href="#_routine_say.pod6">say</a>  "abc" <b>. <a href="#_routine_uc.pod6">uc</a> </b> ;
     # ABC

This calls the uc method on "abc", which is an object of type Str . If you need to supply arguments to the method, add parentheses after the method name with the arguments inside the parentheses:

    my $formatted-text = "Fourscore and seven years ago...". <a href="#_routine_indent.pod6">indent</a>  <b>(8)</b> ;

$formatted-text now contains the above text, but indented 8 spaces.

Multiple arguments simply require a comma between them:

    my @words = "Abe", "Lincoln";
     @words. <a href="#_routine_push.pod6">push</a> ("said" <b>,</b>  $formatted-text. <a href="#_routine_comb.pod6">comb</a> ( <a href="#_language_regexes.pod6">/\w+/</a> ));

Another method call syntax separates the method name and the argument list with a colon:

    say @words. <a href="#_routine_join.pod6">join</a> : '--';
     # Abe--Lincoln--said--Fourscore--and--seven--years--ago

Since you have to put a : after the method if you want to pass arguments without parentheses, a method call without a colon or parens is unambiguously a method call without an argument list:

    say 4.log:   ; # 1.38629436111989 ( natural logarithm of 4 )
    say 4.log: +2; # 2                ( base-2 logarithm of 4 )
    say 4.log  +2; # 3.38629436111989 ( natural logarithm of 4, plus 2 )

Many operations that don't look like method calls (for example, smart matching, or interpolating an object into a string) result in method calls under the hood.

Methods can return mutable containers, in which case you can assign to the return value of a method call. This is how read-writable attributes to objects are used:

    $*IN. <a href="#_routine_nl-in.pod6">nl-in</a>  = "\r\n";

Here, we are calling method nl-in on the $*IN object, without arguments, and assign to the container it returned with the = operator.

All objects support methods from class Mu, which is the root of the type hierarchy. In other words, all objects are derived from Mu.

## 24.1.1 Type Objects

Types themselves are objects and you can get the type object simply by writing its name:

    my $int-type-obj = Int;

You can ask any object for its type object by calling the WHAT method (which is actually a macro in method form):

    my $int-type-obj = 1.WHAT;

Type objects (other than Mu) can be compared for equality with the === identity operator:

    sub f(Int $x) {
         if $x.WHAT  <b> <a href="===">===</a> </b>  Int {
             say 'you passed an Int';
         }
         else {
             say 'you passed a subtype of Int';
         }
     }

Although, in most cases, the .isa method will suffice:

    sub f($x) {
         if $x <b>. <a href="#_routine_isa.pod6">isa</a> </b> (Int) {
             ...
         }
         ...
     }

Subtype checking is done by smart-matching:

    if $type  <b> <a href="~~">~~</a> </b>   <a href="#_type_Real.pod6">Real</a>  {
         say '$type contains Real or a subtype thereof';
     }

# 24.2 Classes

Classes are declared using the class keyword, typically followed by a name.

    class Journey {
    }

This declaration results in a type object being created and installed in the current package and current lexical scope under the name Journey. You can also declare classes lexically:

    my class Journey {
    }

This restricts their visibility to the current lexical scope, which can be useful if the class is an implementation detail nested inside a module or another class.

## 24.2.1 Attributes

Attributes are variables that exist per instance of a class. They are where the state of an object is stored. In Perl 6, all attributes are private. They are typically declared using the has declarator and the ! twigil.

    class Journey {
        has $!origin;
        has $!destination;
        has @!travellers;
        has $!notes;
    }

While there is no such thing as a public (or even protected) attribute, there is a way to have accessor methods generated automatically: replace the ! twigil with the . twigil (the . should remind you of a method call).

    class Journey {
        has $.origin;
        has $.destination;
        has @!travellers;
        has $.notes;
    }

This defaults to providing a read-only accessor. In order to allow changes to the attribute, add the is rw trait:

    class Journey {
        has $.origin;
        has $.destination;
        has @!travellers;
        has $.notes is rw;
    }

Now, after a Journey object is created, its .origin, .destination, and .notes will all be accessible from outside the class, but only .notes can be modified.

The above allows creation of Journey objects without an origin or destination. To change this you can provide a default value or make sure that it is provided by marking it with is required.

    class Journey {
        # error if origin is not provided
        has $.origin is required;
        # set the destination to Orlando as default (unless that is the origin!)
        has $.destination = self.origin eq 'Orlando' ?? 'Kampala' !! 'Orlando';
        has @!travellers;
        has $.notes is rw;
    }

Since classes inherit a default constructor from Mu and we have requested that some accessor methods are generated for us, our class is already somewhat functional.

    # Create a new instance of the class.
     my $vacation = Journey.new(
         origin       <a href="=&gt;">=></a>  'Sweden',
         destination => 'Switzerland',
         notes       => 'Pack hiking gear!'
     );

     # Use an accessor; this outputs Sweden.
     say $vacation.origin;

     # Use an rw accessor to change the value.
     $vacation.notes = 'Pack hiking gear and sunglasses!';

Note that the default constructor will only set attributes that have an accessor method, but it can initialize read-only attributes.

## 24.2.2 Methods

Methods are declared with the method keyword inside a class body.

    class Journey {
         has $.origin;
         has $.destination;
         has @!travellers;
         has $.notes is rw;

          <b>method</b>  add_traveller($name) {
             if $name  <a href="#_routine_ne.pod6">ne</a>   <a href="#_routine_any.pod6">any</a> (@!travellers) {
                  <a href="#_routine_push.pod6">push</a>  @!travellers, $name;
             }
             else {
                  <a href="#_routine_warn.pod6">warn</a>  "$name is already going on the journey!";
             }
         }

          <b>method</b>  describe() {
             "From $!origin to $!destination"
         }
     }

A method can have a signature, just like a subroutine. Attributes can be used in methods and can always be used with the ! twigil, even if they are declared with the . twigil. This is because really, the . twigil declares a ! twigil and then additionally generates an accessor method.

Looking at the code above, there is a subtle but important difference between using $!origin and $.origin in the method describe. The first is always a simple lookup of the attribute. It is cheap, and you know that it is the attribute declared in this class. The latter is really a method call and thus it may be overridden in a subclass. Only use $.origin if you explicitly want to allow overriding.

Unlike Subroutines, additional named arguments will not produce compile time or runtime errors. That allows chaining of methods via Re-dispatching

Method names can be resolved at runtime with the ."" operator.

    class A { has $.b };
    my $name = 'b';
    A.new."$name"().say;
    # OUTPUT«(Any)␤»

## 24.2.3 self

Inside a method, the term self is available, which is bound to the invocant, i.e. the object that the method was called on. self can be used to call further methods on the invocant. Within methods, something like $.origin is the same thing as self.origin.

## 24.2.4 Private Methods

Methods strictly for use inside the class and that are not to be called from anywhere else are declared with an exclamation mark ! before the method name. They are called with an exclamation mark instead of a dot:

    method !do-something-private($x) {
        ...
    }
    method public($x) {
        if self.precondition {
            self!do-something-private(2 * $x)
        }
    }

Private methods are not inherited to subclasses.

## 24.2.5 Submethods

A submethod is a public method that is not inherited to subclasses. The name stems from the fact that they are semantically similar to subroutines.

Submethods are useful for object construction and destruction tasks, as well as for tasks that are so specific to a certain type that subtypes must certainly override them.

For example the default method new calls submethod BUILD on each class in an inheritance chain:

    class Point2D {
         has $.x;
         has $.y;

         submethod BUILD(:$!x, :$!y) {
             say "Initializing Point2D";
         }
     }

     class InvertiblePoint2D is Point2D {
         submethod BUILD() {
             say "Initializing InvertiblePoint2D";
         }
         method invert {
             self.new(x => - $.x, y => - $.y);
         }
     }

     say InvertiblePoint2D.new(x => 1, y => 2);

This produces the following output:

    Initializing Point2D
     Initializing InvertiblePoint2D
     InvertiblePoint2D.new(x => 1, y => 2)

See also: #Object Construction.

## 24.2.6 Inheritance

Classes can have parent classes.

    class Child  <b> <a href="#_routine_is.pod6">is</a>  Parent1 is Parent2</b>  { }

If a method is called on the child class, and the child class does not provide that method, the method of that name in one of the parent classes is invoked instead, if it exists. The order in which parent classes are consulted is called the method resolution order (MRO). Perl 6 uses the C3 method resolution order. You can ask a type for its MRO through a call to its meta class:

    say List <b>.^ <a href="#_type_Metamodel::C3MRO.pod6-mro">mro</a> </b> ;      # List() Cool() Any() Mu()

If a class does not specify a parent class, Any is assumed by default. All classes directly or indirectly derive from Mu, the root of the type hierarchy.

All calls to public methods are "virtual" in the C++ sense, which means that the actual type of an object determines which method to call, not the declared type:

    class Parent {
         method frob {
             say "the parent class frobs"
         }
     }

     class Child is Parent {
         method frob {
             say "the child's somewhat more fancy frob is called"
         }
     }

     my Parent $test;
     $test = Child.new;
     $test.frob;          # calls the frob method of Child rather than Parent

This produces the output:

    the child's somewhat more fancy frob is called

## 24.2.7 Object Construction

Objects are generally created through method calls, either on the type object or on another object of the same type.

Class Mu provides a constructor method called new, which takes named arguments and uses them to initialize public attributes.

    class Point {
         has $.x;
         has $.y = 2 * $!x;
     }
     my $p = Point <b>. <a href="#_routine_new.pod6">new</a> </b> ( x  <a href="=&gt;">=></a>  5, y => 2);
     #             ^^^ inherited from class Mu
     say "x: ", $p.x;
     say "y: ", $p.y;

This outputs:

    x: 5
    y: 2

    my $p2 = Point <b>.new</b> ( x => 5 );
     # the given value for x is used to calculate the right
     # value for y.
     say "x: ", $p.x;
     say "y: ", $p.y;

This outputs:

    x: 5
    y: 10

Mu.new calls method bless on its invocant, passing all the named arguments. bless creates the new object and then calls method BUILDALL on it. BUILDALL walks all subclasses in reverse method resolution order (i.e. from Mu to most derived classes) and in each class checks for existence of a method named BUILD. If it exists, it is called, again passing all named arguments from method new to it. If not, the public attributes from this class are initialized from named arguments of the same name. In either case, if neither BUILD nor the default mechanism has initialized the attribute, default values are applied (the 2 * $!x in the example above).

Due to the nature of the default behavior of BUILDALL and custom BUILD submethods, named arguments to the constructor new derived from Mu can correspond directly to public attributes of any of the classes in the method resolution order, or to any named parameter to any BUILD submethod.

This object construction scheme has several implications for customized constructors. First, custom BUILD methods should always be submethods, otherwise they break attribute initialization in subclasses. Second, BUILD submethods can be used to run custom code at object construction time. They can also be used for creating aliases for attribute initialization:

    class EncodedBuffer {
         has $.enc;
         has $.data;

         submethod  <b>BUILD</b> (:encoding(:$enc), :$data) {
             $!enc   <a href=":=">:=</a>   $enc;
             $!data := $data;
         }
     }
     my $b1 = EncodedBuffer.new( encoding => 'UTF-8', data => [64, 65] );
     my $b2 = EncodedBuffer.new( enc      => 'UTF-8', data => [64, 65] );
     #  both enc and encoding are allowed now

Since passing arguments to a routine binds the arguments to the parameters, a separate binding step is unnecessary if the attribute is used as a parameter. Hence the example above could also have been written as:

        submethod BUILD(:encoding(:$ <b>!</b> enc), :$ <b>!</b> data) {
             # nothing to do here anymore, the signature binding
             # does all the work for us.
         }

The third implication is that if you want a constructor that accepts positional arguments, you must write your own new method:

        class Point {
             has $.x;
             has $.y;
             method new($x, $y) {
                 self. <a href="#_routine_bless.pod6">bless</a> (:$x, :$y);
             }
         }

However this is considered poor practice, because it makes correct initialization of objects from subclasses harder.

Another thing to note is that the name new is not special in Perl 6. It is merely a common convention. You can call bless from any method at all, or use CREATE to fiddle around with low-level workings.

Another pattern of hooking into object creation is by writing your own method BUILDALL. To make sure that initialization of superclasses works fine, you need to callsame to invoke the parent classes BUILDALL.

    class MyClass {
         method BUILDALL(|) {
             # initial things here

             callsame;   # call the parent classes (or default) BUILDALL

             # you can do final checks here.

             self # return the fully built object
         }
     }

TODO: better example for BUILDALL overriding

## 24.2.8 Object Cloning

The Mu parent class, from which all classes inherit, supplies a method named clone which is somewhat magical, in that it can copy values from an instance's private attributes to create a new instance. This cloning is shallow, in that it only binds attributes to the same values they contained in the original instance; it does not make copies of those contained values.

As with new, one may provide initial values for public attributes. These override values received from the original instance. (See the documentation for Mu's clone for an example.)

Note that since clone is not a submethod, a class which provides its own clone method will replace the Mu method. There is no automatic mechanism like BUILDALL for cloning. For example, if one wished to make clone deeper for a particular class, one would will probably want to use callwith or nextwith to push the deeper copies to superclasses:

    class A {
        has $.a;
        #...
        method clone {
            nextwith(:a($.a.clone))
        }
    }

This works well for simple classes, but in some cases one might need to follow BUILDALL's lead and work in reverse method resolution order:

    class B is A {
        has $.b;
        #...
        method clone {
            my $obj = callsame;
            $obj.b = $!b.clone(:seed($obj.a.generate_seed));
            $obj
        }
    }

# 24.3 Roles

Roles are in some ways similar to classes, in that they are a collection of attributes and methods. They differ in that roles are also meant for describing only parts of an object's behavior and in how roles are applied to classes. Or to phrase it differently, classes are meant for managing instances and roles are meant for managing behavior and code reuse.

    use MONKEY-SEE-NO-EVAL;
     role Serializable {
         method serialize() {
             self. <a href="#_routine_perl.pod6">perl</a> ; # very primitive serialization
         }
         method deserialize($buf) {
              <a href="#_routine_EVAL.pod6">EVAL</a>  $buf; # reverse operation to .perl
         }
     }

     class Point  <b>does</b>  Serializable {
         has $.x;
         has $.y;
     }
     my $p = Point.new(:x(1), :y(2));
     my $serialized = $p.serialize;      # method provided by the role
     my $clone-of-p = Point.deserialize($serialized);
     say $clone-of-p.x;      # 1

Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.

## 24.3.1 Role Application

Role application differs significantly from class inheritance. When a role is applied to a class, the methods of that role are copied into the class. If multiple roles are applied to the same class, conflicts (e.g. attributes or non-multi methods of the same name) cause a compile-time error, which can be solved by providing a method of the same name in the class.

This is much safer than multiple inheritance, where conflicts are never detected by the compiler, but are instead simply resolved to the superclass that appears earlier in the method resolution order, which might not be what the programmer wanted.

For example, if you've discovered an efficient method to ride cows, and are trying to market it as a new form of popular transportation, you might have a class Bull, for all the bulls you keep around the house, and a class Automobile, for things that you can drive.

    class Bull {
        has Bool $.castrated = False;
        method steer {
            # Turn your bull into a steer
            $!castrated = True;
            return self;
        }
    }
    class Automobile {
        has $.direction;
        method steer($!direction) { }
    }
    class Taurus is Bull is Automobile { }

    my $t = Taurus.new;
    $t.steer; # Castrates $t

With this setup, your poor customers will find themselves unable to turn their Taurus and you won't be able to make more of your product! In this case, it may have been better to use roles:

    role Bull-Like {
        has Bool $.castrated = False;
        method steer {
            # Turn your bull into a steer
            $!castrated = True;
            return self;
        }
    }
    role Steerable {
        has Real $.direction;
        method steer(Real $d = 0) {
            $!direction += $d;
        }
    }
    class Taurus does Bull-Like does Steerable { }

This code will die with something like:

    ===SORRY!===
    Method 'steer' must be resolved by class Taurus because it exists in
    multiple roles (Steerable, Bull-Like)

This check will save you and your customers a lot of headaches and you can simply define your class instead as:

    class Taurus does Bull-Like does Steerable {
        method steer($direction?) {
            self.Steerable::steer($direction?)
        }
    }

When a role is applied to a second role, the actual application is delayed until the second role is applied to a class, at which point both roles are applied to the class. Thus

    role R1 {
        # methods here
    }
    role R2 does R1 {
        # methods here
    }
    class C does R2 { }

produces the same class C as

    role R1 {
        # methods here
    }
    role R2 {
        # methods here
    }
    class C does R1 does R2 { }

## 24.3.2 Stubs

When a role contains a stubbed method, a non-stubbed version of a method of the same name must be supplied at the time the role is applied to a class. This allows you to create roles that act as abstract interfaces.

    role AbstractSerializable {
         method serialize() {  <b> <a href="...">...</a> </b>  }  # literal ... here marks the
                                           # method as a stub
     }

     # the following is a compile time error, for example
     #        Method 'serialize' must be implemented by Point because
     #        it is required by a role
     class APoint does AbstractSerializable {
         has $.x;
         has $.y;
     }

     # this works:
     class SPoint does AbstractSerializable {
         has $.x;
         has $.y;
         method serialize() { "p($.x, $.y)" }
     }

The implementation of the stubbed method may also be provided by another role.

## 24.3.3 Inheritance

Roles cannot inherit from classes, but they may cause any class which does that role to inherit from another class. So if you write:

        role A is Exception { }
         class X::Ouch does A { }
         X::Ouch.^parents.say # ((Exception))

...then X::Ouch will inherit directly from Exception, as we can see above by listing its parents.

## 24.3.4 Pecking order

A method defined directly in a class will always override definitions from applied roles or from inherited classes. If no such definition exists, methods from roles override methods inherited from classes. This happens both when said class was brought in by a role, and also when said class was inherited directly.

Note that each candidate for a multi-method is its own method... in this case, the above only applies if two such candidates have the same signature. Otherwise, there is no conflict, and the candidate is just added to the multi-method.

## 24.3.5 Automatic Role Punning

Any attempt to instantiate (and many other kinds of usage) a role will automatically create a class with the same name as the role, making it possible to transparently use a role as if it were a class.

    role Point {
         has $.x;
         has $.y;
         method abs { sqrt($.x * $.x + $.y * $.y) }
     }
     say Point.new(x => 6, y => 8).abs;

We call this automatic creating of classes punning, and the generated class a pun.

## 24.3.6 Parameterized Roles

Roles can be parameterized, by giving them a signature in square brackets:

    role BinaryTree[::Type] {
         has BinaryTree[Type] $.left;
         has BinaryTree[Type] $.right;
         has Type $.node;

         method visit-preorder(&amp;cb) {
             cb $.node;
             for $.left, $.right -> $branch {
                 $branch.visit-preorder(&amp;cb) if defined $branch;
             }
         }
         method visit-postorder(&amp;cb) {
             for $.left, $.right -> $branch {
                 $branch.visit-postorder(&amp;cb) if defined $branch;
             }
             cb $.node;
         }
         method new-from-list(::?CLASS:U: *@el) {
             my $middle-index = @el.elems div 2;
             my @left         = @el[0 .. $middle-index - 1];
             my $middle       = @el[$middle-index];
             my @right        = @el[$middle-index + 1 .. *];
             self.new(
                 node    => $middle,
                 left    => @left  ?? self.new-from-list(@left)  !! self,
                 right   => @right ?? self.new-from-list(@right) !! self,
             );
         }
     }

     my $t = BinaryTree[Int].new-from-list(4, 5, 6);
     $t.visit-preorder(&amp;say);    # 5 \n 4 \n 6
     $t.visit-postorder(&amp;say);   # 4 \n 6 \n 5

Here the signature consists only of a type capture, but any signature will do:

    use v6;

     enum Severity &lt;debug info warn error critical>;

     role Logging[$filehandle = $*ERR] {
         method log(Severity $sev, $message) {
             $filehandle.print("[{uc $sev}] $message\n");
         }
     }

     Logging[$*OUT].log(debug, 'here we go');        # [DEBUG] here we go

You can have multiple roles of the same name, but with different signatures; the normal rules of multi dispatch apply for choosing multi candidates.

## 24.3.7 Mixins of Roles

Roles can be mixed into objects. A role's given attributes and methods will be added to the methods and attributes the object already has. Multiple mixins and anonymous roles are supported.

    role R { method Str() {'hidden!'} };
    my $i = 2 but R;
    sub f(\bound){ put bound };
    f($i); # hidden!

Note that the object got the role mixed in, not the object's class or the container. Thus @-sigiled containers will require binding to make the role stick. Some operators will return a new value, which effectively strips the mixin from the result.

Mixins can happen at any time of your object's life.

    # A counter for Table of Contents
    role TOC-Counter {
        has Int @!counters is default(0);
        method Str() { @!counters.join: '.' }
        method inc($level) {
            @!counters[$level - 1]++;
            @!counters.splice($level);
            self
        }
    }

    my Num $toc-counter = NaN;     # don't do maths with Not A Number
    say $toc-counter; # NaN
    $toc-counter does TOC-Counter; # now we mix the role in
    $toc-counter.inc(1).inc(2).inc(2).inc(1).inc(2).inc(2).inc(3).inc(3);
    put $toc-counter / 1;          # NaN (because that's numerical context)
    put $toc-counter;              # 2.2.2 (put will call TOC-Counter::Str)

Roles can by anonymous.

    my %seen of Int is default(0 but role :: { method Str() {'NULL'} });
    say %seen&lt;not-there>;          # NULL
    say %seen&lt;not-there>.defined;  # True (0 may be False but is well defined)
    say Int.new(%seen&lt;not-there>); # 0

# 24.4 Meta-Object Programming and Introspection

Perl 6 has a meta object system, which means that the behavior of objects, classes, roles, grammars, enums, etc. are themselves controlled by other objects; those objects are called meta objects. Meta objects are, like ordinary objects, instances of classes, in this case we call them meta classes.

For each object or class you can get the meta object by calling .HOW on it. Note that although this looks like a method call, it is actually special-cased in the compiler, so it is more like a macro.

So, what can you do with the meta object? For one you can check if two objects have the same meta class by comparing them for equality:

    say 1.HOW ===   2.HOW;      # True
    say 1.HOW === Int.HOW;      # True
    say 1.HOW === Num.HOW;      # False

Perl 6 uses the word HOW, Higher Order Workings, to refer to the meta object system. Thus it should be no surprise that in Rakudo, the class name of the meta class that controls class behavior is called Perl6::Metamodel::ClassHOW. For each class there is one instance of Perl6::Metamodel::ClassHOW.

But of course the meta model does much more for you. For example it allows you to introspect objects and classes. The calling convention for methods on meta objects is to call the method on the meta object and pass in the object of interest as first argument to the object. So to get the name of the class of an object, you could write:

    my $object = 1;
    my $metaobject = 1.HOW;
    say $metaobject.name($object);      # Int

    # or shorter:
    say 1.HOW.name(1);                  # Int

(The motivation is that Perl 6 also wants to allow a more prototype-based object system, where it's not necessary to create a new meta object for every type).

To get rid of using the same object twice, there is a shortcut:

    say 1.^name;                        # Int
    # same as
    say 1.HOW.name(1);                  # Int

See Metamodel::ClassHOW for documentation of the meta class of class and also the general documentation on the meta object protocol.

# 25 Operators

Common Perl 6 infixes, prefixes, postfixes, and more!

# 25.1 Operator Precedence

In an expression like 1 + 2 * 3, the 2 * 3 is evaluated first because the infix * has tighter precedence than the +.

The following table summarizes the precedence levels in Perl 6, from tightest to loosest:

A | Level | Examples
--- | --- | ---
N | Terms | 42 3.14 "eek" qq["foo"] $x :!verbose @$array
L | Method postfix | .meth .+ .? .* .() .[] .{} .<> .«» .:: .= .^ .:
N | Autoincrement | ++ --
R | Exponentiation | **
L | Symbolic unary | ! + - ~ ? | || +^ ~^ ?^ ^
L | Multiplicative | * / % %% +& +< +> ~& ~< ~> ?& div mod gcd lcm
L | Additive | + - +| +^ ~| ~^ ?| ?^
L | Replication | x xx
X | Concatenation | ~
X | Junctive and | &
X | Junctive or | | ^
L | Named unary | temp let
N | Structural infix | but does <=> leg cmp .. ..^ ^.. ^..^
C | Chaining infix | != == < <= > >= eq ne lt le gt ge ~~ === eqv !eqv =~=
X | Tight and | &&
X | Tight or | || ^^ // min max
R | Conditional | ?? !! ff fff
R | Item assignment | = => += -= **= xx= .=
L | Loose unary | so not
X | Comma operator | , :
X | List infix | Z minmax X X~ X* Xeqv ...
R | List prefix | print push say die map substr ... [+] [*] any Z=
X | Loose and | and andthen
X | Loose or | or xor orelse
X | Sequencer | <==, ==>, <<==, ==>>
N | Terminator | ; {...}, unless, extra ), ], }

Using two ! symbols below generically to represent any pair of operators that have the same precedence, the associativities specified above for binary operators are interpreted as follows:

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)

For unary operators this is interpreted as:

A | Assoc | Meaning of !$a!
--- | --- | ---
L | left | (!$a)!
R | right | !($a!)
N | non | ILLEGAL

In the operator descriptions below, a default associativity of left is assumed.

# 25.2 Operator classification

Operators can occur in several positions relative to a term:

+term | prefix
term1 + term2 | infix
term++ | postfix
(term) | circumfix
term1[term2] | postcircumfix

Each operator is also available as a subroutine. The name of the routine is formed of the operator category, then a colon, and a list quote construct with the symbol(s) that make up the operator:

    infix:&lt;+>(1, 2)                 # same as 1 + 2
    circumfix:«( )»('a', 'b', 'c')  # same as ('a', 'b', 'c')

As a special case the listop (list operator) can stand either as a term or as a prefix. Subroutine calls are the most common listops. Other cases include meta-reduced infix operators ([+]| 1, 2, 3) and the #prefix ... etc. stub operators.

Defining custom operators is covered in Defining Operators functions.

# 25.3 Meta Operators

Meta operators can be parameterized with other operators or subroutines in the same way as functions can take functions as parameters. To use a subroutine as a parameter prefix it's name with a &. Perl 6 will generate the actual combined operator in the background, allowing the mechanism to be applied to user defined operators. There are quite a few Meta operators with different semantics, as explained in detail as follows.

# 25.4 Substitution Operators

    my $str = 'match string';
    $str ~~ s/match/replacement/;
    say $str; # replacement string

    say S/match/replacement/ given 'match string'; # replacement string

The lower-case version (s///) substitutes in-place, while the upper-case version (S///) leaves the original alone and returns the resultant string.

Both operators work on `$_` variable. Since smartmatch operator aliases the left hand side to `$_`, you can use lowercase `s///` with it, but it's a mistake to use it with uppercase `S///`, because you can't retrieve the modified string. The correct way is to alias the given string by some other method, such as a `for` loop or, as is shown in the example above, with a `given` block (in this case, it's a postfix form of it, without curlies).

Both operators can take the same adverbs as the .subst method, which go between the `s`/`S` and the opening `/`. Whitespace can be used liberally:

    $str ~~ s:g/match/replacement/;
    say S:i :g /match/replacement/;

You can also use a different delimiter:

    $str ~~ s!foo!!;
    say S{foo} = {} given 'foobar';

Non-matching characters can simply replace the original slashes. Matching characters, like braces, require an extra step where you use an assignment operator to assign the replacement to the match part.

# 25.5 Assignment Operators

Infix operators can be combined with the assignment operator to modify a value and apply the result to a container in one go. Containers will be autovivified if possible.

    my $a = 32;
    $a += 10;  # 42

    my $a = 3;
    $a min= 5; # still 3
    $a min= 2; # 2

This behavior is automatically extended to include custom-defined infix operators.

    sub infix:&lt;space-concat> ($a, $b) { $a ~ " " ~ $b };
    my $a = 'word1';
    $a space-concat= 'word2'; # 'word1 word2'

Although not strictly operators, methods can be used in the same fashion.

    my Rat $a .= new;
    my $a = 3.14;
    $a .= Int; # 3

# 25.6 Negated Relational Operators

The result of a relational operator returning Bool can be negated by prefixing with !. To avoid visual confusion with the !! operator, you may not modify any operator already beginning with !.

There are shortcuts for !== and !eq, namely != and ne.

    my $a = True;
    say so $a != True; # False
    my $i = 10;

    my $release = Date.new(:2015year, :12month, :24day);
    my $today = Date.today;
    say so $release !before $today; # True

# 25.7 Reversed Operators

Any infix operator may be called with its two arguments reversed by prefixing with R. Associativity of operands is reversed as well.

    say 4 R/ 12; # 3
    say [R/] 2, 4, 16; # 2

# 25.8 Hyper Operators

Hyper operators apply a given operator enclosed by « and » to one or two lists, returning the resulting list. The pointy part of « or » has to point to the shorter list. A list with just one element is fine too. If one of the lists is shorter then the other, the operator will cycle over the shorter list until all elements of the longer list are processed.

    say (1, 2, 3) »*» 2;          # (2 4 6)
    say (1, 2, 3, 4) »~» &lt;a b>;   # (1a 2b 3a 4b)
    say (1, 2, 3) »+« (4, 5, 6);  # (5 7 9)

Assignment meta operators can be hyped.

    my @a = 1, 2, 3;
    say @a »+=» 1; # [2 3 4]

Hyper forms of unary operators have the pointy bit point to the operator and the blunt end at the list to be operated on.

    my @wisdom = True, False, True;
    say !« @wisdom; # [False True False]

    my @a = 1, 2, 3;
    @a»++;           # (2, 3, 4)

Hyper operators are defined recursively on nested arrays.

    say -« [[1, 2], 3]; # [[-1 -2] -3]

Methods can be called too, in an out of order, concurrent fashion. The resulting list is in order. Please note that all hyper operators are candidates for autothreading and will cause tears if said methods have side effects. The optimizer has full reign over hyper operators, which is the reason that they can not be defined by the user.

    my CarefulClass @objs;
    my @results = @objs».take-care();

    my @slops; # May Contain Nuts
    @slops».?this-method-may-not-exist();

Hyper operators can work with hashes. The pointy direction indicates if missing keys are to be ignored in the resulting hash. The enclosed operator operates on all values that have keys in both hashes.

C<%foo «+» %bar;> | intersection of keys
C<%foo »+« %bar;> | union of keys
C<%outer »+» %inner;> | only keys of %inner that exist in %outer will occur in the result

    my %outer = 1, 2, 3 Z=> &lt;a b c>;
    my %inner = 1, 2 Z=> &lt;x z>;
    say %outer «~» %inner; # {"1" => "ax", "2" => "bz"}

Hyper operators can take user defined operators as its operator argument.

    sub pretty-file-site (Int $size --> Str) {
        # rounding version of infix:&lt;/>(Int, Int)
        sub infix:&lt;r/>(Int \i1, Int \i2) {
            round(i1 / i2, 0.1)
        }

        # we build a vector of fractions of $size and zip that with the fitting prefix
        for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
                  Z      &lt;EB     PB     TB     GB     MB     KB> -> [\v,\suffix] {
            # starting with the biggest suffix, we take the first that is 0.5 of that suffix or bigger
            return v ~ ' ' ~ suffix if v > 0.4
        }
        # this be smaller or equal then 0.4 KB
        return $size.Str;
    }

    for 60, 50, 40, 30, 20, 10 -> $test {
        my &amp;a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
        print pretty-file-site(a.Int) xx 2, ' ';
    }

    # OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB»

Hyper operators do not descent into child lists. You can chain hyper operators to destructure a List of Lists.

    my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
    my $p = (2, 3);
    say $neighbors »>>+&lt;&lt;» ($p, *); # ((1 3) (2 2) (2 4) (3 3))

# 25.9 Reduction Operators

Reduction operators apply any infix operator, surrounded by [ and ], element by element and return the resulting value. To use a function reference provide an additional layer of [ and ].

    say [+] 1, 2, 3; # 6
    sub plus { $^a + $^b };
    say [[&amp;plus]] 1, 2, 3; # 6

They can be defined as a list prefix operators or will be generated automatically.

    multi infix:&lt;[~~]> (@c, &amp;test) is looser(&amp;infix:&lt;~~>) {
        gather for @c { take $_ if test($_) }
    };
    my @l = 1, 'a', 2, 'b';
    say @l [~~] {$^a ~~ Str}; # (a b)

For list infix operators, flattening is not done on the input list. This allows list operators to become the reduction operator.

    [X~] (1, 2), &lt;a b> # 1, 2 X~ &lt;a b>

By default reduction meta operators are eager. To lazily generate values, prefix the operator with a \. If the non-meta part contains a \ already, quote it with [] (e.g. [\[\x]]).

    my $lazy := [\+] 1..*;
    say $lazy[^10]; # (1 3 6 10 15 21 28 36 45 55)

# 25.10 Cross Operators

The cross metaoperator, X, will apply a given infix operator in order of cross product to all lists, such that the rightmost operator varies most quickly.

    1..3 X~ &lt;a b>
    # produces &lt;1a, 1b, 2a, 2b, 3a, 3b>

# 25.11 Zip Operators

The zip metaoperator, Z, will apply a given infix operator to pairs taken one left, one right, from its arguments. The resulting list is returned.

    my @l = &lt;a b c> Z~ 1, 2, 3; # [a1 b2 c3]

If one of the operands runs out of elements prematurely, the zip operator will stop. An infinite list can be used to repeat elements. A list with a final element of * will repeat its 2nd last element indefinitely.

    my @l = &lt;a b c d> Z~ ':' xx *; # &lt;a: b: c: d:>
    my @l = &lt;a b c d> Z~ 1, 2, *;  # &lt;a1 b2 c2 d2>

If infix operator is not given, , (comma operator) will be used by default:

    my @l = 1 Z 2; # [(1 2)]

# 25.12 Sequential Operators

The sequential metaoperator, S, will suppress any concurrency, or reordering done by the optimizer. Most simple infix operators are supported.

    say so 1 S&amp; 2 S&amp; 3; # True

# 25.13 Nesting of Meta Operators

To avoid ambiguity when chaining meta operators use square brackets to help the compiler to understand you.

    my @a = 1, 2, 3;
    my @b = 5, 6, 7;
    @a X[+=] @b;
    say @a; # [19 20 21]

# 25.14 Term Precedence

## 25.14.1 term < >

The quote-words construct. Breaks up the contents on whitespace, and returns a List of the words. If a word looks like a number literal or a Pair literal, it is converted to the appropriate number.

    say &lt;a b c>[1];     # b

## 25.14.2 term ( )

The grouping operator.

An empty group () creates an empty List . Parens around non-empty expressions simply structure the expression, but not have additional semantics.

In an argument list, putting parenthesis around an argument prevents it from being interpreted as a named argument.

    multi sub p(:$a!) { say 'named'      }
    multi sub p($a)   { say 'positional' }
    p a => 1;       # named
    p (a => 1);     # positional

## 25.14.3 term { }

Block or Hash constructor.

If the contents looks like a list of pairs and does not use $_ or other placeholder parameters, returns an itemized Hash.

Otherwise it constructs a Block.

Note that this construct does not re-parse the contents; rather the contents are always parsed as a statement list (i.e. like a block), and if the later analysis shows that it needs to be interpreted as a hash, the block is executed and coerced to Hash.

## 25.14.4 circumfix [ ]

The Array constructor. Returns an itemized Array which does not flatten in list context.

# 25.15 Method Postfix Precedence

## 25.15.1 postcircumfix [ ]

    sub postcircumfix:&lt;[ ]>(@container, **@index,
                            :$k, :$v, :$kv, :$p, :$exists, :$delete)

Universal interface for positional access to zero or more elements of a @container, a.k.a. "array indexing operator".

    my @alphabet = 'a' .. 'z';
    say @alphabet[0];                   #-> a
    say @alphabet[1];                   #-> b
    say @alphabet[*-1];                 #-> z
    say @alphabet[100]:exists;          #-> False
    say @alphabet[15, 4, 17, 11].join;  #-> perl
    say @alphabet[23 .. *].perl;        #-> ("x", "y", "z")

    @alphabet[1, 2] = "B", "C";
    say @alphabet[0..3].perl            #-> ("a", "B", "C", "d")

See Subscripts for a more detailed explanation of this operator's behavior, and how to implement support for it in custom types.

## 25.15.2 postcircumfix { }

    sub postcircumfix:&lt;{ }>(%container, **@key,
                            :$k, :$v, :$kv, :$p, :$exists, :$delete)

Universal interface for associative access to zero or more elements of a %container, a.k.a. "hash indexing operator".

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color{"banana"};               #-> yellow
    say %color{"cherry", "kiwi"}.perl;  #-> ("red", "green")
    say %color{"strawberry"}:exists;    #-> False

    %color{"banana", "lime"} = "yellowish", "green";
    %color{"cherry"}:delete;
    say %color;  #-> banana => yellowish, kiwi => green, lime => green

See postcircumfix < > and postcircumfix « » for convenient shortcuts, and Subscripts for a more detailed explanation of this operator's behavior, and how to implement support for it in custom types.

## 25.15.3 postcircumfix < >

Shortcut for postcircumfix { } that quotes its argument using the same rules as the quote-words operator of the same name.

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    say %color&lt;banana>;             #-> yellow
    say %color&lt;cherry kiwi>.perl;   #-> ("red", "green")
    say %color&lt;strawberry>:exists;  #-> False

This is not a real operator, just syntactic sugar that is turned into the { } postcircumfix operator at compile-time.

## 25.15.4 postcircumfix « »

Shortcut for postcircumfix { } that quotes its argument using the same rules as the interpolating quote-words operator of the same name.

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    my $fruit = "kiwi";
    say %color«cherry $fruit».perl;   #-> ("red", "green")

This is not a real operator, just syntactic sugar that is turned into the { } postcircumfix operator at compile-time.

## 25.15.5 postcircumfix ( )

The call operator. Treats the invocant as a Callable and invokes it, using the expression between the parens as arguments.

Note that an identifier followed by a pair of parens is always parsed as a subroutine call.

If you want your objects to respond to the call operator, you need to implement a method CALL-ME.

## 25.15.6 postfix .

The operator for calling one method, $invocant.method.

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.7 postfix .&

The operator to call a subroutine (with at least one positional argument) like a method. The invocant will be bound to the first positional argument.

Technically this is not an operator, but syntax special-cased in the compiler.

    my sub f($invocant){ dd $invocant; }
    my $i = 42;
    42.&amp;f;
    # OUTPUT«Int $invocant = 42␤»
    42.&amp;(-> $invocant { dd $invocant });
    # OUTPUT«Int $invocant = 42␤»

## 25.15.8 postfix .=

A mutating method call. $invocant.=method desugars to $invocant = $invocant.method, similar to = .

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.9 postfix .^

A meta-method call. $invocant.^method calls method on $invocant's metaclass. It desugars to $invocant.HOW.method($invocant, ...). See HOW for more information.

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.10 postfix .?

Safe call operator. $invocant.?method calls method method on $invocant if it has a method of such name. Otherwise it returns Nil.

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.11 postfix .+

$invocant.+method calls all methods called method from $invocant, and returns a List of the results. Dies if no such method was found.

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.12 postfix .*

$invocant.*method calls all methods called method from $invocant, and returns a List of the results. If no such method was found, an empty List is returned.

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.13 postfix ». / postfix >>.

Hyper method call operator. Will call a method on all elements of a List out of order and return the list of return values in order.

    my @a = &lt;a b c>;
    @a».say;                          # a␤b␤c␤
    my @b = @a».ord;                  # [97, 98, 99]
    sub foo(Str:D $c){ $c.ord * 2 };  # The first parameter of a method is the invocant.
    say @a».&amp;foo;                     # So we can pretend to have a method call with a sub that got a good first positional argument.
    say @a».&amp;({ .ord});               # Blocks have an implicit positional arguments that lands in $_. The latter can be omitted for method calls.

## 25.15.14 postfix .postfix / .postcircumfix

In most cases, a dot may be placed before a postfix or postcircumfix:

    @a[1, 2, 3];
    @a.[1, 2, 3]; # Same

This can be useful for visual clarity or brevity. For example, if an object's attribute is a function, putting a pair of parentheses after the attribute name will become part of the method call. So either two pairs of parentheses must be used, or a dot has to come before the parentheses to separate it from the method call.

    class Operation {
        has $.symbol;
        has &amp;.function;
    }
    my $addition = Operation.new(:symbol&lt;+>, :function{ $^a + $^b });
    say $addition.function()(1, 2); # 3
    # OR
    say $addition.function.(1, 2); # 3

If the postfix is an identifier, however, it will be interpreted as a normal method call.

    1.i # No such method 'i' for invocant of type 'Int'

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.15 postfix .:<prefix>

A prefix can be called like a method using colonpair notation. For example:

    my $a = 1;
    say ++$a;     # 2
    say $a.:&lt;++>; # 3

Technically this is not an operator, but syntax special-cased in the compiler.

## 25.15.16 postfix .::

A class-qualified method call, used to call a method as defined in a parent class or role, even after it has been redefined in the child class.

    class Bar {
        method baz { 42 }
    }
    class Foo is Bar {
        method baz { "nope" }
    }
    say Foo.Bar::baz; # 42

# 25.16 Autoincrement Precedence

## 25.16.1 prefix ++

    multi sub prefix:&lt;++>($x is rw) is assoc&lt;none>

Increments its argument by one, and returns the incremented value.

    my $x = 3;
    say ++$x;       # 4
    say $x;         # 4

It works by calling the succ method (for successor) on its argument, which gives custom types the freedom to implement their own increment semantics.

## 25.16.2 prefix --

    multi sub prefix:&lt;-->($x is rw) is assoc&lt;none>

Decrements its argument by one, and returns the decremented value.

    my $x = 3;
    say --$x;       # 2
    say $x;         # 2

It works by calling the pred method (for predecessor) on its argument, which gives custom types the freedom to implement their own decrement semantics.

## 25.16.3 postfix ++

    multi sub postfix:&lt;++>($x is rw) is assoc&lt;none>

Increments its argument by one, and returns the unincremented value.

    my $x = 3;
    say $x++;       # 3
    say $x;         # 4

It works by calling the succ method (for successor) on its argument, which gives custom types the freedom to implement their own incrementation semantics.

Note that this does not necessarily return its argument. For example for undefined values, it returns 0:

    my $x;
    say $x++;       # 0
    say $x;         # 1

## 25.16.4 postfix --

    multi sub postfix:&lt;-->($x is rw) is assoc&lt;none>

Decrements its argument by one, and returns the undecremented value.

    my $x = 3;
    say $x--;       # 3
    say $x;         # 2

It works by calling the pred method (for predecessor) on its argument, which gives custom types the freedom to implement their own decrementation semantics.

Note that this does not necessarily return its argument. For example for undefined values, it returns 0:

    my $x;
    say $x--;       # 0
    say $x;         # -1

# 25.17 Exponentiation Precedence

## 25.17.1 infix **

    multi sub infix:&lt;**>(Any, Any) returns Numeric:D is assoc&lt;right>

The exponentiation operator coerces both arguments to Numeric and calculates the left-hand-side raised to the power of the right-hand side.

If the right-hand side is a non-negative integer and the left-hand side is an arbitrary precision type (Int, FatRat), then the calculation is carried out without loss of precision.

# 25.18 Symbolic Unary Precedence

## 25.18.1 prefix ?

    multi sub prefix:&lt;?>(Mu) returns Bool:D

Boolean context operator.

Coerces the argument to Bool by calling the Bool method on it. Note that this collapses Junctions.

## 25.18.2 prefix !

    multi sub prefix:&lt;!>(Mu) returns Bool:D

Negated boolean context operator.

Coerces the argument to Bool by calling the Bool method on it, and returns the negation of the result. Note that this collapses Junctions.

## 25.18.3 prefix +

    multi sub prefix:&lt;+>(Any) returns Numeric:D

Numeric context operator.

Coerces the argument to Numeric by calling the Numeric method on it.

## 25.18.4 prefix -

    multi sub prefix:&lt;->(Any) returns Numeric:D

Negative numeric context operator.

Coerces the argument to Numeric by calling the Numeric method on it, and then negates the result.

## 25.18.5 prefix ~

    multi sub prefix:&lt;~>(Any) returns Str:D

String context operator.

Coerces the argument to Str by calling the Str method on it.

## 25.18.6 prefix |

Flattens objects of type Capture, Pair, List Map and Hash into an argument list.

Outside of argument lists, it returns a Slip, which makes it flatten into the outer list. Inside argument list Positional s are turned into positional arguments and Associative s are turned into named arguments.

## 25.18.7 prefix +^

    multi sub prefix:&lt;+^>(Any) returns Int:D

Integer bitwise negation operator.

Coerces the argument to Int and does a bitwise negation on the result, assuming two's complement.

## 25.18.8 prefix ?^

    multi sub prefix:&lt;?^>(Mu) returns Bool:D

Boolean bitwise negation operator.

Coerces the argument to Bool and then does a bit flip, which makes it the same as prefix:<!> .

## 25.18.9 prefix ^

    multi sub prefix:&lt;^>(Any) returns Range:D

upto operator.

Coerces the argument to Numeric, and generates a range from 0 up to (but excluding) the argument.

    say ^5;         # 0..^5
    for ^5 { }      # 5 iterations

# 25.19 Multiplicative Precedence

## 25.19.1 infix *

    multi sub infix:&lt;*>(Any, Any) returns Numeric:D

Multiplication operator.

Coerces both arguments to Numeric and multiplies them. The result is of the wider type. See Numeric for details.

## 25.19.2 infix /

    multi sub infix:&lt;/>(Any, Any) returns Numeric:D

Division operator.

Coerces both argument to Numeric and divides the left through the right number. Division of Int values returns Rat, otherwise the "wider type" rule described in Numeric holds.

## 25.19.3 infix div

    multi sub infix:&lt;div>(Int:D, Int:D) returns Int:D

Integer division operator. Rounds down.

## 25.19.4 infix %

    multi sub infix:&lt;%>($x, $y) return Numeric:D

Modulo operator. Coerces to Numeric first.

Generally the following identity holds:

    $x % $y == $x - floor($x / $y) * $y

## 25.19.5 infix %%

    multi sub infix:&lt;%%>($a, $b) returns Bool:D

Divisibility operator. Returns True if $a % $b == 0.

## 25.19.6 infix mod

    multi sub infix:&lt;mod>(Int:D $a, Int:D $b) returns Int:D

Integer modulo operator. Returns the remainder of an integer modulo operation.

## 25.19.7 infix +&

    multi sub infix:&lt;+&amp;>($a, $b) returns Int:D

Numeric bitwise AND operator. Coerces both arguments to Int and does a bitwise AND operation assuming two's complement.

## 25.19.8 infix +<

    multi sub infix:&lt;&lt; +&lt; >>($a, $b) returns Int:D

Integer bit shift to the left.

## 25.19.9 infix +>

    multi sub infix:&lt;&lt; +> >>($a, $b) returns Int:D

Integer bit shift to the right.

## 25.19.10 infix gcd

    multi sub infix:&lt;gcd>($a, $b) returns Int:D

Coerces both arguments to Int and returns the greatest common divisor.

## 25.19.11 infix lcm

    multi sub infix:&lt;lcm>($a, $b) returns Int:D

Coerces both arguments to Int and returns the least common multiple, that is the smallest integer that is evenly divisible by both arguments.

# 25.20 Additive Precedence

## 25.20.1 infix +

    multi sub infix:&lt;+>($a, $b) returns Numeric:D

Addition operator.

Coerces both arguments to Numeric and adds them.

## 25.20.2 infix -

    multi sub infix:&lt;->($a, $b) returns Numeric:D

Subtraction operator.

Coerces both arguments to Numeric and subtracts the second from the first.

## 25.20.3 infix +|

    multi sub infix:&lt;+|>($a, $b) returns Int:D

Integer bitwise OR operator.

Coerces both arguments to Int and does a bitwise OR (inclusive OR) operation.

## 25.20.4 infix +^

    multi sub infix:&lt;+^>($a, $b) returns Int:D

Integer bitwise XOR operator.

Coerces both arguments to Int and does a bitwise XOR (exclusive OR) operation.

## 25.20.5 infix ?|

    multi sub infix:&lt;?|>($a, $b) returns Bool:D

Boolean logical OR operator.

Coerces both arguments to Bool and does a logical OR (inclusive OR) operation.

# 25.21 Replication Precedence

## 25.21.1 infix x

    proto sub infix:&lt;x>(Any, Any) returns Str:D
    multi sub infix:&lt;x>(Any, Any)
    multi sub infix:&lt;x>(Str:D, Int:D)

String repetition operator.

Coerces $a to Str and $b to Int and repeats the string $b times. Return the empty string if $b <= 0 .

    say 'ab' x 3;       # ababab
    say 42 x 3;         # 424242

## 25.21.2 infix xx

    multi sub infix:&lt;xx>($a, $b) returns List:D

List repetition operator.

Returns a list of $a repeated and evaluated $b times ($b is coerced to Int). If $b <= 0 , the empty list is returned.

The left-hand side is evaluated for each repetition, so

    [1, 2] xx 5

returns five distinct arrays (but with the same content each time), and

    rand xx 3

returns three pseudo random numbers that are determined independently.

The right-hand side can be *, in which case a lazy, infinite list is returned.

# 25.22 Concatenation

## 25.22.1 infix ~

    proto sub infix:&lt;~>(Any, Any) returns Str:D
    multi sub infix:&lt;~>(Any,   Any)
    multi sub infix:&lt;~>(Str:D, Str:D)

String concatenation operator.

Coerces both arguments to Str and concatenates them.

    say 'ab' ~ 'c';     # abc

# 25.23 Junctive AND (all) Precedence

## 25.23.1 infix &

    multi sub infix:&lt;&amp;>($a, $b) returns Junction:D is assoc&lt;list>

All junction operator.

Creates an all Junction from its arguments. See Junction for more details.

# 25.24 Junctive OR (any) Precedence

## 25.24.1 infix |

    multi sub infix:&lt;|>($a, $b) returns Junction:D is assoc&lt;list>

Any junction operator.

Creates an any Junction from its arguments. See Junction for more details.

## 25.24.2 infix ^

    multi sub infix:&lt;^>($a, $b) returns Junction:D is assoc&lt;list>

One junction operator.

Creates a one Junction from its arguments. See Junction for more details.

# 25.25 Named Unary Precedence

## 25.25.1 prefix temp

    sub prefix:&lt;temp>(Mu $a is rw)

"temporizes" the variable passed as the argument, which means it is reset to its old value on scope exit. (This is similar to the local operator in Perl 5, except that temp does not reset the value).

## 25.25.2 prefix let

    sub prefix:&lt;let>(Mu $a is rw)

Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.

    my $answer = 42;

    {
        let $answer = 84;
        die if not Bool.pick;
        CATCH {
            default { say "it's been reset :(" }
        }
        say "we made it 84 sticks!";
    }

    say $answer;

In the above case, if the Bool.pick returns true, the answer will stay as 84 because the block returns a defined value (say returns true). Otherwise the die statement will cause the block to exit unsuccessfully, resetting the answer to 42.

this is duplicated in variables.pod

# 25.26 Nonchaining Binary Precedence

## 25.26.1 infix does

    sub infix:&lt;does>(Mu $obj, Mu $role) is assoc&lt;none>

Mixes $role into $obj at run time. Requires $obj to be mutable.

$role doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.

## 25.26.2 infix but

    sub infix:&lt;but>(Mu $obj, Mu $role) is assoc&lt;none>

Creates a copy of $obj with $role mixed in. Since $obj is not modified, but can be used to created immutable values with mixins.

$role doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.

## 25.26.3 infix cmp

    proto sub infix:&lt;cmp>(Any, Any) returns Order:D is assoc&lt;none>
    multi sub infix:&lt;cmp>(Any,       Any)
    multi sub infix:&lt;cmp>(Real:D,    Real:D)
    multi sub infix:&lt;cmp>(Str:D,     Str:D)
    multi sub infix:&lt;cmp>(Version:D, Version:D)

Generic, "smart" three-way comparator.

Compares strings with string semantics, numbers with number semantics, Pair objects first by key and then by value etc.

if $a eqv $b, then $a cmp $b always returns Order::Same.

    say (a => 3) cmp (a => 4);      # Less
    say 4        cmp 4.0;           # Same
    say 'b'      cmp 'a';           # More

## 25.26.4 infix leg

    proto sub infix:&lt;leg>($a, $b) returns Order:D is assoc&lt;none>
    multi sub infix:&lt;leg>(Any,   Any)
    multi sub infix:&lt;leg>(Str:D, Str:D)

String three-way comparator. Short for less, equal or greater?.

Coerces both arguments to Str, and then does a lexicographic comparison.

    say 'a' leg 'b';        Less
    say 'a' leg 'a';        Same
    say 'b' leg 'a';        More

## 25.26.5 infix <=>

    multi sub infix:«&lt;=>»($a, $b) returns Order:D is assoc&lt;none>

Numeric three-way comparator.

Coerces both arguments to Real, and then does a numeric comparison.

## 25.26.6 infix ..

    multi sub infix:&lt;..>($a, $b) returns Range:D is assoc&lt;none>

Range operator

Constructs a Range from the arguments.

## 25.26.7 infix ..^

    multi sub infix:&lt;..^>($a, $b) returns Range:D is assoc&lt;none>

Right-open range operator.

Constructs a Range from the arguments, excluding the end point.

## 25.26.8 infix ^..

    multi sub infix:&lt;^..>($a, $b) returns Range:D is assoc&lt;none>

Left-open range operator.

Constructs a Range from the arguments, excluding the start point.

## 25.26.9 infix ^..^

    multi sub infix:&lt;^..^>($a, $b) returns Range:D is assoc&lt;none>

Open range operator

Constructs a Range from the arguments, excluding both start and end point.

# 25.27 Chaining Binary Precedence

## 25.27.1 infix ==

    proto sub infix:&lt;==>($, $) returns Bool:D is assoc:&lt;chain>
    multi sub infix:&lt;==>(Any, Any)
    multi sub infix:&lt;==>(Int:D, Int:D)
    multi sub infix:&lt;==>(Num:D, Num:D)
    multi sub infix:&lt;==>(Rational:D, Rational:D)
    multi sub infix:&lt;==>(Real:D, Real:D)
    multi sub infix:&lt;==>(Complex:D, Complex:D)
    multi sub infix:&lt;==>(Numeric:D, Numeric:D)

Numeric equality operator.

Coerces both arguments to Numeric if necessary, and returns True if they are equal.

## 25.27.2 infix !=

    proto sub infix:&lt;!=>(Mu, Mu) returns Bool:D is assoc&lt;chain>

Numeric inequality operator.

Coerces both arguments to Numeric (if necessary), and returns True if they are distinct.

## 25.27.3 infix <

    proto sub infix:«&lt;»(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:«&lt;»(Int:D, Int:D)
    multi sub infix:«&lt;»(Num:D, Num:D)
    multi sub infix:«&lt;»(Real:D, Real:D)

Numeric less than operator.

Coerces both arguments to Real (if necessary), and returns True if the first argument is smaller than the second.

## 25.27.4 infix <=

    proto sub infix:«&lt;=»(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:«&lt;=»(Int:D, Int:D)
    multi sub infix:«&lt;=»(Num:D, Num:D)
    multi sub infix:«&lt;=»(Real:D, Real:D)

Numeric less than or equal to operator.

Coerces both arguments to Real (if necessary), and returns True if the first argument is smaller than or equal to the second.

## 25.27.5 infix >

    proto sub infix:«>»(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:«>»(Int:D, Int:D)
    multi sub infix:«>»(Num:D, Num:D)
    multi sub infix:«>»(Real:D, Real:D)

Numeric greater than operator.

Coerces both arguments to Real (if necessary), and returns True if the first argument is larger than the second.

## 25.27.6 infix >=

    proto sub infix:«>=»(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:«>=»(Int:D, Int:D)
    multi sub infix:«>=»(Num:D, Num:D)
    multi sub infix:«>=»(Real:D, Real:D)

Numeric less than or equal to operator.

Coerces both arguments to Real (if necessary), and returns True if the first argument is larger than or equal to the second.

## 25.27.7 infix eq

    proto sub infix:&lt;eq>(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;eq>(Any,   Any)
    multi sub infix:&lt;eq>(Str:D, Str:D)

String equality operator.

Coerces both arguments to Str (if necessary), and returns True if both are equal.

Mnemonic: equal

## 25.27.8 infix ne

    proto sub infix:&lt;ne>(Mu, Mu) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;ne>(Mu,    Mu)
    multi sub infix:&lt;ne>(Str:D, Str:D)

String inequality operator.

Coerces both arguments to Str (if necessary), and returns False if both are equal.

Mnemonic: not equal

## 25.27.9 infix gt

    proto sub infix:&lt;gt>(Mu, Mu) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;gt>(Mu,    Mu)
    multi sub infix:&lt;gt>(Str:D, Str:D)

String greater than operator.

Coerces both arguments to Str (if necessary), and returns True if the first is larger than the second, as determined by lexicographic comparison.

Mnemonic: greater than

## 25.27.10 infix ge

    proto sub infix:&lt;ge>(Mu, Mu) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;ge>(Mu,    Mu)
    multi sub infix:&lt;ge>(Str:D, Str:D)

String greater than or equal to operator.

Coerces both arguments to Str (if necessary), and returns True if the first is equal to or larger than the second, as determined by lexicographic comparison.

Mnemonic: greater or equal

## 25.27.11 infix lt

    proto sub infix:&lt;lt>(Mu, Mu) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;lt>(Mu,    Mu)
    multi sub infix:&lt;lt>(Str:D, Str:D)

String less than operator.

Coerces both arguments to Str (if necessary), and returns True if the first is smaller than the second, as determined by lexicographic comparison.

Mnemonic: less than

## 25.27.12 infix le

    proto sub infix:&lt;le>(Mu, Mu) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;le>(Mu,    Mu)
    multi sub infix:&lt;le>(Str:D, Str:D)

String less than or equal to operator.

Coerces both arguments to Str (if necessary), and returns True if the first is equal to or smaller than the second, as determined by lexicographic comparison.

Mnemonic: less or equal

## 25.27.13 infix before

    proto sub infix:&lt;before>(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;before>(Any,       Any)
    multi sub infix:&lt;before>(Real:D,    Real:D)
    multi sub infix:&lt;before>(Str:D,     Str:D)
    multi sub infix:&lt;before>(Version:D, Version:D)

Generic ordering, uses the same semantics as cmp. Returns True if the first argument is smaller than the second.

## 25.27.14 infix after

    proto sub infix:&lt;after>(Any, Any) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;after>(Any,       Any)
    multi sub infix:&lt;after>(Real:D,    Real:D)
    multi sub infix:&lt;after>(Str:D,     Str:D)
    multi sub infix:&lt;after>(Version:D, Version:D)

Generic ordering, uses the same semantics as cmp. Returns True if the first argument is larger than the second.

## 25.27.15 infix eqv

    proto sub infix:&lt;eqv>(Any, Any) returns Bool:D is assoc&lt;chain>
    proto sub infix:&lt;eqv>(Any, Any)

Equivalence operator. Returns True if the two arguments are structurally the same, i.e. from the same type and (recursively) contain the same values.

    say [1, 2, 3] eqv [1, 2, 3];        # True
    say Any eqv Any;                    # True
    say 1 eqv 2;                        # False
    say 1 eqv 1.0;                      # False

For arbitrary objects this is not possible with the default eqv operator. E.g., eqv will not consider two instances of the same object as being structurally equivalent:

    class A {
        has $.a;
    }
    say A.new(a => 5) eqv A.new(a => 5);  #=> False

To get eqv semantics for objects of this class, one would need to implement an appropriate infix eqv operator:

    class A {
        has $.a;
    }
    multi infix:&lt;eqv>(A $l, A $r) { $l.a eqv $r.a }
    say A.new(a => 5) eqv A.new(a => 5);  #=> True

## 25.27.16 infix ===

    proto sub infix:&lt;===>(Any, Any) returns Bool:D is assoc&lt;chain>
    proto sub infix:&lt;===>(Any, Any)

Value identity operator. Returns True if both arguments are the same object.

    class A { };
    my $a = A.new;
    say $a === $a;              # True
    say A.new === A.new;        # False
    say A === A;                # True

For value types, === behaves like eqv:

    say 'a' === 'a';            # True
    say 'a' === 'b';            # False

    # different types
    say 1 === 1.0;              # False

=== uses the WHICH method to obtain the object identity, so all value types must override method WHICH.

## 25.27.17 infix =:=

    proto sub infix:&lt;=:=>(Mu \a, Mu \b) returns Bool:D is assoc&lt;chain>
    multi sub infix:&lt;=:=>(Mu \a, Mu \b)

Container identity operator. Returns True if both arguments are bound to the same container. If it returns True, it generally means that modifying one will also modify the other.

    my ($a, $b) = (1, 3);
    say $a =:= $b;      # False
    $b = 2;
    say $a;             # 1
    $b := $a;
    say $a =:= $b;      # True
    $a = 5;
    say $b;             # 5

## 25.27.18 infix ~~

The smart-match operator. Aliases the left-hand side to $_, then evaluates the right-hand side, and calls .ACCEPTS($_) on it. The semantics are left to the type of the right-hand side operand.

Here is an excerpt of built-in smart-matching functionality:

Right-hand side | Comparison semantics
--- | ---
Mu:U | type check
Str | string equality
Numeric | numeric equality
Regex | regex match
Callable | boolean result of invocation
Any:D | object identity

## 25.27.19 infix =~=

    proto sub infix:&lt;=~=>($, $) returns Bool:D is assoc:&lt;chain>
    multi sub infix:&lt;=~=>(Any, Any)
    multi sub infix:&lt;=~=>(Int:D, Int:D)
    multi sub infix:&lt;=~=>(Num:D, Num:D)
    multi sub infix:&lt;=~=>(Rational:D, Rational:D)
    multi sub infix:&lt;=~=>(Real:D, Real:D)
    multi sub infix:&lt;=~=>(Complex:D, Complex:D)
    multi sub infix:&lt;=~=>(Numeric:D, Numeric:D)

The approximately-equal operator. Calculates the relative difference between the left-hand and right-hand sides and returns True if the difference is less than $*TOLERANCE (which defaults to 1e-15). However, if either side is zero then it checks that the absolute difference between the sides is less than $*TOLERANCE. Note that this operator is not arithmetically symmetrical (doesn't do ± Δ):

    say ($x + $*TOLERANCE) =~= $x;   # True
    say ($x - $*TOLERANCE) =~= $x;   # False

The tolerance is supposed to be modifiable via an adverb:

    say $x =~= $y :tolerance(.1);

however, this is not yet implemented. The same effect can be achieved by assigning to $*TOLERANCE.

    {
        my $*TOLERANCE = .1;
        say 11 =~= 10;               # True
    }

Note that setting $*TOLERANCE = 0 will cause all comparisons to fail.

    {
        my $*TOLERANCE = 0;
        say 1 =~= 1;                 # False
    }

# 25.28 Tight AND Precedence

## 25.28.1 infix &&

Returns the first argument that evaluates to False in boolean context, or otherwise the last argument.

Note that this short-circuits, i.e. if one of the arguments evaluates to a false value, the arguments to the right of are never evaluated.

    sub a { 1 }
    sub b { 0 }
    sub c { die "never called" };
    say a() &amp;&amp; b() &amp;&amp; c();      # 0

# 25.29 Tight OR Precedence

## 25.29.1 infix ||

Returns the first argument that evaluates to True in boolean context, or otherwise the last argument.

Note that this short-circuits, i.e. if one of the arguments evaluates to a true value, the arguments to the right of are never evaluated.

    sub a { 0 }
    sub b { 1 }
    sub c { die "never called" };
    say a() || b() || c();      # 1

## 25.29.2 infix ^^

Returns the first true argument if there is only one, and Nil otherwise. Short-circuits as soon as two true arguments are found.

    say 0 ^^ 42;                # 42
    say 0 ^^ 42 ^^ 1 ^^ die 8;  # (empty line)

Note that the semantics of this operator may not be what you assume: infix ^^ flips to first true value it finds, and then flips to Nil forever after the second, no matter how many more true values there are. (In other words, it has "find the one true value" semantics, not "boolean parity" semantics.)

## 25.29.3 infix //

Defined-or operator. Returns the first defined operand, or else the last operand. Short-circuits.

    say Any // 0 // 42;         # 0

## 25.29.4 infix min

Returns the smallest of the arguments, as determined by cmp semantics.

    $foo min= 0  # read as: $foo decreases to 0

## 25.29.5 infix max

Returns the largest of the arguments, as determined by cmp semantics.

    $foo max= 0  # read as: $foo increases to 0

# 25.30 Conditional Operator Precedence

## 25.30.1 infix ?? !!

Ternary operator, conditional operator.

$condition ?? $true !! $false evaluates and returns the expression from the $true branch if $condition is a true value. Otherwise it evaluates and returns the $false branch.

## 25.30.2 infix ff

    sub infix:&lt;ff>(Mu $a, Mu $b)

Flipflop operator.

Compares both arguments to $_ (that is, $_ ~~ $a and $_ ~~ $b). Evaluates to False until the left-hand smartmatch is True, at which point it evaluates to True until the right-hand smartmatch is True.

In effect, the left-hand argument is the "start" condition, and the right-hand is the "stop" condition. This construct is typically used to pick up only a certain section of lines. For example:

        my $excerpt = q:to/END/;
         Here's some unimportant text.
         =begin code
             This code block is what we're after.
             We'll use 'ff' to get it.
         =end code
         More unimportant text.
         END

         my @codelines = gather for $excerpt.lines {
             take $_ if  <b>"=begin code" ff "=end code"</b>
         }

         # this will print four lines, starting with "=begin code" and ending with
         # "=end code"
         say @codelines.join("\n");

After matching the start condition, the operator will then match the same $_ to the stop condition, and act accordingly if successful. In this example, only the first element is printed:

    for &lt;AB C D B E F> {
        say $_ if /A/ ff /B/;  # prints only "AB"
    }

If you only want to test against a start condition, and have no stop condition, * can be used as the "stop" condition.

    for &lt;A B C D E> {
        say $_ if /C/ ff *; # prints C, D, and E
    }

For the sed-like version, which does not try $_ on the stop condition after succeeding on the start condition, see fff .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.3 infix ^ff

    sub infix:&lt;^ff>(Mu $a, Mu $b)

Works like ff , except it does not return True for items matching the start condition (including items also matching the stop condition).

A comparison:

    my @list = &lt;A B C>;
    say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ ^ff /C/ for @list; # prints B and C

The sed-like version can be found in ^fff .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.4 infix ff^

    sub infix:&lt;ff^>(Mu $a, Mu $b)

Works like ff , except it does not return True for items matching the stop condition (including items that first matched the start condition).

    my @list = &lt;A B C>;
    say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ ff^ /C/ for @list; # prints A and B

The sed-like version can be found in fff^ .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.5 infix ^ff^

    sub infix:&lt;^ff^>(Mu $a, Mu $b)

Works like ff , except it does not return True for items matching either the stop or start condition (or both).

    my @list = &lt;A B C>;
    say $_ if /A/ ff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ ^ff^ /C/ for @list; # prints B

The sed-like version can be found in ^fff^ .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.6 infix fff

    sub infix:&lt;fff>(Mu $a, Mu $b)

Performs a sed-like flipflop operation, wherein it returns False until the left argument smartmatches against $_, and after that returns True until the right argument smartmatches against $_.

Works similarly to ff , except that it only tries one argument per invocation. That is, if $_ smartmatches the left argument, fff will not then try to match that same $_ against the right argument.

    for &lt;AB C D B E F> {
        say $_ if /A/ fff /B/;  # Prints "AB", "C", "D", and "B"
    }

The non-sed-like flipflop (which after successfully matching the left argument against $_ will try that same $_ against the right argument and act accordingly), see ff .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.7 infix ^fff

    sub infix:&lt;^fff>(Mu $a, Mu $b)

Like fff , except it does not return true for matches to the left argument.

    my @list = &lt;A B C>;
    say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ ^fff /C/ for @list; # prints B and C

For the non-sed version, see ^ff .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.8 infix fff^

    sub infix:&lt;fff^>(Mu $a, Mu $b)

Like fff , except it does not return true for matches to the right argument.

    my @list = &lt;A B C>;
    say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ fff^ /C/ for @list; # prints A and B

For the non-sed version, see ff^ .

This operator cannot be overloaded, as it is handled specially by the compiler.

## 25.30.9 infix ^fff^

    sub infix:&lt;^fff^>(Mu $a, Mu $b)

Like fff , except it does not return true for matches to either the left or right argument.

    my @list = &lt;A B C>;
    say $_ if /A/ fff /C/ for @list;  # prints A, B, and C
    say $_ if /A/ ^fff^ /C/ for @list; # prints B

For the non-sed version, see ^ff^ .

This operator cannot be overloaded, as it is handled specially by the compiler.

# 25.31 Item Assignment Precedence

## 25.31.1 infix =

    sub infix:&lt;=>(Mu $a is rw, Mu $b)

Item assignment operator.

Places the value of the right-hand side into the container on the left-hand side. Its exact semantics are left to the container type on the left-hand side.

(Note that item assignment and list assignment have different precedence levels, and the syntax of the left-hand side decides whether an equal sign = is parsed as item assignment or list assignment operator).

## 25.31.2 infix =>

    sub infix:«=>»($key, Mu $value) returns Pair:D

Pair constructor.

Constructs a Pair object with the left-hand side as the key and the right-hand side as the value.

Note that the => operator is syntactically special-cased, in that it allows unquoted identifier on the left-hand side.

    my $p = a => 1;
    say $p.key;         # a
    say $p.value;       # 1

A Pair within an argument list with an unquoted identifier on the left is interpreted as a named argument.

See the Terms language documentation for more ways to create Pair objects.

# 25.32 Loose Unary Precedence

## 25.32.1 prefix not

    multi sub prefix:&lt;not>(Mu $x) returns Bool:D

Evaluates its argument in boolean context (and thus collapses Junctions), and negates the result. Please note that not is easy to misuse, see traps.

## 25.32.2 prefix so

    multi sub prefix:&lt;so>(Mu $x) returns Bool:D

Evaluates its argument in boolean context (and thus collapses Junctions), and returns the result.

# 25.33 Comma Operator Precedence

## 25.33.1 infix ,

    sub infix:&lt;,>(*@a) is assoc&lt;list> returns List:D

Constructs a List from its arguments. Also used syntactically as the separator of arguments in calls.

## 25.33.2 infix :

Used as an argument separator just like infix , and marks the argument to its left as the invocant. That turns what would otherwise be a function call into a method call.

    substr('abc': 1);       # same as 'abc'.substr(1)

Infix : is only allowed after the first argument of a non-method call. In other positions it is a syntax error.

# 25.34 List Infix Precedence

## 25.34.1 infix Z

    sub infix:&lt;Z>(**@lists) returns List:D is assoc&lt;chain>

Zip operator.

Interleaves the lists passed to Z like a zipper, stopping as soon as the first input list is exhausted:

    say (1, 2 Z &lt;a b c> Z &lt;+ ->).perl;  #=> ((1, "a", "+"), (2, "b", "-")).Seq

The Z operator also exists as a meta operator, in which case the inner lists are replaced by the value from applying the meta'ed operator to the list:

    say 100, 200 Z+ 42, 23;             #=> (142 223)
    say 1..3 Z~ &lt;a b c> Z~ 'x' xx 3;    #=> (1ax 2bx 3cx)

## 25.34.2 infix X

    sub infix:&lt;X>(**@lists) returns List:D is assoc&lt;chain>

Creates a cross product from all the lists, order so that the rightmost elements vary most rapidly:

    1..3 X &lt;a b c> X 9
    # produces ((1 a 9) (1 b 9) (1 c 9)
    #           (2 a 9) (2 b 9) (2 c 9)
    #           (3 a 9) (3 b 9) (3 c 9))

The X operator also exists as a meta operator, in which case the inner lists are replaced by the value from applying the meta'ed operator to the list:

    1..3 X~ &lt;a b c> X~ 9
    # produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)

## 25.34.3 infix ...

    multi sub infix:&lt;...>(**@) is assoc&lt;list>
    multi sub infix:&lt;...^>(**@) is assoc&lt;list>

The sequence operator is a generic operator to produce lazy lists.

It can have initial elements and a generator on left-hand side, and an endpoint on the right-hand side.

The sequence operator invokes the generator with as many arguments as necessary. The arguments are taken from the initial elements and the already generated elements.

The default generator is *.succ or *.pred, depending on how the end points compare:

    say 1 ... 4;        # 1 2 3 4
    say 4 ... 1;        # 4 3 2 1
    say 'a' ... 'e';    # a b c d e
    say 'e' ... 'a';    # e d c b a

An endpoint of * (Whatever) generates an infinite sequence, with a default generator of *.succ

    say (1 ... *)[^5];  # 1 2 3 4 5

Custom generators are the last argument before the '...' operator. This one takes two arguments, and generates the Fibonacci numbers

    say (1, 1, -> $a, $b { $a + $b } ... *)[^8];    # 1 1 2 3 5 8 13 21
    # same but shorter
    say (1, 1, *+* ... *)[^8];                      # 1 1 2 3 5 8 13 21

Of course the generator can also take only one argument.

    say 5, { $_ * 2 } ... 40;                       # 5 10 20 40

There must be at least as many initial elements as arguments to the generator.

Without a generator, and more than one initial element, and all initial elements numeric, the sequence operator tries to deduce the generator. It knows about arithmetic and geometric sequences.

    say 2, 4, 6 ... 12;     # 2 4 6 8 10 12
    say 1, 2, 4 ... 32;     # 1 2 4 8 16 32

If the endpoint is not *, it is smart-matched against each generated element, and the sequence is terminated when the smart-match succeeded. For the ... operator, the final element is included, for the ...^ operator it is excluded.

This allows you to write

    say 1, 1, *+* ...^ *>= 100;

To generate all Fibonacci numbers up to but excluding 100.

The ... operators consider the initial values as "generated elements" as well, so the are also checked against the endpoint:

    my $end = 4;
    say 1, 2, 4, 8, 16 ... $end;
    # outputs 1 2 4

# 25.35 List Prefix Precedence

## 25.35.1 infix =

List assignment operator. Its exact semantics are left to the container type on the left-hand side. See Array and Hash for common cases.

The distinction between item assignment and list assignment is determined by the parser depending on the syntax of the left-hand side.

## 25.35.2 infix :=

Binding operator. Whereas $x = $y puts the value in $y into $x, $x := $y makes $x and $y the same thing.

        my $a = 42;
         my $b  <b>=</b>  $a;
         $b <a href="++">++</a> ;
         say $a;

This will output 42, because $a and $b both contained the number 42, but the containers were different.

        my $a = 42;
         my $b  <b>:=</b>  $a;
         $b <a href="++">++</a> ;
         say $a;

This will output 43, since $b and $a both represented the same object.

## 25.35.3 infix ::=

Read-only binding operator. See infix := .

## 25.35.4 listop ...

The yada, yada, yada operator or stub operator. If it is the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the ... statement is executed, it calls fail, with the default message stub code executed.

## 25.35.5 listop !!!

Fatal stub operator.

If it is the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the !!! statement is executed, it calls die, with the default message stub code executed.

## 25.35.6 listop ???

Admonitory stub operator.

If it is the only statement in a routine or type, it marks that routine or type as a stub (which is significant in the context of pre-declaring types and composing roles).

If the ??? statement is executed, it calls warn, with the default message stub code executed.

## 25.35.7 Reduction operators

Any infix operator (except for non-associating operators) can be surrounded by square brackets in term position to create a list operator that reduces using that operation.

        [+] 1, 2, 3;      # 1 + 2 + 3 = 6
         my @a = (5, 6);
         [*] @a;           # 5 * 6 = 30

Reduction operators have the same associativity as the operators they are based on.

        [-] 4, 3, 2;      # 4-3-2 = (4-3)-2 = -1
         [**] 4, 3, 2;     # 4**3**2 = 4**(3**2) = 262144

# 25.36 Loose AND precedence

## 25.36.1 infix and

Same as #infix &&, except with looser precedence.

Returns the first operand that evaluates to False in boolean context, or otherwise the last operand, it short-circuits. Please note that and is easy to misuse, see traps.

## 25.36.2 infix andthen

Returns the first undefined argument, otherwise the last argument. Short-circuits. The result of the left side is bound to $_ for the right side, or passed as arguments if the right side is a block or pointy block.

# 25.37 Loose OR Precedence

## 25.37.1 infix or

Same as infix ||, except with looser precedence.

Returns the first argument that evaluates to True in boolean context, or otherwise the last argument, it short-circuits. Please note that or is easy to misuse, see traps.

## 25.37.2 infix orelse

Same as infix //, except with looser precedence.

Returns the first defined argument, or else the last argument. Short-circuits.

# 25.38 Sequencer Precedence

## 25.38.1 infix ==>

This feed operator takes the result from the left and passes it to the next (right) routine as the last parameter.

The precedence is very loose so you will need to use parentheses to assign the result or you can even just use another feed operator! In the case of routines/methods that take a single argument or where the first argument is a block, it is often required that you call with parentheses (though this is not required for the very last routine/method).

    # Traditional structure, read bottom-to-top
    my @result =
        sort               # (4) Sort, result is &lt;Earth People>
        grep { /&lt;[PE]>/ }, # (3) Look for P or E
        map { .tc },       # (2) Capitalize the words
        &lt;people of earth>; # (1) Start with the input

    # Feed (left-to-right) with parentheses, read top-to-bottom
    my @result = (
        &lt;people of earth>  # (1) Start with the input
        ==> map({ .tc })   # (2) Capitalize the words
        ==> grep /&lt;[PE]>/  # (3) Look for P or E
        ==> sort           # (4) Sort, result is &lt;Earth People>
    );

    # For illustration, method chaining equivalent, read top-to-bottom
    my @result =
        &lt;people of earth>  # (1) Start with the input
        .map({ .tc })      # (2) Capitalize the words
        .grep(/&lt;[PE]>/)    # (3) Look for P or E
        .sort;             # (4) Sort, result is &lt;Earth People>

    # To assign without the need of parentheses use another feed operator
    &lt;people of earth>
        ==> map({ .tc })
        ==> grep /&lt;[PE]>/
        ==> sort()
        ==> my @result;

    # It can be useful to capture a partial result, however, unlike
    # the leftward feed operator, it does require parentheses or a semicolon
    &lt;people of earth>
        ==> map({ .tc })
        ==> my @caps; @caps # also could wrap in parentheses instead
        ==> grep /&lt;[PE]>/
        ==> sort()
        ==> my @result;

The feed operator lets you construct method-chaining-like patterns out of routines and the results of methods on unrelated data. In method-chaining, you are restricted to the methods available on the data or the result of previous method call. With feed operators, that restriction is gone. The resulting code could also be seen to be more readable than a series of method calls broken over multiple lines.

Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the left operand is enclosable as a closure (that can be cloned and run in a subthread).

## 25.38.2 infix <==

This leftward feed operator takes the result from the right and passes it to the previous (left) routine as the last parameter. This elucidates the right-to-left dataflow for a series of list manipulating functions.

    # Traditional structure, read bottom-to-top
    my @result =
        sort                   # (4) Sort, result is &lt;Earth People>
        grep { /&lt;[PE]>/ },     # (3) Look for P or E
        map { .tc },           # (2) Capitalize the words
        &lt;people of earth>;     # (1) Start with the input

    # Feed (right-to-left) with parentheses, read bottom-to-top
    my @result = (
        sort()                 # (4) Sort, result is &lt;Earth People>
        &lt;== grep({ /&lt;[PE]>/ }) # (3) Look for P or E
        &lt;== map({ .tc })       # (2) Capitalize the words
        &lt;== &lt;people of earth>  # (1) Start with the input
    );

    # To assign without parentheses, use another feed operator
    my @result
        &lt;== sort()             # (4) Sort, result is &lt;Earth People>
        &lt;== grep({ /&lt;[PE]>/ }) # (3) Look for P or E
        &lt;== map({ .tc })       # (2) Capitalize the words
        &lt;== &lt;people of earth>; # (1) Start with the input

    # It can be useful to capture a partial result
    my @result
        &lt;== sort()
        &lt;== grep({ /&lt;[PE]>/ })
        &lt;== my @caps # unlike ==>, there is no need for additional statement
        &lt;== map({ .tc })
        &lt;== &lt;people of earth>;

Unlike the rightward feed operator, the result is not closely mappable to method-chaining. However, compared to the traditional structure above where each argument is separated by a line, the resulting code is more demonstrative than commas. The leftward feed operator also allows you to "break into" the statement and capture an intermediary result which can be extremely useful for debugging or to take that result and create another variation on the final result.

Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the right operand is enclosable as a closure (that can be cloned and run in a subthread).

# 26 Packages

Organizing and referencing namespaced program elements

* Take a lot of stuff from S02 for this * Document 'import'

Packages are nested namespaces of named program elements. Modules, classes, grammars, and others are types of packages. Like files in a directory, you can generally refer to named elements with their short-name if they are local, or with a longer name to disambiguate.

# 26.1 Names

A name is anything that is a legal part of a variable name (not counting the sigil). This includes:

    $foo                # simple identifiers
    $Foo::Bar::baz      # compound identifiers separated by ::
    $Foo::($bar)::baz   # compound identifiers that perform interpolations
    $42                 # numeric names
    $!                  # certain punctuational variables

:: is used to separate nested package names.

## 26.1.1 Package-qualified names

Ordinary package-qualified names look like:

    $Foo::Bar::baz      # the $baz variable in package Foo::Bar

Sometimes it's clearer to keep the sigil with the variable name, so an alternate way to write this is:

    Foo::Bar::&lt;$baz>

This is resolved at compile time because the variable name is a constant.

If the name part before :: is null, it means the package is unspecified and must be searched for. Generally this means that an initial :: following the main sigil is a no-op on names that are known at compile time, though ::() can also be used to introduce an interpolation. Also, in the absence of another sigil, :: can serve as its own sigil indicating intentional use of a not-yet-declared package name.

# 26.2 Pseudo-packages

The following pseudo-package names are reserved at the front of a name:

    MY          # Symbols in the current lexical scope (aka $?SCOPE)
    OUR         # Symbols in the current package (aka $?PACKAGE)
    CORE        # Outermost lexical scope, definition of standard Perl
    GLOBAL      # Interpreter-wide package symbols, really UNIT::GLOBAL
    PROCESS     # Process-related globals (superglobals)
    COMPILING   # Lexical symbols in the scope being compiled

The following relative names are also reserved but may be used anywhere in a name:

    CALLER      # Contextual symbols in the immediate caller's lexical scope
    CALLERS     # Contextual symbols in any caller's lexical scope
    DYNAMIC     # Contextual symbols in my or any caller's lexical scope
    OUTER       # Symbols in the next outer lexical scope
    OUTERS      # Symbols in any outer lexical scope
    LEXICAL     # Contextual symbols in my or any outer's lexical scope
    UNIT        # Symbols in the outermost lexical scope of compilation unit
    SETTING     # Lexical symbols in the unit's DSL (usually CORE)
    PARENT      # Symbols in this package's parent package (or lexical scope)
    CLIENT      # The nearest CALLER that comes from a different package

The file's scope is known as UNIT, but there are one or more lexical scopes outside of that corresponding to the linguistic setting (often known as the prelude in other cultures). Hence, the SETTING scope is equivalent to UNIT::OUTERS. For a standard Perl program SETTING is the same as CORE, but various startup options (such as -n or -p) can put you into a domain specific language, in which case CORE remains the scope of the standard language, while SETTING represents the scope defining the DSL that functions as the setting of the current file. When used as a search term in the middle of a name, SETTING includes all its outer scopes up to CORE. To get only the setting's outermost scope, use UNIT::OUTER instead.

# 26.3 Looking up names

## 26.3.1 Interpolating into names

You may interpolate a string into a package or variable name using ::($expr) where you'd ordinarily put a package or variable name. The string is allowed to contain additional instances of ::, which will be interpreted as package nesting. You may only interpolate entire names, since the construct starts with ::, and either ends immediately or is continued with another :: outside the parens. Most symbolic references are done with this notation:

    $foo = "Bar";
    $foobar = "Foo::Bar";
    $::($foo)           # lexically-scoped $Bar
    $::("MY::$foo")     # lexically-scoped $Bar
    $::("OUR::$foo")    # package-scoped $Bar
    $::("GLOBAL::$foo") # global $Bar
    $::("PROCESS::$foo")# process $Bar
    $::("PARENT::$foo") # current package's parent's $Bar
    $::($foobar)        # $Foo::Bar
    $::($foobar)::baz   # $Foo::Bar::baz
    $::($foo)::Bar::baz # $Bar::Bar::baz
    $::($foobar)baz     # ILLEGAL at compile time (no operator baz)

An initial :: doesn't imply global. Here as part of the interpolation syntax it doesn't even imply package. After the interpolation of the ::() component, the indirect name is looked up exactly as if it had been there in the original source code, with priority given first to leading pseudo-package names, then to names in the lexical scope (searching scopes outwards, ending at CORE). The current package is searched last.

Use the MY pseudopackage to limit the lookup to the current lexical scope, and OUR to limit the scopes to the current package scope.

## 26.3.2 Direct lookup

To do direct lookup in a package's symbol table without scanning, treat the package name as a hash:

    Foo::Bar::{'&amp;baz'}  # same as &amp;Foo::Bar::baz
    PROCESS::&lt;$IN>      # Same as $*IN
    Foo::&lt;::Bar>&lt;::Baz> # same as Foo::Bar::Baz

Unlike ::() symbolic references, this does not parse the argument for ::, nor does it initiate a namespace scan from that initial point. In addition, for constant subscripts, it is guaranteed to resolve the symbol at compile time.

The null pseudo-package is the same search list as an ordinary name search. That is, the following are all identical in meaning:

    $foo
    $::{'foo'}
    ::{'$foo'}
    $::&lt;foo>
    ::&lt;$foo>

Each of them scans lexical scopes outward, and then the current package scope (though the package scope is then disallowed when "strict" is in effect).

As a result of these rules, you can write any arbitrary variable name as either of:

    $::{'!@#$#@'}
    ::{'$!@#$#@'}

You can also use the ::<> form as long as there are no spaces in the name.

## 26.3.3 Package lookup

Subscript the package object itself as a hash object, the key of which is the variable name, including any sigil. The package object can be derived from a type name by use of the :: postfix:

    MyType::&lt;$foo>

# 26.4 Globals

Interpreter globals live in the GLOBAL package. The user's program starts in the GLOBAL package, so "our" declarations in the mainline code go into that package by default. Process-wide variables live in the PROCESS package. Most predefined globals such as $*UID and $*PID are actually process globals.

# 26.5 Version

Any package may have a Version object attached to it. This object can be accessed via $?PACKAGE.^ver or from outside the package Fully::Qualified::Name.^ver.

# 27 Performance

Measuring and improving run-time or compile-time performance

This page is about anything to do with computer performance in the context of Perl 6.

# 27.1 First, clarify the problem

Make sure you're not wasting time on the wrong code: start by identifying your "critical 3%" by "profiling" as explained below.

## 27.1.1 Time with now - INIT now

Expressions of the form now - INIT now, where INIT is a phase in the running of a Perl 6 program, provide a great idiom for timing code snippets.

Use the m: your code goes here #perl6 channel evalbot to write lines like:

    m: say now - INIT now
    rakudo-moar 8bd7ee: OUTPUT«0.0018558␤»

The now to the left of INIT runs 0.0018558 seconds later than the now to the right of the INIT because the latter occurs during the INIT phase.

## 27.1.2 Profile with prof-m: your code goes here

Enter prof-m: your code goes here in the #perl6 channel to invoke a Perl 6 compiler with a --profile option. The evalbot's output includes a link to profile info:

        yournick prof-m: say 'hello world'
         camelia  prof-m 273e89: OUTPUT«hello world␤...»
                  .. Prof:  <a href="http://p.p6c.org/20f9e25">http://p.p6c.org/20f9e25</a>

Click on the profile info link to see a profile for say 'hello world'.

To learn how to interpret the profile info, ask questions on channel.

## 27.1.3 Profile locally

When using the MoarVM backend the Rakudo compiler's --profile command line option writes profile information as an HTML file.

To learn how to interpret the profile info, use the prof-m: your code goes here evalbot (explained above) and ask questions on channel.

## 27.1.4 Profile compiling

The Rakudo compiler's --profile-compile option profiles the time and memory used to compile code.

## 27.1.5 Create or view benchmarks

Use perl6-bench.

If you run perl6-bench for multiple compilers (typically versions of Perl 5, Perl 6, or NQP) then results for each are visually overlaid on the same graphs to provide for quick and easy comparison.

## 27.1.6 Share problems

Once you've used the above techniques to pinpoint code and performance that really matters you're in a good place to share problems, one at a time:

- For each problem you see, distill it down to a one-liner or short public gist of code that either already includes performance numbers or is small enough that it can be profiled using prof-m: your code or gist URL goes here.

- Think about the minimum speed increase (or ram reduction or whatever) you need/want. What if it took a month for folk to help you achieve that? A year?

- Let folk know if your Perl 6 use-case is in a production setting or just for fun.

# 27.2 Solve problems

This bears repeating: make sure you're not wasting time on the wrong code. Start by identifying the "critical 3%" of your code.

## 27.2.1 Line by line

A quick, fun, productive way to try improve code line-by-line is to collaborate with others using the #perl6 evalbot camelia.

## 27.2.2 Routine by routine

With multidispatch you can drop in new variants of routines "alongside" existing ones:

    # existing code generically matches a two arg foo call:
    multi sub foo(Any $a, Any $b) { ... }

    # new variant takes over for a foo("quux", 42) call:
    multi sub foo("quux", Int $b) { ... }

The call overhead of having multiple foo definitions is generally insignificant (though see discussion of where below), so if your new definition handles its particular case more quickly/leanly than the previously existing set of definitions then you probably just made your code that much faster/leaner for that case.

## 27.2.3 Speed up type-checks and call resolution

Most where clauses -- and thus most subsets -- force dynamic (run-time) type checking and call resolution for any call it might match. This is slower, or at least later, than compile-time.

Method calls are generally resolved as late as possible, so dynamically, at run-time, whereas sub calls are generally resolvable statically, at compile-time.

## 27.2.4 Choose better algorithms

One of the most reliable techniques for making large performance improvements regardless of language or compiler is to pick an algorithm better suited to your needs.

A classic example is Boyer-Moore. To match a small string in a large string, one obvious way to do it is to compare the first character of the two strings and then, if they match, compare the second characters, or, if they don't match, compare the first character of the small string with the second character in the large string, and so on. In contrast, the Boyer-Moore algorithm starts by comparing the *last* character of the small string with the correspondingly positioned character in the large string. For most strings the Boyer-Moore algorithm is close to N times faster algorithmically, where N is the length of the small string.

The next couple sections discuss two broad categories for algorithmic improvement that are especially easy to accomplish in Perl 6. For more on this general topic, read the wikipedia page on algorithmic efficiency, especially the See also section near the end.

### 27.2.4.1 Change sequential/blocking code to parallel/non-blocking

This is another very important class of algorithmic improvement.

See the slides for Parallelism, Concurrency, and Asynchrony in Perl 6 and/or the matching video.

## 27.2.5 Use existing high performance code

Is there an existing high (enough) performance implementation of what you're trying to speed up / slim down?

There are a lot of C libs out there. NativeCall makes it easy to create wrappers for C libs (there's experimental support for C++ libs too) such as Gumbo. (Data marshalling and call handling is somewhat poorly optimized at the time of writing this but for many applications that won't matter.)

Perl 5's compiler can be treated as a C lib. Mix in Perl 6 types, the MOP, and some hairy programming that someone else has done for you, and the upshot is that you can conveniently use Perl 5 modules in Perl 6.

More generally, Perl 6 is designed for smooth interop with other languages and there are a number of modules aimed at providing convenient use of libs from other langs.

## 27.2.6 Make the Rakudo compiler generate faster code

The focus to date (Feb 2016) regarding the compiler has been correctness, not how fast it generates code or, more importantly, how fast or lean the code it generates runs. But that's expected to change somewhat this year and beyond. You can talk to compiler devs on the freenode IRC channels #perl6 and #moarvm about what to expect. Better still you can contribute yourself:

- Rakudo is largely written in Perl 6. So if you can write Perl 6, then you can hack on the compiler, including optimizing any of the large body of existing high-level code that impacts the speed of your code (and everyone else's).

- Most of the rest of the compiler is written in a small language called NQP that's basically a subset of Perl 6. If you can write Perl 6 you can fairly easily learn to use and improve the mid-level NQP code too, at least from a pure language point of view. To dig in to NQP and Rakudo's guts, start with NQP and internals course.

- If low-level C hacking is your idea of fun, checkout MoarVM and visit the freenode IRC channel #moarvm (logs).

## 27.2.7 Still need more ideas?

There are endless performance topics.

Some known current Rakudo performance weaknesses not yet covered in this page include use of gather/take, use of junctions, regexes, and string handling in general.

If you think some topic needs more coverage on this page please submit a PR or tell someone your idea. Thanks. :)

# 27.3 Not getting the results you need/want?

If you've tried everything on this page to no avail, please consider discussing things with a compiler dev on #perl6 so we can learn from your use-case and what you've found out about it so far.

Once you know one of the main devs knows of your plight, allow enough time for an informed response (a few days or weeks depending on the exact nature of your problem and potential solutions).

If that hasn't worked out either, please consider filing an issue discussing your experience at our user experience repo before moving on. Thanks. :)

# 28 Phasers

Program execution phases and corresponding phaser blocks

The lifetime (execution timeline) of a program is broken up into phases. A phaser is a block of code called during a specific execution phase.

# 28.1 Phasers

A phaser block is just a trait of the closure containing it, and is automatically called at the appropriate moment. These auto-called blocks are known as phasers, since they generally mark the transition from one phase of computing to another. For instance, a CHECK block is called at the end of compiling a compilation unit. Other kinds of phasers can be installed as well; these are automatically called at various times as appropriate, and some of them respond to various control exceptions and exit values.

Here is a summary:

    BEGIN {...} #  * at compile time, ASAP, only ever runs once
    CHECK {...} #  * at compile time, ALAP, only ever runs once
     LINK {...} #  * at link time, ALAP, only ever runs once
     INIT {...} #  * at run time, ASAP, only ever runs once
      END {...} #  at run time, ALAP, only ever runs once

    ENTER {...} #  * at every block entry time, repeats on loop blocks.
    LEAVE {...} #  at every block exit time (even stack unwinds from exceptions)
     KEEP {...} #  at every successful block exit, part of LEAVE queue
     UNDO {...} #  at every unsuccessful block exit, part of LEAVE queue

    FIRST {...} #  * at loop initialization time, before any ENTER
     NEXT {...} #  at loop continuation time, before any LEAVE
     LAST {...} #  at loop termination time, after any LEAVE

      PRE {...} #  assert precondition at every block entry, before ENTER
     POST {...} #  assert postcondition at every block exit, after LEAVE

    CATCH {...} #  catch exceptions, before LEAVE

    CONTROL {...} #  catch control exceptions, before LEAVE

       LAST {...} #  supply tapped by whenever-block is done, runs very last
       QUIT {...} #  catch async exceptions within a whenever-block, runs very last

    COMPOSE {...} #  when a role is composed into a class

Phasers marked with a * have a run-time value, and if evaluated earlier than their surrounding expression, they simply save their result for use in the expression later when the rest of the expression is evaluated:

    my $compiletime = BEGIN { now };
    our $temphandle = ENTER { maketemp() };

As with other statement prefixes, these value-producing constructs may be placed in front of either a block or a statement:

    my $compiletime = BEGIN now;
    our $temphandle = ENTER maketemp();

Most of these phasers will take either a block or a function reference. The statement form can be particularly useful to expose a lexically scoped declaration to the surrounding lexical scope without "trapping" it inside a block.

These declare the same variables with the same scope as the preceding example, but run the statements as a whole at the indicated time:

    BEGIN my $compiletime = now;
    ENTER our $temphandle = maketemp();

(Note, however, that the value of a variable calculated at compile time may not persist under run-time cloning of any surrounding closure.)

Most of the non-value-producing phasers may also be so used:

    END say my $accumulator;

Note, however, that

    END say my $accumulator = 0;

sets the variable to 0 at END time, since that is when the "my" declaration is actually executed. Only argumentless phasers may use the statement form. This means that CATCH and CONTROL always require a block, since they take an argument that sets $_ to the current topic, so that the innards are able to behave as a switch statement. (If bare statements were allowed, the temporary binding of $_ would leak out past the end of the CATCH or CONTROL, with unpredictable and quite possibly dire consequences. Exception handlers are supposed to reduce uncertainty, not increase it.)

Some of these phasers also have corresponding traits that can be set on variables. These have the advantage of passing the variable in question into the closure as its topic:

    our $h will enter { .rememberit() } will undo { .forgetit() };

Only phasers that can occur multiple times within a block are eligible for this per-variable form.

The topic of the block outside a phaser is still available as OUTER::<$_> . Whether the return value is modifiable may be a policy of the phaser in question. In particular, the return value should not be modified within a POST phaser, but a LEAVE phaser could be more liberal.

Any phaser defined in the lexical scope of a method is a closure that closes over self as well as normal lexicals. (Or equivalently, an implementation may simply turn all such phasers into submethods whose primed invocant is the current object.)

When multiple phasers are scheduled to run at the same moment, the general tiebreaking principle is that initializing phasers execute in order declared, while finalizing phasers execute in the opposite order, because setup and teardown usually want to happen in the opposite order from each other.

## 28.1.1 Execution Order

    Compilation Begins

      BEGIN {...} #  at compile time, ASAP, only ever runs once
      CHECK {...} #  at compile time, ALAP, only ever runs once
       LINK {...} #  at link time, ALAP, only ever runs once
    COMPOSE {...} #  when a role is composed into a class

    Execution Begins

       INIT {...} #  at run time, ASAP, only ever runs once

    Before block execution begins

        PRE {...} #  assert precondition at every block entry, before ENTER

    Loop execution begins

      FIRST {...} #  at loop initialization time, before any ENTER

    Block execution begins

      ENTER {...} #  at every block entry time, repeats on loop blocks.

    Exception maybe happens

      CATCH {...} #  catch exceptions, before LEAVE
    CONTROL {...} #  catch control exceptions, before LEAVE

    End of loop, either continuing or finished

       NEXT {...} #  at loop continuation time, before any LEAVE
       LAST {...} #  at loop termination time, after any LEAVE

    End of block

      LEAVE {...} #  at every block exit time (even stack unwinds from exceptions)
       KEEP {...} #  at every successful block exit, part of LEAVE queue
       UNDO {...} #  at every unsuccessful block exit, part of LEAVE queue

    Postcondition for block

       POST {...} #  assert postcondition at every block exit, after LEAVE

    Async whenever-block is complete

       LAST {...} #  if ended normally with done, runs once after block
       QUIT {...} #  catch async exceptions

    Program terminating

        END {...} #  at run time, ALAP, only ever runs once

# 28.2 Program Execution Phasers

## 28.2.1 BEGIN

Runs at compile time, as soon as possible, only runs once.

Can have a return value that is provided even in later phases.

## 28.2.2 CHECK

Runs at compile time, As late as possible, only runs once.

Can have a return value that is provided even in later phases.

Code that is generated at run time can still fire off CHECK and INIT phasers, though of course those phasers can't do things that would require travel back in time. You need a wormhole for that.

## 28.2.3 LINK

Runs at link time, As late as possible, only runs once.

Can have a return value that is provided even in later phases.

The compiler is free to ignore LINK phasers compiled at run time since they're too late for the application-wide linking decisions.

## 28.2.4 INIT

Runs after compilation during main execution, as soon as possible, only runs once.

Can have a return value that is provided even in later phases.

When phasers are in different modules, the INIT and END phasers are treated as if declared at use time in the using module. (It is erroneous to depend on this order if the module is used more than once, however, since the phasers are only installed the first time they're noticed.)

Code that is generated at run time can still fire off CHECK and INIT phasers, though of course those phasers can't do things that would require travel back in time. You need a wormhole for that.

An INIT only runs once for all copies of a cloned closure.

## 28.2.5 END

Runs after compilation during main execution, as late as possible, only runs once.

When phasers are in different modules, the INIT and END phasers are treated as if declared at use time in the using module. (It is erroneous to depend on this order if the module is used more than once, however, since the phasers are only installed the first time they're noticed.)

# 28.3 Block Phasers

Execution in the context of a block has its own phases.

Block-leaving phasers wait until the call stack is actually unwound to run. Unwinding happens only after some exception handler decides to handle the exception that way. That is, just because an exception is thrown past a stack frame does not mean we have officially left the block yet, since the exception might be resumable. In any case, exception handlers are specified to run within the dynamic scope of the failing code, whether or not the exception is resumable. The stack is unwound and the phasers are called only if an exception is not resumed.

These can occur multiple times within the block. So they aren't really traits, exactly--they add themselves onto a list stored in the actual trait. So if you examine the ENTER trait of a block, you'll find that it's really a list of phasers rather than a single phaser.

All of these phaser blocks can see any previously declared lexical variables, even if those variables have not been elaborated yet when the closure is invoked (in which case the variables evaluate to an undefined value.)

## 28.3.1 ENTER

Runs at every block entry time, repeats on loop blocks.

Can have a return value that is provided even in later phases.

An exception thrown from an ENTER phaser will abort the ENTER queue, but one thrown from a LEAVE phaser will not.

## 28.3.2 LEAVE

Runs at every block exit time (even stack unwinds from exceptions).

So LEAVE phasers for a given block are necessarily evaluated after any CATCH and CONTROL phasers. This includes the LEAVE variants, KEEP and UNDO. POST phasers are evaluated after everything else, to guarantee that even LEAVE phasers can't violate postconditions.

An exception thrown from an ENTER phaser will abort the ENTER queue, but one thrown from a LEAVE phaser will not.

If a POST fails or any kind of LEAVE block throws an exception while the stack is unwinding, the unwinding continues and collects exceptions to be handled. When the unwinding is completed all new exceptions are thrown from that point.

## 28.3.3 KEEP

Runs at every successful block exit, as part of the LEAVE queue (shares the same order of execution).

For phasers such as KEEP and POST that are run when exiting a scope normally, the return value (if any) from that scope is available as the current topic within the phaser.

## 28.3.4 UNDO

Runs at every unsuccessful block exit, as part of the LEAVE queue (shares the same order of execution).

## 28.3.5 PRE

Asserts a precondition at every block entry. Runs before the ENTER phase.

PRE phasers fire off before any ENTER or FIRST.

The exceptions thrown by failing PRE and POST phasers cannot be caught by a CATCH in the same block, which implies that POST phaser are not run if a PRE phaser fails.

## 28.3.6 POST

Asserts a postcondition at every block entry. Runs after the LEAVE phase.

For phasers such as KEEP and POST that are run when exiting a scope normally, the return value (if any) from that scope is available as the current topic within the phaser.

The POST block can be defined in one of two ways. Either the corresponding POST is defined as a separate phaser, in which case PRE and POST share no lexical scope. Alternately, any PRE phaser may define its corresponding POST as an embedded phaser block that closes over the lexical scope of the PRE.

If a POST fails or any kind of LEAVE block throws an exception while the stack is unwinding, the unwinding continues and collects exceptions to be handled. When the unwinding is completed all new exceptions are thrown from that point.

The exceptions thrown by failing PRE and POST phasers cannot be caught by a CATCH in the same block, which implies that POST phaser are not run if a PRE phaser fails.

# 28.4 Loop Phasers

FIRST, NEXT, and LAST are meaningful only within the lexical scope of a loop, and may occur only at the top level of such a loop block.

## 28.4.1 FIRST

Runs at loop initialization, before ENTER.

Can have a return value that is provided even in later phases.

## 28.4.2 NEXT

Runs when loop is continued (either through next or because you got to the bottom of the loop and are looping back around), before LEAVE.

A NEXT executes only if the end of the loop block is reached normally, or an explicit next is executed. In distinction to LEAVE phasers, a NEXT phaser is not executed if the loop block is exited via any exception other than the control exception thrown by next. In particular, a last bypasses evaluation of NEXT phasers.

## 28.4.3 LAST

Runs when loop is aborted (either through last, or return, or because you got to the bottom of the loop and are done), after LEAVE.

# 28.5 Exception Handling Phasers

## 28.5.1 CATCH

Runs when an exception is raised by the current block, before the LEAVE phase.

## 28.5.2 CONTROL

Runs when a control exception is raised by the current block, before the LEAVE phase. It is raised by return, fail, redo, next, last, take, warn, proceed and succeed.

# 28.6 Object Phasers

## 28.6.1 COMPOSE

Runs when a role is composed into a class.

# 28.7 Asynchronous Phasers

## 28.7.1 LAST

Runs when a Supply finishes with a call to done or when a supply block exits normally. It runs completely after the whenever block it is placed within finishes.

This phaser reuses the name LAST, but works differently from the LAST loop phaser. This phaser is similar to setting the done routine while tapping a supply with tap.

## 28.7.2 QUIT

Runs when a Supply terminates early with an exception. It runs after the whenever block it is placed within finishes.

This phaser is similar to setting the quit routine while tapping a Supply with tap.

# 29 Quoting Constructs

Writing strings, word lists, and regexes in Perl 6

# 29.1 The Q Lang

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

## 29.1.1 Literal strings: Q

     <b>Q[</b> A literal string <b>]</b>
      <b>｢</b> More plainly. <b>｣</b>
      <b>Q ^</b> Almost any non-word character can be a delimiter! <b>^</b>

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

    Q&lt;Make sure you  <b>&lt;</b> match <b>></b>  opening and closing delimiters>
     Q{This is still a closing curly brace →  <b>\</b> }

These examples produce:

    A literal string
    More plainly.
    Almost any non-word character can be a delimiter!
    Make sure you &lt;match> opening and closing delimiters
    This is still a closing curly brace → \

The other quote forms add to this basic functionality:

## 29.1.2 Escaping: q

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

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

These examples produce:

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

## 29.1.3 Interpolation: qq

    my $color = 'blue';
      <a href="#_routine_say.pod6">say</a>   <b>"</b> My favorite color is  <b>$color</b> ! <b>"</b>

    My favorite color is blue!

The qq form -- usually written using double quotes -- allows for interpolation of variables, i.e., variables can be written within the string so that the content of the variable is inserted into the string. It is also possible to escape variables within a qq-quoted string:

    say  <b>"</b> The  <b>\</b> $color variable contains the value '$color' <b>"</b> ;

    The $color variable contains the value 'blue'

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

    my ($x, $y, $z) = 4, 3.5, 3;
     say "This room is  <b>$x</b>  m by  <b>$y</b>  m by  <b>$z</b>  m.";
     say "Therefore its volume should be  <b>{ $x * $y * $z }</b>  m³!";

    This room is 4 m by 3.5 m by 3 m.
    Therefore its volume should be 42 m³!

By default, only variables with the $ sigil are interpolated normally. This way, when you write "documentation@perl6.org", you aren't interpolating the @perl6 variable. If that's what you want to do, append a [] to the variable name:

    my @neighbors = "Felix", "Danielle", "Lucinda";
     say "@neighbors <b>[]</b>  and I try our best to coexist peacefully."

    Felix Danielle Lucinda and I try our best to coexist peacefully.

Often a method call is more appropriate. These are allowed within qq quotes as long as they have parentheses after the call. Thus the following code will work:

    say "@neighbors <b>. <a href="#_routine_join.pod6">join</a> (', ')</b>  and I try our best to coexist peacefully."

    Felix, Danielle, Lucinda and I try our best to coexist peacefully.

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

## 29.1.4 Word quoting: qw

     <b>&lt;</b> a b c <b>></b>   <a href="#_routine_eqv.pod6">eqv</a>  ('a', 'b', 'c')
      <b>qw|</b> ! @ # $ % ^ &amp; * \| &lt; >  <b>|</b>  eqv '! @ # $ % ^ &amp; * | &lt; >'.words
      <b>Q:w {</b>  [ ] \{ \}  <b>}</b>  eqv ('[', ']', '{', '}')

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

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

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

It's easier to write and to read this:

    my @directions = &lt;left right up down>;

## 29.1.5 Word quoting with quote protection: qww

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

    say qw{"a b" c}.perl; # ("\"a", "b\"", "c")

Thus, if you wish to preserve quoted sub-strings as single items in the resulting words you need to use the qww variant:

    say qww{"a b" c}.perl; # ("a b", "c")

## 29.1.6 Word quoting with interpolation: qqw

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

    my $a = 42; say qw{$a b c};  # $a b c

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

    my $a = 42;
    my @list = qqw{$a b c};
    say @list;                # 42 b c

Note that variable interpolation happens before word splitting:

    my $a = "a b";
    my @list = qqw{$a c};
    .say for @list; # says "a", says "b", then says "c"

## 29.1.7 Word quoting with interpolation and quote protection: qqww

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

    my $a = 42; say qqw{"$a b" c}.perl; # ("\"42", "b\"", "c")

Thus, if you wish to preserve quoted sub-strings as single items in the resulting words you need to use the qqww variant:

    my $a = 42; say qqww{"$a b" c}.perl; # ("42 b", "c")

or equivalently:

    my $a = 42; say &lt;&lt;"$a b" c>>.perl; # ("42 b", "c")
    my $a = 42; say «"$a b" c».perl; # ("42 b", "c")

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

    my $a = "1 2";
    say qqww{"$a" $a}.perl; # ("1 2", "1", "2")
    my $b = "1 \"2 3\"";
    say qqww{"$b" $b}.perl; # ("1 \"2 3\"", "1", "\"2", "3\"")

## 29.1.8 Shell quoting: qx

To run a string as an external program, not only is it possible to pass the string to the shell or run functions but one can also perform shell quoting in a similar manner to the backticks a.k.a. qx in Perl 5. There are some subtleties to consider, however. The backticks are no longer used for shell quoting in Perl 6 and the qx quotes don't interpolate Perl variables. Thus

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

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

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

will now print hello there.

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

    my $output = qx{echo "hello!"};
    say $output;    # hello!

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

## 29.1.9 Shell quoting with interpolation: qqx

If one wishes to use the content of a Perl variable within an external command, then the qqx shell quoting construct should be used (this corresponds to Perl 5's qx):

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

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

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

See also shell and run for other ways to execute external commands.

## 29.1.10 Heredocs: :to

A convenient way to write multi-line string literals are heredocs, which let you choose the delimiter yourself:

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

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

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

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

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

produces this output:

    Here is
     some multi line
         string

Heredocs include the newline from before the terminator.

# 29.2 Regexes

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

# 30 Perl 6 from Ruby - Nutshell

Learning Perl 6 from Ruby, in a nutshell: What do I already know?

This page attempts to index the high-level differences in syntax and semantics between Ruby and Perl 6. Whatever works in Ruby and must be written differently in Perl 6 should be listed here (whereas many Perl 6 features and idioms won't be).

Hence this should not be mistaken for a beginner tutorial or overview of Perl 6; it is intended as a technical reference for Perl 6 learners with a strong Ruby background.

# 30.1 Basic Syntax

## 30.1.1 Statement Ending Semi-Colons

Ruby detects the end of most statements with a newline (and a few exceptions), as long as the expression is complete. It is common break up a long expression by leaving an operator dangling at the end of a line to ensure that the parsing will continue:

    foo +     # In Ruby a trailing operator means parsing should continue
      bar +
      baz

In Perl 6 you must explicitly terminate statements with a ;, which allows for better feedback and more flexibility in breaking up long lines. Two exceptions not needing an explicit ; are the last statement in a block, and after the closing curley brace of the block itself (if there is nothing else on that line):

    if 5 &lt; $x &lt; 10 {
      say "Yep!";
      $x = 17         # No ; required before closing }
    }                 # No ; required after closing } because of the newline
    say "Done!";      # The ; is not required here if nothing follows

## 30.1.2 Whitespace

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

    # unidiomatic but valid Ruby
    puts"Hello "+
    (people [ i]
        . name
        ) . upcase+"!"if$greeted[i]&lt;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 Ruby, 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 an array variable and its square braces), but there are a few that will unfortunately conflict with some Ruby hackers' habitual coding styles:

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

      foo (3, 4, 1); # Not right in Ruby or Perl 6 (in Perl 6 this would
                     # try to pass a single argument of type List to foo)
      foo(3, 4, 1);  # Ruby and Perl 6
      foo 3, 4, 1;   # Ruby and Perl 6 - alternative parentheses-less style

- Space is required immediately after keywords

      if(a &lt; 0); ...; end         # OK in Ruby
      if ($a &lt; 0) { ... }         # Perl 6
      if $a &lt; 0 { ... }           # Perl 6, more idiomatic

      while(x > 5); ...; end      # OK in Ruby
      while ($x > 5) { ... }      # Perl 6
      while $x > 5 { ... }        # Perl 6, more idiomatic

- No space allowed before a postfix/postcircumfix operator (including array/hash subscripts).

      seen [ :fish ] = 1    # Ruby, not idiomatic but allowed
      %seen&lt; fish > = 1;    # Perl 6, no space allowed after 'seen'

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

      n&lt;1     # Ruby (in Perl 6 this would conflict with postcircumfix &lt; >)
      $n &lt; 1; # Perl 6

## 30.1.3 . Method calls, .send

Method call syntax uses a dot just like Ruby:

    person.name    # Ruby
    $person.name   # Perl 6

To call a method whose name is not known until runtime:

    object.send(methodname, args);  # Ruby
    $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.

## 30.1.4 Variables, Sigils, Scope, and Common Types

In Ruby, variables use sigils primarily to indicate scope. $ for global scope, @@ for class scope, @ for instance scope, and no sigil for local variables (including parameters). The & sigil is also used to indicate method references. Symbols are prefixed with :, but they are not variable and so not really sigils.

In Perl 6 sigils are primarily used to indicate a role that the contained value implements, indicating the type (or at least the interface) of the value. The sigils are invariant, no matter how the variable is being used - you can think of them as part of the variable's name.

The scope of a variable is instead indicated by the declaration itself (my, has, our, etc).

### 30.1.4.1 Variable Scope

For local variables, Ruby uses implicit variable declaration upon assignment and limited to the current block. In Ruby the content of an if or while built-in construct is not a block or scope.

Perl 6 uses explicit scope indicators, and never creates variables implicitly. Every place you see { ... } is a scope, including the body of a conditional or loop. The commonly used scope declarations:

    foo = 7        # Ruby, variable scope is defined by first assignment and
                   # extends to the end of the current block

    my  $foo = 7   # Perl 6, lexical scoped to the current block
    our $foo = 7   # Perl 6, package scoped
    has $!foo = 7  # Perl 6, instance scoped (attribute)

### 30.1.4.2 $ Scalar

The $ sigil is always used with "scalar" variables (e.g. $name). These are single-value containers.

This is the most general-purpose variable type, with no restrictions on its contents. Note that you can still address/use its contents, like $x[1], $x{"foo"}, and $f("foo").

### 30.1.4.3 @ Array

The @ sigil is always used with "array" variables (e.g. @months, @months[2], @months[2, 4] for an array slice). Variables using the @ sigil can only contain things that do the Positional role, indicating positional indexing and slicing capabilities.

- Indexing

      puts months[2]; # Ruby
      say @months[2]; # Perl 6

- Value-slicing

      puts months[8..11].join(',') # Ruby
      say @months[8..11].join(',') # Perl 6

### 30.1.4.4 % Hash

The % sigil is always used with "hash" variables (e.g. %calories, %calories<apple>, %calories<pear plum>). Variables using the % sigil can only contain things that do the Associative role.

Ruby uses square brackets to access values for both Arrays and Hashes. Perl 6 uses curley braces for hashes instead. The angle-brackets version is available which always autoquotes its contents (strings without quotes):

Adverbs can be used to control the type of slice.

- Indexing

      puts calories["apple"]  # Ruby
      say %calories{"apple"}; # Perl 6

      puts calories["apple"]  # Ruby
      puts calories[:apple]   # Ruby, symbols for keys are common
      say %calories&lt;apple>;   # Perl 6 - angle brackets instead of single-quotes
      say %calories«$key»;    # Perl 6 - double angles interpolate as double-quotes

- Value-slicing

      puts calories.values_at('pear', 'plum').join(',') # Ruby
      puts calories.values_at(%w(pear plum)).join(',')  # Ruby, pretty?
      say %calories{'pear', 'plum'}.join(',');          # Perl 6
      say %calories&lt;pear plum>.join(',');               # Perl 6 (prettier)
      my $keys = 'pear plum';
      say %calories«$keys».join(','); # Perl 6, interpolated split

- Key/value-slicing

      say calories.slice('pear', 'plum').join(','); # Ruby, with ActiveRecord
      say %calories{'pear', 'plum'}:kv.join(',');   # Perl 6 - use :kv adverb
      say %calories&lt;pear plum>:kv.join(',');        # Perl 6 (prettier version)

### 30.1.4.5 & Sub

The & sigil is used very similarly to Ruby's & 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". Variables using the & sigil can only contain things that do the Callable role.

    add = -> n, m { n + m } # Ruby lambda for an addition function
    add.(2, 3)              # => 5, Ruby invocation of a lambda
    add.call(2, 3)          # => 5, Ruby invocation of a lambda

    my &amp;add = -> $n, $m { $n + $m } # Perl 6 addition function
    &amp;add(2, 3)                      # => 5, you can keep the sigil
    add(2, 3)                       # => 5, and it works without it

    foo_method = &amp;foo;     # Ruby
    my &amp;foo_method = &amp;foo; # Perl 6

    some_func(&amp;say) # Ruby pass a function reference
    some_func(&amp;say) # Perl 6 passes function references the same way

Often in Ruby we pass a block as the last parameter, which is especially used for DSLs. This can be an implicit parameter called by yield, or an explicit block prefixed with &. In Perl 6 a Callable parameter is always listed and called by the variable name (instead of yield), and there are a variety of ways of invoking the function.

    # Ruby, declare a method and call the implicit block argument
    def f
      yield 2
    end

    # Ruby, invoke f, pass it a block with 1 argument
    f do |n|
      puts "Hi #{n}"
    end

    # Perl 6, declare a method with an explicit block argument
    sub f(&amp;g:($)) {
      g(2)
    }

    # Perl 6, invoke f, pass it a block with 1 argument
    # There are several other ways to do this
    f(-> $n { say "Hi {$n}" }) # Explicit argument
    f -> $n { say "Hi {$n}" }  # Explicit argument, no parenthesis
    f { say "Hi {$^n}" }       # Implicit argument

    # Additionally, if 'f' is a method on instance 'obj' you can use C&lt;:>
    # instead of parenthesis
    obj.f(-> $n { say "Hi {$n}" })  # Explicit argument
    obj.f: -> $n { say "Hi {$n}" }  # Explicit argument, no parenthesis
    obj.f: { say "Hi {$^n}" }       # Implicit argument, no parenthesis

### 30.1.4.6 * Slurpy params / argument expansion

In Ruby you can declare an argument to slurp the remainder of the passed parameters into an array using a * prefix. It works the same way in Perl 6:

    def foo(*args); puts "I got #{args.length} args!"; end # Ruby
    sub foo(*@args) { say "I got #{@args.elems} args!" }   # Perl 6

You might want to expand an array into a set of arguments. In Perl 6 this is also done using the * prefix:

    args = %w(a b c)         # Ruby
    foo(*args)

    my @args = &lt;a b c>       # Perl 6
    foo(*@args)

Perl 6 has many more advanced ways of passing parameters and receiving arguments, see Signatures and Captures.

## 30.1.5 Twigils

Perl 6 additionally uses "twigils", which are further indicators about the variable and go between the sigil and the rest of the variable name. Examples:

    $foo     # Scalar with no twigil
    $!foo    # Private instance variable
    $.foo    # Instance variable accessor
    $*foo    # Dynamically scoped variable
    $^foo    # A positional (placeholder) parameter to a block
    $:foo    # A named parameter
    $=foo    # POD (documentation) variables
    $?FILE   # Current source filename. The ? twigil indicates a compile-time value
    $~foo    # Sublanguage seen by parser, uncommon

Though each of these examples use the $ sigil, most could use @ (Positional) or % (Associative).

## 30.1.6 : Symbols

Perl 6 generally uses strings in the places where Ruby uses symbols. A primary example of this is in hash keys.

    address[:joe][:street] # Typical Ruby nested hash with symbol keys
    %address&lt;joe>&lt;street>  # Typical Perl 6 nested hash with string keys

Perl 6 has colon-pair syntax, which can sometimes look like Ruby symbols.

    :age            # Ruby symbol

    # All of these are equivalent for Perl 6
    :age            # Perl 6 pair with implicit True value
    :age(True)      # Perl 6 pair with explicit True value
    age => True     # Perl 6 pair using arrow notation
    "age" => True   # Perl 6 pair using arrow notation and explicit quotes

You could probably get away with using a colon-pair without an explicit value and pretend that it is a Ruby symbol a lot of the time, but it isn't idomatic Perl 6.

# 30.2 Operators

Many operators have a similar usage in both Ruby and Perl 6:

- , List Separator

- + Numeric Addition

- - Numeric Subtraction

- * Numeric Multiplication

- / Numeric Division

- % Numeric Modulus

- ** Numeric Exponentiation

- ! && || Booleans, high-precedence

- not and or Booleans, low-precedence

You may use $x++ instead of x += 1 as a shortcut for incrementing a variable. This can be used as a pre-increment ++$x (increment, return new value) or post-increment $x++ (increment, return old value).

You may use $x-- instead of x -= 1 as a shortcut for decrementing a variable. This can be used as a pre-decrement --$x (decrement, return new value) or post-decrement $x-- (decrement, return old value).

## 30.2.1 == != < > <= >= Comparisons

Comparisons in Perl 6 are separated between numeric and string to avoid common errors.

- == != < > <= >= Comparisons

- eq ne lt gt le ge String comparisons

For example, using == tries to convert the values to numbers, and eq tries to convert the values to strings.

## 30.2.2 <=> Three-way comparisons

In Ruby, the <=> operator returns -1, 0, or 1. In Perl 6, they return Order::Less, Order::Same, or Order::More.

<=> forces numeric context for the comparison.

leg ("Less, Equal, or Greater?") forces string context for the comparison.

cmp does either <=> or leg, depending on the existing type of its arguments.

## 30.2.3 ~~ Smart-match operator

This is a very common matching operator which doesn't exist in Ruby. Here are some examples:

    say "match!" if $foo ~~ /bar/;      # Regex match
    say "match!" if $foo ~~ "bar";      # String match
    say "match!" if $foo ~~ :(Int, Str) # Signature match (destructure)

See S03/Smart matching

## 30.2.4 & | ^ Numeric Bitwise ops

## 30.2.5 & | ^ Boolean ops

In Perl 6, these 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)
    +&amp;  +|  +^  And Or Xor: Numeric
    ~&amp;  ~|  ~^  And Or Xor: String
    ?&amp;  ?|  ?^  And Or Xor: Boolean

    # Prefix ops (one argument, after the op)
    +^  Not: Numeric
    ~^  Not: String
    ?^  Not: Boolean (same as the ! op)

## 30.2.6 &. Conditional chaining operator

Ruby uses the &. operator to chain methods without raising an error if one invocation returns nil. In Perl 6 use .? for the same purpose.

## 30.2.7 << >> Numeric shift left, right ops, shovel operator

Replaced by +< and +> .

    puts 42 &lt;&lt; 3  # Ruby
    say  42 +&lt; 3; # Perl 6

Note that Ruby often uses the << operator as the "shovel operator", which is similar to .push. This usage isn't common in Perl 6.

## 30.2.8 => and : Key-Value Separators

In Ruby, => is used in the context of key/value pairs for Hash literal declaration and parameter passing. : is used as a shorthand when the left side is a symbol.

In Perl 6, => is the Pair operator, which is quite different in principle, but works the same in many situations.

If you are using => in a hash literal, then the usage is very similar:

    hash = { "AAA" => 1, "BBB" => 2 }  # Ruby, though symbol keys are more common
    my %hash = ( AAA => 1, BBB => 2 ); # Perl 6, uses ()'s though {} usually work

## 30.2.9 ? : Ternary operator

In Perl 6, this is spelled with two question marks instead of one question mark, and two exclamation points instead of one colon. This deviation from the common ternary operators disambiguates several situations and makes the false-case stand out more.

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

## 30.2.10 + String Concatenation

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

    $food = 'grape' + 'fruit'  # Ruby
    $food = 'grape' ~ 'fruit'; # Perl 6

## 30.2.11 String interpolation

In Ruby, "#{foo}s" deliminates a block embedded in a double-quoted string. In Perl 6 drop the # prefix: "{$foo}s". As in Ruby, you can place arbitrary code into the embedded block and it will be rendered in string context.

Simple variables can be interpolated into a double-quoted string without using the block syntax:

    # Ruby
    name = "Bob"
    puts "Hello! My name is #{name}!"

    # Perl 6
    my $name = "Bob"
    say "Hello! My name is $name!"

The result of an embedded block in Ruby uses .to_s to get string context. Perl 6 uses .Str, or .gist for the same affect.

# 30.3 Compound Statements

## 30.3.1 Conditionals

### 30.3.1.1 if elsif else unless

This work very similarly between Ruby and Perl 6, but Perl 6 uses { } to clearly deliniate the blocks.

    # Ruby
    if x > 5
        puts "Bigger!"
    elsif x == 5
        puts "The same!"
    else
        puts "Smaller!"
    end

    # Perl 6
    if x > 5 {
        say "Bigger!"
    } elsif x == 5 {
        puts "The same!"
    } else {
        puts "Smaller!"
    }

Binding the conditional expression to a variable is a little different:

    if x = dostuff(); ...; end   # Ruby
    if dostuff() -> $x {...}     # Perl 6, block-assignment uses arrow

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

### 30.3.1.2 case-when

The Perl 6 given-when construct is like a chain of if-elsif-else statements or like the case-when construct in Ruby. A big difference is that Ruby uses the == comparison for each condition, but Perl 6 uses the more general smart-match ~~ operator.

It has the general structure:

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

In its simplest form, the construct is as follows:

    given $value {
        when "a match" {
            do-something();
        }
        when "another match" {
            do-something-else();
        }
        default {
            do-default-thing();
        }
    }

This is simple in the sense that a scalar value is matched in the when statements. More generally, the matches are actually smart-matches on the input value such that lookups using more complex entities such as regexps can be used instead of scalar values.

## 30.3.2 Loops

### 30.3.2.1 while until

Mostly unchanged; parens around the conditions are 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 x = dostuff(); ...; end    # Ruby
    while dostuff() -> $x {...}      # Perl 6

### 30.3.2.2 for .each

for loops are rare in Ruby, instead we typically use .each on an enumerable. The most direct translation to Perl 6 would be to use .map for both .each and .map, but we typically use a for loop directly.

    # Ruby for loop
    for n in 0..5
        puts "n: #{n}"
    end

    # Ruby, more common usage of .each
    (0..5).each do |n|
        puts "n: #{n}"
    end

    # Perl 6
    for 0..5 -> $n {
        say "n: $n";
    }

    # Perl 6, mis-using .map
    (0..5).map: -> $n {
        say "n: $n";
    }

In Ruby, the iteration variable for .each is a copy of the list element, and modifying it does nothing to the original list. Note that it is a copy of the REFERENCE, so you can still change the values to which it refers.

In Perl 6, that alias is read-only (for safety) and thus behaves exactly like Ruby, unless you change -> to <->.

    cars.each { |car| ... }    # Ruby; read-only referenc
    for @cars  -> $car   {...} # Perl 6; read-only
    for @cars &lt;-> $car   {...} # Perl 6; read-write

## 30.3.3 Flow Interruption statements

Same as Ruby:

- next

- redo

- - break

This is last in Perl 6.

# 30.4 Regular Expressions ( Regex / Regexp )

Regular expressions in Perl 6 are significantly different, and more powerful, than in Ruby. By default whitespace is ignored and all characters must be escaped, for example. Regexes can be easily combined and declared in ways to build efficient grammars.

There are many powerful features of Perl 6 regexes, especially defining entire grammars using the same syntax. See Regexes and Grammars.

## 30.4.1 .match method and =~ operator

In Ruby, regex matches can be done against a variable using the =~ regexp match operator or the .match method. In Perl 6, the ~~ smartmatch op is used instead, or the .match method.

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

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

    next if line.match(/static/)    # Ruby
    next if $line.match(/static/);  # Perl 6

Alternately, the .match and .subst methods can be used. Note that .subst is non-mutating. See S05/Substitution.

## 30.4.2 .sub and .sub!

In Perl 6 you typically use the s/// operator to do regex substitution.

    fixed = line.sub(/foo/, 'bar')        # Ruby, non-mutating
    my $fixed = $line.subst(/foo/, 'bar') # Perl 6, non-mutating

    line.sub!(/foo/, 'bar')   # Ruby, mutating
    $line ~~ s/foo/bar/;      # Perl 6, mutating

## 30.4.3 Regex options

Move any options 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 # Ruby
    next if $line ~~ m:i/static/; # Perl 6

## 30.4.4 Whitespace is ignored, most things must be quoted

In order to aid in readability and reusability, whitespace is not significant in Perl 6 regexes.

    /this is a test/ # Ruby, boring string
    /this.*/         # Ruby, possibly interesting string

    / this " " is " " a " " test / # Perl 6, each space is quoted
    / "this is a test" / # Perl 6, quoting the whole string
    / this .* /          # Perl 6, possibly interesting string

## 30.4.5 Special matchers generally fall under the <> syntax

There are many cases of special matching syntax that Perl 6 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 look-around 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>

(Unrelated to <> syntax, the "lookaround" /foo\Kbar/ becomes /foo <( bar )> /

- (?(?{condition))yes-pattern|no-pattern) becomes [ <?{condition}> yes-pattern | no-pattern ]

## 30.4.6 Longest token matching (LTM) displaces alternation

In Perl 6 regexen, | does Longest Token Match (LTM), which decides which alternation wins an ambiguous match based off of a set of rules, rather than about which was written first in the regex.

To avoid the new logic, change any | in your Ruby regex to a ||.

# 30.5 File-related operations

## 30.5.1 Reading the lines of a text file into an array

Both Ruby and Perl 6 make it easy to read all of the lines in a file into a single variable, and in both cases each line has the newline removed.

    lines = File.readlines("file")   # Ruby
    my @lines = "file".IO.lines;     # Perl 6, create an IO object from a string

## 30.5.2 Iterating over the lines of a text file

Reading the entire file into memory isn't recommended. The .lines method in Perl 6 returns a lazy sequence, but assigning to an array forces the file to be read. It is better to iterate over the results:

    # Ruby
    File.foreach("file") do |line|
        puts line
    end

    # Perl 6
    for "file".IO.lines -> $line {
        say $line
    }

# 30.6 Object Orientation

## 30.6.1 Basic classes, methods, attributes

Classes are defined similarly between Ruby and Perl 6, using the class keyword. Ruby uses def for methods, whereas Perl 6 uses method.

    # Ruby
    class Foo
        def greet(name)
            puts "Hi #{name}!"
        end
    end

    # Perl 6
    class Foo {
        method greet($name) {
            say "Hi $name!"
        }
    }

In Ruby you can use an attribute without declaring it beforehand, and you can tell it is an attribute because of the @ sigil. You can also easily create accessors using attr_accessor and it's variants. In Perl 6 you use a has declaration and a variety of sigils. You can use the ! twigil for private attributes or . to create an accessor.

    # Ruby
    class Person
        attr_accessor :age    # Declare .age as an accessor method for @age
        def initialize
            @name = 'default' # Assign default value to private instance var
        end
    end

    # Perl 6
    class Person
        has $.age;              # Declare $!age and accessor methods
        has $!name = 'default'; # Assign default value to private instance var
    end

Creating a new instance of the class uses the .new method. In Ruby you must manually assign instance variables as needed inside initialize. In Perl 6 you get a default constructor that accepts key/value pairs of accessor attributes, and can do further setup in the BUILD method. Like with Ruby, you can override new itself for more advanced functionality, but this is rare.

    # Ruby
    class Person
        attr_accessor :name, :age
        def initialize(attrs)
            @name = attrs[:name] || 'Jill'
            @age  = attrs[:age] || 42
            @birth_year = Time.now.year - @age
        end
    end
    p = Person.new( name: 'Jack', age: 23 )

    # Perl 6
    class Person
        has $.name = 'Jill';
        has $.age  = 42;
        has $!birth_year;
        method BUILD {
            $!birth_year = now.Date.year - $.age;
        }
    }
    p = Person.new( name => 'Jack', age => 23 )

## 30.6.2 Private Methods

Private methods in Perl 6 are declared with a ! prefixed in their name, and are invoked with a ! instead of a ..

    # Ruby
    class Foo
        def visible
            puts "I can be seen!"
            hidden
        end

        private
        def hidden
            puts "I cannot easily be called!"
        end
    end

    # Perl 6
    class Foo {
        method visible {
            say "I can be seen!"
            self!hidden
        }

        method !hidden {
            say "I cannot easily be called!"
        }
    }

An important note is that in Ruby child objects can see parent private methods (so they are more like "protected" methods in other languages). In Perl 6 child objects cannot call parent private methods.

## 30.6.3 Going Meta

Here are a few examples of meta-programming. Note that Perl 6 separates the meta-methods from the regular methods.

    person = Person.new       # Ruby, create a new person
    my $person = Person.new   # Perl 6, create a new person

    person.class              # Ruby, returns Person (class)
    $person.WHAT              # Perl 6, returns Person (class)

    person.methods            # Ruby
    $person.^methods          # Perl 6, using .^ syntax to access meta-methods

    person.instance_variables # Ruby
    $person.^attributes       # Perl 6

Like Ruby, in Perl 6, everything is an object, but not all operations are equivalent to .send. Many operators are global functions that use typed multi-dispatch (function signatures with types) to decide which implementation to use.

    5.send(:+, 3)    # => 8, Ruby
    &amp;[+](5, 3)       # => 8, Perl 6, reference to infix additon operator

    &amp;[+].^candidates # Perl 6, lists all signatures for the + operator

See Meta-Object Protocol for lots of further details.

# 30.7 Environment variables

## 30.7.1 Perl module library path

In Ruby, one of the environment variables to specify extra search paths for modules is RUBYLIB.

    $ RUBYLIB="/some/module/lib" ruby program.rb

In Perl 6 this is similar, you merely needs to change the name. As you probably guessed, you just need to use PERL6LIB:

    $ PERL6LIB="/some/module/lib" perl6 program.p6

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

    # Ruby and Perl 6
    use lib '/some/module/lib';

# 30.8 Misc.

## 30.8.1 Importing specific functions from a module

In Ruby there is no built-in way to selectively import/export methods from a module.

In Perl 6 you 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; # remainder of the file is in 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 you tries to use baz an "Undeclared routine" error is raised at compile time.

Some modules allow for selectively importing funcitons, which would look like:

    use Bar &lt;foo>; # Import only foo
    foo(1);        #=> "foo 1"
    bar(2);        # Error!

## 30.8.2 OptionParser, parsing command-line flags

Command line argument switch parsing in Perl 6 is done by the parameter list of the MAIN subroutine.

    # Ruby
    require 'optparse'
    options = {}
    OptionParser.new do |opts|
        opts.banner = 'Usage: example.rb --length=abc'
        opts.on("--length", "Set the file") do |length|
            raise "Length must be > 0" unless length.to_i > 0
            options[:length] = length
        end
        opts.on("--filename", "Set the file") do |filename|
            options[:file] = filename
        end
        opts.on("--verbose", "Increase verbosity") do |verbose|
            options[:verbose] = true
        end
    end.parse!

    puts options[:length]
    puts options[:filename]
    puts 'Verbosity ', (options[:verbose] ? 'on' : 'off')

    ruby example.rb --filename=foo --length=42 --verbose
        42
        foo
        Verbosity on

    ruby example.rb --length=abc
        Length must be > 0

    # Perl 6
    sub MAIN ( Int :$length where * > 0, :filename = 'file.dat', Bool :$verbose ) {
        say $length;
        say $data;
        say 'Verbosity ', ($verbose ?? 'on' !! 'off');
    }

    perl6 example.p6 --file=foo --length=42 --verbose
        42
        foo
        Verbosity on
    perl6 example.p6 --length=abc
        Usage:
          c.p6 [--length=&lt;Int>] [--file=&lt;Any>] [--verbose]

Note that Perl 6 auto-generates a full usage message on error in command-line parsing.

# 30.9 RubyGems, External Libraries

See https://modules.perl6.org/, where a growing number of Perl 6 libraries are available along with the tools to manage them.

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.

You can experiment with Inline::Ruby to call existing Ruby code from your Perl 6 programs. This uses an embedded instance of the ruby interpreter to run Ruby code called from your Perl 6 script. Note that this is an EXPERIMENTAL library. You can similarly call other language's libraries with Inline::Perl5, Inline::Python, and others.

# 31 Regexes

Pattern matching against strings

Regular expressions are a computer science concept where simple patterns describe the format of text. Pattern matching is the process of applying these patterns to actual text to look for matches.

Most modern regular expression facilities are more powerful than traditional regular expressions due to the influence of languages such as Perl, but the short-hand term regex has stuck and continues to mean regular expression-like pattern matching.

In Perl 6, although they are capable of much more than regular languages, we continue to call them regexes.

# 31.1 Lexical conventions

Perl 6 has special syntax for writing regexes:

    m/abc/;         # a regex that is immediately matched against $_
    rx/abc/;        # a Regex object
    /abc/;          # a Regex object

The first two can use delimiters other than the slash:

    m{abc};
    rx{abc};

Note that neither the colon : nor round parentheses can be delimiters; the colon is forbidden because it clashes with adverbs, such as rx:i/abc/ (case insensitive regexes), and round parentheses indicate a function call instead.

Whitespace in regexes is generally ignored (except with the :s or :sigspace adverb).

As in the rest of Perl 6, comments in regexes start with a hash character # and go to the end of the current line.

# 31.2 Literals

The simplest case of a regex is a constant string. Matching a string against that regex searches for that string:

    if 'properly' ~~ m/ perl / {
        say "'properly' contains 'perl'";
    }

Alphanumeric characters and the underscore _ are literal matches. All other characters must either be escaped with a backslash (for example \: to match a colon), or included in quotes:

    / 'two words' /     # matches 'two words' including the blank
    / "a:b"       /     # matches 'a:b' including the colon
    / '#' /             # matches a hash character

Strings are searched left to right for the regex, thus it is sufficient if a substring matches the regex:

    if 'abcdef' ~~ / de / {
        say ~$/;            # de
        say $/.prematch;    # abc
        say $/.postmatch;   # f
        say $/.from;        # 3
        say $/.to;          # 5
    };

Match results are stored in the $/ variable and are also returned from the match. The result is of type Match if the match was successful; otherwise it is Nil.

# 31.3 Wildcards and character classes

## 31.3.1 Dot to match any character

An unescaped dot . in a regex matches any single character.

So these all match:

    'perl' ~~ /per./;       # matches the whole string
    'perl' ~~ / per . /;    # the same; whitespace is ignored
    'perl' ~~ / pe.l /;     # the . matches the r
    'speller' ~~ / pe.l/;   # the . matches the first l

This doesn't match:

    'perl' ~~ /. per /

because there is no character to match before per in the target string.

## 31.3.2 Backslashed, predefined character classes

There are predefined character classes of the form \w. Its negation is written with an upper-case letter, \W.

- \d and \D

\d matches a single digit (Unicode property N) and \D matches a single character that is not a digit.

    'ab42' ~~ /\d/ and say ~$/;     # 4
    'ab42' ~~ /\D/ and say ~$/;     # a

Note that not only the Arabic digits (commonly used in the Latin alphabet) match \d, but also digits from other scripts.

Examples for digits are:

    U+0035 5 DIGIT FIVE
    U+07C2 ߂ NKO DIGIT TWO
    U+0E53 ๓ THAI DIGIT THREE
    U+1B56 ᭖ BALINESE DIGIT SIX

- \h and \H

\h matches a single horizontal whitespace character. \H matches a single character that is not a horizontal whitespace character.

Examples for horizontal whitespace characters are

    U+0020 SPACE
    U+00A0 NO-BREAK SPACE
    U+0009 CHARACTER TABULATION
    U+2001 EM QUAD

Vertical whitespace like newline characters are explicitly excluded; those can be matched with \v, and \s matches any kind of whitespace.

- \n and \N

\n matches a single, logical newline character. \n is supposed to also match a Windows CR LF codepoint pair; though it is unclear whether the magic happens at the time that external data is read, or at regex match time. \N matches a single character that's not a logical newline.

- \s and \S

\s matches a single whitespace character. \S matches a single character that is not whitespace.

    if 'contains a word starting with "w"' ~~ / w \S+ / {
        say ~$/;        # word
    }

- \t and \T

\t matches a single tab/tabulation character, U+0009. (Note that exotic tabs like the U+000B VERTICAL TABULATION character are not included here). \T matches a single character that is not a tab.

- \v and \V

\v matches a single vertical whitespace character. \V matches a single character that is not vertical whitespace.

Examples for vertical whitespace characters:

    U+000A LINE FEED
    U+000B VERTICAL TABULATION
    U+000C CARRIAGE RETURN
    U+0085 NEXT LINE
    U+2029 PARAGRAPH SEPARATOR

Use \s to match any kind of whitespace, not just vertical whitespace.

- \w and \W

\w matches a single word character, i.e. a letter (Unicode category L), a digit or an underscore. \W matches a single character that isn't a word character.

Examples of word characters:

    0041 A LATIN CAPITAL LETTER A
    0031 1 DIGIT ONE
    03B4 δ GREEK SMALL LETTER DELTA
    03F3 ϳ GREEK LETTER YOT
    0409 Љ CYRILLIC CAPITAL LETTER LJE

## 31.3.3 Unicode properties

The character classes so far are mostly for convenience; a more systematic approach is the use of Unicode properties. They are called in the form <:property> , where property can be a short or long Unicode property name.

The following list is stolen from the Perl 5 perlunicode documentation:

Short | Long
--- | ---
L | Letter
LC | Cased_Letter
Lu | Uppercase_Letter
Ll | Lowercase_Letter
Lt | Titlecase_Letter
Lm | Modifier_Letter
Lo | Other_Letter
M | Mark
Mn | Nonspacing_Mark
Mc | Spacing_Mark
Me | Enclosing_Mark
N | Number
Nd | Decimal_Number (also Digit)
Nl | Letter_Number
No | Other_Number
P | Punctuation (also punct)
Pc | Connector_Punctuation
Pd | Dash_Punctuation
Ps | Open_Punctuation
Pe | Close_Punctuation
Pi | Initial_Punctuation
| (may behave like Ps or Pe depending on usage)
Pf | Final_Punctuation
| (may behave like Ps or Pe depending on usage)
Po | Other_Punctuation
S | Symbol
Sm | Math_Symbol
Sc | Currency_Symbol
Sk | Modifier_Symbol
So | Other_Symbol
Z | Separator
Zs | Space_Separator
Zl | Line_Separator
Zp | Paragraph_Separator
C | Other
Cc | Control (also cntrl)
Cf | Format
Cs | Surrogate
Co | Private_Use
Cn | Unassigned

For example <:Lu> matches a single, upper-case letter.

Negation works as <:!category> , so <:!Lu> matches a single character that isn't an upper-case letter.

Several categories can be combined with one of these infix operators:

Operator | Meaning
--- | ---
+ | set union
| | set union
& | set intersection
- | set difference (first minus second)
^ | symmetric set intersection / XOR

So, to match either a lower-case letter or a number, one can write <:Ll+:N> or <:Ll+:Number> or <+ :Lowercase_Letter + :Number> .

It is also possible to group categories and sets of categories with parentheses, e.g.:

    'perl6' ~~ m{\w+(&lt;:Ll+:N>)}  # 0 => ｢6｣

## 31.3.4 Enumerated character classes and ranges

Sometimes the pre-existing wildcards and character classes are not enough. Fortunately, defining your own is fairly simple. Between <[ ]> , you can put any number of single characters and ranges of characters (expressed with two dots between the end points), with or without whitespace.

    "abacabadabacaba" ~~ / &lt;[ a .. c 1 2 3 ]> /

Between the < > you can also use the same operators for categories (+, |, &, -, ^) to combine multiple range definitions and even mix in some of the unicode categories above. You are also allowed to write the backslashed forms for character classes between the [ ] .

    / &lt;[\d] - [13579]> /
    # not quite the same as
    / &lt;[02468]> /
    # because the first one also contains "weird" unicodey digits

To negate a character class, put a - after the opening angle:

    say 'no quotes' ~~ /  &lt;-[ " ]> + /;  # matches characters except "

A common pattern for parsing quote-delimited strings involves negated character classes:

    say '"in quotes"' ~~ / '"' &lt;-[ " ]> * '"'/;

This first matches a quote, then any characters that aren't quotes, and then a quote again. The meaning of * and + in the examples above are explained in section Quantifier.

Just as you can use the - for both set difference and negation of a single value, you can also explicitly put a + in front:

    / &lt;+[123]> /  # same as &lt;[123]>

# 31.4 Quantifiers

A quantifier makes a preceding atom match not exactly once, but rather a variable number of times. For example a+ matches one or more a characters.

Quantifiers bind tighter than concatenation, so ab+ matches one a followed by one or more bs. This is different for quotes, so 'ab'+ matches the strings ab, abab, ababab etc.

## 31.4.1 One or more: +

The + quantifier makes the preceding atom match one or more times, with no upper limit.

For example to match strings of the form key=value, you can write a regex like this:

    / \w+ '=' \w+ /

## 31.4.2 Zero or more: *

The * quantifier makes the preceding atom match zero or more times, with no upper limit.

For example to allow optional whitespace between a and b you can write

    / a \s* b /

## 31.4.3 Zero or one match: ?

The ? quantifier makes the preceding atom match zero or once.

## 31.4.4 General quantifier: ** min..max

To quantify an atom an arbitrary number of times, you can write e.g. a ** 2..5 to match the character a at least twice and at most 5 times.

        say so 'a' ~~ /a ** 2..5/;        # False
         say so  'aaa' ~~ /a ** 2..5/;     # True

If the minimal and maximal number of matches are the same, a single integer is possible: a ** 5 matches a exactly five times.

        say so 'aaaaa' ~~ /a ** 5/;       # True

It is also possible to use non inclusive ranges using a caret:

        say so 'a'    ~~ /a ** 1^..^6/;   # False
         say so 'aaaa' ~~ /a ** 1^..^6/;   # True

This includes the numeric ranges starting from 0:

        say so 'aaa' ~~ /a ** ^6/;        # True

or a Whatever operator for an infinite range with a non inclusive minimum:

        say so 'aaaa' ~~ /a ** 1^..*/;    # True

## 31.4.5 Modified quantifier: %

To more easily match things like comma separated values, you can tack on a % modifier to any of the above quantifiers to specify a separator that must occur between each of the matches. So, for example a+ % ',' will match a or a,a or a,a,a or so on, but it will not match a, or a,a,. To match those as well, you may use %% instead of %.

## 31.4.6 Greedy versus frugal quantifiers: ?

By default, quantifiers request a greedy match:

        'abababa' ~~ /a .* a/ &amp;&amp; say ~$/;  # abababa

You can attach a ? modifier to the quantifier to enable frugal matching:

        'abababa' ~~ /a .*? a/ &amp;&amp; say ~$/; # aba

You can also explicitly request greedy matching with the ! modifier.

## 31.4.7 Preventing backtracking: :

You can prevent backtracking in regexes by attaching a : modifier to the quantifier:

        say so 'abababa' ~~ /a .* aba/   # True
         say so 'abababa' ~~ /a .*: aba/  # False

# 31.5 Alternation

To match one of several possible alternatives, separate them by ||; the first matching alternative wins.

For example, ini files have the following form:

    [section]
    key = value

Hence, if you parse a single line of an ini file, it can be either a section or a key-value pair and the regex would be (to a first approximation):

    / '[' \w+ ']' || \S+ \s* '=' \s* \S* /

That is, either a word surrounded by square brackets, or a string of non-whitespace characters, followed by zero or more spaces, followed by the equals sign =, followed again by optional whitespace, followed by another string of non-whitespace characters.

# 31.6 Longest Alternation

In regexes branches separated by |, the longest match wins, independent of the lexical ordering in the regexes.

    say ('abc' ~~ / a | .b /).Str;    # ab

# 31.7 Anchors

The regex engine tries to find a match inside a string by searching from left to right.

    say so 'properly' ~~ / perl/;     # True
    #          ^^^^

But sometimes this is not what you want. For instance, you might want to match the whole string, or a whole line, or one or several whole words. Anchors or assertions can help you with this by limiting where they match.

Anchors need to match successfully in order for the whole regex to match but they do not use up characters while matching.

## 31.7.1 ^ , Start of String and $ , End of String

The ^ assertion only matches at the start of the string:

    say so 'properly' ~~ /  perl/;    # True
    say so 'properly' ~~ /^ perl/;    # False
    say so 'perly'    ~~ /^ perl/;    # True
    say so 'perl'     ~~ /^ perl/;    # True

The $ assertion only matches at the end of the string:

    say so 'use perl' ~~ /  perl  /;  # True
    say so 'use perl' ~~ /  perl $/;  # True
    say so 'perly'    ~~ /  perl $/;  # False

You can, of course, combine both anchors:

    say so 'use perl' ~~ /^ perl $/;  # False
    say so 'perl'     ~~ /^ perl $/;  # True

Keep in mind, these anchors match end of string, not line:

    my $str = q:to/EOS/;
       Keep it secret
       and keep it safe
       EOS

    say so $s ~~ /safe   $/;          # True
    say so $s ~~ /secret $/;          # False
    say so $s ~~ /^Keep   /;          # True
    say so $s ~~ /^and    /;          # False

## 31.7.2 ^^ , Start of Line and $$ , End of Line

The ^^ assertion matches at the start of a logical line. That is, either at the start of the string, or after a newline character.

$$ matches only at the end of a logical line, that is, before a newline character, or at the end of the string when the last character is not a newline character.

(To understand the following example, it is important to know that the q:to/EOS/...EOS "heredoc" syntax removes leading indention to the same level as the EOS marker, so that the first, second and last lines have no leading space and the third and fourth lines have two leading spaces each).

        my $str = q:to/EOS/;
             There was a young man of Japan
             Whose limericks never would scan.
               When asked why this was,
               He replied "It's because
             I always try to fit as many syllables into the last line as ever I possibly can."
             EOS
         say so $str ~~ /^^ There/;        # True  (start of string)
         say so $str ~~ /^^ limericks/;    # False (not at the start of a line)
         say so $str ~~ /^^ I/;            # True  (start of the last line)
         say so $str ~~ /^^ When/;         # False (there are blanks between
                                           #        start of line and the "When")

         say so $str ~~ / Japan $$/;       # True  (end of first line)
         say so $str ~~ / scan $$/;        # False (there is a . between "scan"
                                           #        and the end of line)
         say so $str ~~ / '."' $$/;        # True  (at the last line)

## 31.7.3 << and >> , left and right word boundary

<< matches a left word boundary: it matches positions where there is a non-word character at the left (or the start of the string) and a word character to the right.

>> matches a right word boundary: it matches positions where there is a word character at the left and a non-word character at the right (or the end of the string).

    my $str = 'The quick brown fox';
    say so $str ~~ /br/;              # True
    say so $str ~~ /&lt;&lt; br/;           # True
    say so $str ~~ /br >>/;           # False
    say so $str ~~ /own/;             # True
    say so $str ~~ /&lt;&lt; own/;          # False
    say so $str ~~ /own >>/;          # True

# 31.8 Grouping and Capturing

In regular (non-regex) Perl 6, you can use parentheses to group things together, usually to override operator precedence:

    say 1 + 4 * 2;      # 9, because it is parsed as 1 + (4 * 2)
    say (1 + 4) * 2;    # 10

The same grouping facility is available in regexes:

    / a || b c /        # matches 'a' or 'bc'
    / ( a || b ) c /    # matches 'ac' or 'bc'

The same grouping applies to quantifiers:

    / a b+ /            # Matches an 'a' followed by one or more 'b's
    / (a b)+ /          # Matches one or more sequences of 'ab'
    / (a || b)+ /       # Matches a sequence of 'a's and 'b's, at least one long

An unquantified capture produces a Match object. When a capture is quantified (except with the ? quantifier) the capture becomes a list of Match objects instead.

## 31.8.1 Capturing

The round parentheses don't just group, they also capture; that is, they make the string matched within the group available as a variable, and also as an element of the resulting Match object:

    my $str =  'number 42';
    if $str ~~ /'number ' (\d+) / {
        say "The number is $0";         # the number is 42
        # or
        say "The number is $/[0]";      # the number is 42
    }

Pairs of parentheses are numbered left to right, starting from zero.

    if 'abc' ~~ /(a) b (c)/ {
        say "0: $0; 1: $1";             # 0: a; 1: c
    }

The $0 and $1 etc. syntax is actually just a shorthand; these captures are canonically available from the match object $/ by using it as a list, so $0 is actually syntax sugar for $/[0].

Coercing the match object to a list gives an easy way to programmatically access all elements:

    if 'abc' ~~ /(a) b (c)/ {
        say $/.list.join: ', '  # a, c
    }

## 31.8.2 Non-capturing grouping

The parentheses in regexes perform a double role: they group the regex elements inside and they capture what is matched by the sub-regex inside.

To get only the grouping behavior, you can use square brackets [ ... ] instead.

    if 'abc' ~~ / [a||b] (c) / {
        say ~$0;                # c
    }

If you do not need the captures, using non-capturing groups provides three benefits: it communicates the intent more clearly, it makes it easier to count the capturing groups that you do care about and it is a bit faster.

## 31.8.3 Capture numbers

It is stated above that captures are numbered from left to right. While true in principle, this is also overly simplistic.

The following rules are listed for the sake of completeness; when you find yourself using them regularly, it is worth considering named captures (and possibly subrules) instead.

Alternations reset the capture count:

    / (x) (y)  || (a) (.) (.) /
    # $0  $1      $0  $1  $2

Example:

    if 'abc' ~~ /(x)(y) || (a)(.)(.)/ {
        say ~$1;            # b
    }

If two (or more) alternations have a different number of captures, the one with the most captures determines the index of the next capture:

    $_ = 'abcd';

     if / a [ b (.) || (x) (y) ] (.) / {
         #      $0     $0  $1    $2
         say ~$2;            # d
     }

Captures can be nested, in which case they are numbered per level

    if 'abc' ~~ / ( a (.) (.) ) / {
        say "Outer: $0";              # Outer: abc
        say "Inner: $0[0] and $0[1]"; # Inner: b and c
    }

## 31.8.4 Named captures

Instead of numbering captures, you can also give them names. The generic -- and slightly verbose -- way of naming captures is like this:

    if 'abc' ~~ / $&lt;myname> = [ \w+ ] / {
        say ~$&lt;myname>      # abc
    }

The access to the named capture, $<myname> , is a shorthand for indexing the match object as a hash, in other words: $/{ 'myname' } or $/<myname> .

Named captures can also be nested using regular capture group syntax:

    if 'abc-abc-abc' ~~ / $&lt;string>=( [ $&lt;part>=[abc] ]* % '-' ) / {
        say ~$&lt;string>       # abc-abc-abc
        say ~$&lt;string>&lt;part> # [abc, abc, abc]
    }

Coercing the match object to a hash gives you easy programmatic access to all named captures:

    if 'count=23' ~~ / $&lt;variable>=\w+ '=' $&lt;value>=\w+ / {
        my %h = $/.hash;
        say %h.keys.sort.join: ', ';        # value, variable
        say %h.values.sort.join: ', ';      # 23, count
        for %h.kv -> $k, $v {
            say "Found value '$v' with key '$k'";
            # outputs two lines:
            #   Found value 'count' with key 'variable'
            #   Found value '23' with key 'value'
        }
    }

There is a more convenient way to get named captures which is discussed in the section on Subrules.

# 31.9 Substitution

Regular expressions can also be used to substitute one piece of text for another. You can use this for anything from correcting a spelling error (for instance, replacing 'Perl Jam' with 'Pearl Jam') to reformatting an ISO8601 date from yyyy-mm-ddThh:mm:ssZ to mm-dd-yy h:m {AM,PM} and beyond.

Just like the search-and-replace editor's dialog box, the s/ / / operator has two sides, a left and right side. The left side is where your matching expression goes, and the right-hand side is what you want to replace it with.

## 31.9.1 Lexical conventions

Substitutions are written similarly to matching, but the substitution operator has both an area for the text to substitute, and the text to be substituted:

    s/replace/with/;         # a substitution that is applied to $_
    $str ~~ s/replace/with/; # a substitution applied to a scalar

The substitution operator allows delimiters other than the slash:

    s|replace|with|;
    s!replace!with!;
    s,replace,with,;

Note that neither the colon : nor balancing delimiters such as {} or () can be delimiters. Colons clash with adverbs such as s:i/Foo/bar/ and the other delimiters are used for other purposes.

Like the m// operator, whitespace is ignored in general. Comments, as in Perl 6 in general, start with the hash character # and go to the end of the current line.

## 31.9.2 Replacing literals

The simplest thing to replace is a literal string. The string you want to replace goes on the left-hand side of the substitution operator, and the string you want to replace it with goes on the right-hand side, like so:

    $_ = 'The Replacements';
    s/Replace/Entrap/;
    .say;                    # The Entrapments

Alphanumeric characters and the underscore are literal matches, just as in its cousin the m// operator. All other characters must be escaped with a backslash \ or included in quotes:

    $_ = 'Space: 1999';
    s/Space\:/Party like it's/;
    .say                        # Party like it's 1999

Note that the matching restrictions only apply to the left-hand side of the substitution expression.

By default, substitutions are only done once per string, this is to mitigate unexpected consequences:

    $_ = 'There can be twly two';
    s/tw/on/;                     # Replace 'tw' with 'on' once
    .say;                         # There can be only two

## 31.9.3 Wildcards and character classes

Anything that can go into the m// operator can go into the left-hand side of the substitution operator, including wildcards and character classes. This is handy when the text you're matching isn't static, such as trying to match a number in the middle of a string:

    $_ = "Blake's 9";
    s/\d+/7/;         # Replace any sequence of digits with '7'
    .say;             # Blake's 7

Of course, you can use any of the +, * and ? modifiers, and they'll behave just as they would in the m// operator's context.

## 31.9.4 Capturing Groups

Just as in the match operator, capturing groups are allowed on the left-hand side, and the matched contents populate the $0..$n variables and the $/ object:

    $_ = '2016-01-23 18:09:00';
    s/ (\d+)\-(\d+)\-(\d+) /today/; # Replace YYYY-MM-DD with 'today'
    .say;                           # today 18:09:00
    "$1-$2-$0".say;                 # 01-23-2016
    "$/[1]-$/[2]-$/[0]".say;        # 01-23-2016

Any of these variables $0, $1, $/ can be used on the right-hand side of the operator as well, so you can manipulate what you've just matched. This way you can separate out the YYYY, MM and DD parts of a date and reformat them into MM-DD-YYYY order:

    $_ = '2016-01-23 18:09:00';
    s/ (\d+)\-(\d+)\-(\d+) /$1-$2-$0/; # Transform YYYY-MM-DD to MM-DD-YYYY
    .say;                              # 01-23-2016 18:09:00

Since the right-hand side is effectively a regular Perl 6 interpolated string, you can reformat the time from HH:MM to h:MM {AM,PM} like so:

    $_ = '18:38';
    s/(\d+)\:(\d+)/{$0 % 12}\:$1 {$0 &lt; 12 ?? 'AM' !! 'PM'}/;
    .say;                                                    # 6:38 PM

Using the modulo % operator above keeps the sample code under 80 characters, but is otherwise the same as $0 < 12 ?? $0 !! $0 - 12 . When combined with the power of the Parser Expression Grammars that really underly what you're seeing here, you can use "regular expressions" to parse pretty much any language out there.

### 31.9.4.1 Common adverbs

The full list of adverbs that you can apply to regular expressions can be found elsewhere in this document (section Adverbs), but the most common modifiers that you will use are probably :g and :i.

- Global adverb :g

Ordinarily substitutions are only made once in a given string, but adding the :g modifier overrides that behavior, so that replacements are made everywhere possible. Substitutions are non-recursive, so for instance:

    $_ = q{I can say "banana" but I don't know when to stop};
    s:g/na/nana,/;  # Substitute 'nana,' for 'na'
    .say;           # I can say "banana,nana," but I don't ...

Even though the substitution doubled the number of na's in the string, the substitution only took place twice. Which is to say the substitution only applies to the original string; the targeted string does not count.

- Insensitive adverb :i

Substitutions are normally case-sensitive, so that s/foo/bar/ will only match 'foo' and not 'Foo'. The :i adverb makes matching case-insensitive:

    $_ = 'STAR TREK Into Darkness';
    s/'Trek Into'/TREK\: Into/;     # Someone forgot the colon?
    .say;                           # STAR TREK Into Darkness
    s:i/'Trek into'/TREK\: Into/;   # Thereifixedit
    .say;                           # STAR TREK: Into Darkness

If you want more in-depth descriptions of what these adverbs are actually doing, look in the section Adverbs section of this document.

These are just a few of the transformations you can apply with the substitution operator. Some of the simpler uses in the real world include removing personal data from log files, editing mySQL timestamps into PostgreSQL format, changing copyright information in HTML files and sanitizing form fields in a web application.

As an aside, novices to regular expressions often get overwhelmed and think that their regular expression needs to match every piece of data in the line, including what they want to match. Write just enough to match the data you're looking for, no more, no less.

# 31.10 Subrules

Just like you can put pieces of code into subroutines, you can also put pieces of regex into named rules.

    my regex line { \N*\n }
    if "abc\ndef" ~~ /&lt;line> def/ {
        say "First line: ", $&lt;line>.chomp;      # First line: abc
    }

A named regex can be declared with my regex thename { body here }, and called with <thename> . At the same time, calling a named regex installs a named capture with the same name.

If the capture should be of a different name, this can be achieved with the syntax <capturename=regexname> . If no capture at all is desired, a leading dot will suppress it: <.regexname> .

Here is a more complete (yet still fairly limited) code for parsing ini files:

    my regex header { \s* '[' (\w+) ']' \h* \n+ }
    my regex identifier  { \w+ }
    my regex kvpair { \s* &lt;key=identifier> '=' &lt;value=identifier> \n+ }
    my regex section {
        &lt;header>
        &lt;kvpair>*
    }

    my $contents = q:to/EOI/;
        [passwords]
            jack=password1
            joy=muchmoresecure123
        [quotas]
            jack=123
            joy=42
    EOI

    my %config;
    if $contents ~~ /&lt;section>*/ {
        for $&lt;section>.list -> $section {
            my %section;
            for $section&lt;kvpair>.list -> $p {
                say $p&lt;value>;
                %section{ $p&lt;key> } = ~$p&lt;value>;
            }
            %config{ $section&lt;header>[0] } = %section;
        }
    }
    say %config.perl;
    # ("passwords" => {"jack" => "password1", "joy" => "muchmoresecure123"},
    #    "quotas" => {"jack" => "123", "joy" => "42"}).hash

Named regexes can and should be grouped in grammars. A list of predefined subrules is listed in S05.

# 31.11 Adverbs

Adverbs modify how regexes work and give very convenient shortcuts for certain kinds of recurring tasks.

There are two kinds of adverbs: regex adverbs apply at the point where a regex is defined and matching adverbs apply at the point that a regex matches against a string.

This distinction often blurs, because matching and declaration are often textually close but using the method form of matching makes the distinction clear.

'abc' ~~ /../ is roughly equivalent to 'abc'.match(/../), or even more clearly written in separate lines:

    my $regex = /../;           # definition
    if 'abc'.match($regex) {    # matching
        say "'abc' has at least two characters";
    }

Regex adverbs like :i go into the definition line and matching adverbs like :overlap are appended to the match call:

    my $regex = /:i . a/;
    for 'baA'.match($regex, :overlap) -> $m {
        say ~$m;
    }
    # output:
    #     ba
    #     aA

## 31.11.1 Regex Adverbs

Adverbs that appear at the time of a regex declaration are part of the actual regex and influence how the Perl 6 compiler translates the regex into binary code.

For example, the :ignorecase (:i) adverb tells the compiler to ignore the distinction between upper case, lower case and title case letters.

So 'a' ~~ /A/ is false, but 'a' ~~ /:i A/ is a successful match.

Regex adverbs can come before or inside a regex declaration and only affect the part of the regex that comes afterwards, lexically.

These two regexes are equivalent:

    my $rx1 = rx:i/a/;      # before
    my $rx2 = rx/:i a/;     # inside

Whereas these two are not:

    my $rx3 = rx/a :i b/;   # matches only the b case insensitively
    my $rx4 = rx/:i a b/;   # matches completely case insensitively

Brackets and parentheses limit the scope of an adverb:

    / (:i a b) c /          # matches 'ABc' but not 'ABC'
    / [:i a b] c /          # matches 'ABc' but not 'ABC'

### 31.11.1.1 Ratchet

The :ratchet or :r adverb causes the regex engine not to backtrack.

Without this adverb, parts of a regex will try different ways to match a string in order to make it possible for other parts of the regex to match. For example in 'abc' ~~ /\w+ ./, the \w+ first eats up the whole string, abc but then the . fails. Thus \w+ gives up a character, matching only ab, and the . can successfully match the string c. This process of giving up characters (or in the case of alternations, trying a different branch) is known as backtracking.

    say so 'abc' ~~ / \w+ . /;        # True
    say so 'abc' ~~ / :r \w+ . /;     # False

Ratcheting can be an optimization, because backtracking is costly. But more importantly, it closely corresponds to how humans parse a text. If you have a regex my regex identifier { \w+ } and my regex keyword { if | else | endif }, you intuitively expect the identifier to gobble up a whole word and not have it give up its end to the next rule, if the next rule otherwise fails. For instance, you don't expect the word motif to be parsed as the identifier mot followed by the keyword if; rather you expect motif to be parsed as one identifier and if the parser expects an if afterwards, rather have it fail than parse the input in a way you don't expect.

Since ratcheting behavior is so often desirable in parsers, there is a shortcut to declaring a ratcheting regex:

    my token thing { .... }
    # short for
    my regex thing { :r ... }

### 31.11.1.2 Sigspace

The :sigspace or :s adverb makes whitespace significant in a regex.

    say so "I used Photoshop®"   ~~ m:i/   photo shop /; # True
     say so "I used a photo shop" ~~ m:i <b>:s</b> / photo shop /; # True
     say so "I used Photoshop®"   ~~ m:i <b>:s</b> / photo shop /; # False

m:s/ photo shop / acts just the same as if one had written m/ photo <.ws> shop <.ws> /. By default, <.ws> makes sure that words are separated, so a b and ^& will match <.ws> in the middle, but ab won't.

Where whitespace in a regex turns into <.ws> depends on what comes before the whitespace. In the above example, whitespace in the beginning of a regex doesn't turn into <.ws>, but whitespace after characters does. In general, the rule is that if a term might match something, whitespace after it will turn into <.ws>.

In addition, if whitespace comes after a term, but before a quantifier (+, *, or ?), <.ws> will be matched after every match of the term, so foo + becomes [ foo <.ws> ]+. On the other hand, whitespace after a quantifier acts as normal significant whitespace, e.g., "foo+ " becomes foo+ <.ws>.

In all, this code:

    rx :s {
         ^^
         {
             say "No sigspace after this";
         }
         &lt;.assertion_and_then_ws>
         characters_with_ws_after+
         ws_separated_characters *
         [
         | some "stuff" .. .
         | $$
         ]
         :my $foo = "no ws after this";
         $foo
     }

Becomes:

    rx {
         ^^  <b>&lt;.ws></b>
         {
             say "No space after this";
         }
         &lt;.assertion_and_then_ws>  <b>&lt;.ws></b>
         characters_with_ws_after+  <b>&lt;.ws></b>
         [ws_separated_characters  <b>&lt;.ws></b> ]*  <b>&lt;.ws></b>
         [
         | some  <b>&lt;.ws></b>  "stuff"  <b>&lt;.ws></b>  ..  <b>&lt;.ws></b>  .  <b>&lt;.ws></b>
         | $$  <b>&lt;.ws></b>
         ]  <b>&lt;.ws></b>
         :my $foo = "no ws after this";
         $foo  <b>&lt;.ws></b>
     }

If a regex is declared with the rule keyword, both the :sigspace and :ratchet adverbs are implied.

Grammars provide an easy way to override what <.ws> matches:

    grammar Demo {
        token ws {
            &lt;!ww>   # only match when not within a word
            \h*     # only match horizontal whitespace
        }
        rule TOP {  # called by Demo.parse;
            a b '.'
        }
    }

    # doesn't parse, whitespace required between a and b
    say so Demo.parse("ab.");         # False
    say so Demo.parse("a b.");        # True
    say so Demo.parse("a\tb .");      # True
    # \n is vertical whitespace, so no match
    say so Demo.parse("a\tb\n.");     # False

When parsing file formats where some whitespace (for example vertical whitespace) is significant, it is advisable to override ws.

## 31.11.2 Matching adverbs

In contrast to regex adverbs, which are tied to the declaration of a regex, matching adverbs only make sense while matching a string against a regex.

They can never appear inside a regex, only on the outside -- either as part of an m/.../ match or as arguments to a match method.

### 31.11.2.1 Continue

The :continue or short :c adverb takes an argument. The argument is the position where the regex should start to search. By default, it searches from the start of the string, but :c overrides that. If no position is specified for :c it will default to 0 unless $/ is set, in which case it defaults to $/.to.

    given 'a1xa2' {
        say ~m/a./;         # a1
        say ~m:c(2)/a./;    # a2
    }

### 31.11.2.2 Exhaustive

To find all possible matches of a regex -- including overlapping ones -- and several ones that start at the same position, use the :exhaustive (short :ex) adverb.

    given 'abracadabra' {
        for m:exhaustive/ a .* a / -> $match {
            say ' ' x $match.from, ~$match;
        }
    }

The above code produces this output:

    abracadabra
     abracada
     abraca
     abra
        acadabra
        acada
        aca
          adabra
          ada
            abra

### 31.11.2.3 Global

Instead of searching for just one match and returning a Match object, search for every non-overlapping match and return them in a List. In order to do this use the :global adverb:

    given 'several words here' {
        my @matches = m:global/\w+/;
        say @matches.elems;         # 3
        say ~@matches[2];           # here
    }

:g is shorthand for :global.

### 31.11.2.4 Pos

Anchor the match at a specific position in the string:

    given 'abcdef' {
        my $match = m:pos(2)/.*/;
        say $match.from;        # 2
        say ~$match;            # cdef
    }

:p is shorthand for :pos.

### 31.11.2.5 Overlap

To get several matches, including overlapping matches, but only one (the longest) from each starting position, specify the :overlap (short :ov) adverb:

    given 'abracadabra' {
        for m:overlap/ a .* a / -> $match {
            say ' ' x $match.from, ~$match;
        }
    }

produces

    abracadabra
        acadabra
          adabra
            abra

# 31.12 Look-around assertions

## 31.12.1 Lookahead assertions

To check that a pattern appears before another pattern, one can use a lookahead assertion via the before assertion. This has the form:

    &lt;?before pattern>

Thus, to search for the string foo which is immediately followed by the string bar, one could use the following regexp:

    rx{ foo &lt;?before bar> }

which one could use like so:

    say "foobar" ~~ rx{ foo &lt;?before bar> };   #->  foo

However, if you want to search for a pattern which is not immediately followed by some pattern, then you need to use a negative lookahead assertion, this has the form:

    &lt;!before pattern>

Hence all occurrences of foo which is not before bar would be matched by

    rx{ foo &lt;!before bar> }

## 31.12.2 Lookbehind assertions

To check that a pattern appears before another pattern, one can use a lookbehind assertion via the after assertion. This has the form:

    &lt;?after pattern>

Thus, to search for the string bar which is immediately preceded by the string foo, one could use the following regexp:

    rx{ &lt;?after foo> bar }

which one could use like so:

    say "foobar" ~~ rx{ &lt;?after foo> bar };   #->  bar

However, if you want to search for a pattern which is not immediately preceded by some pattern, then you need to use a negative lookbehind assertion, this has the form:

    &lt;!after pattern>

Hence all occurrences of bar which do not have foo before them would be matched by

    rx{ &lt;!after foo> bar }

# 31.13 Best practices and gotchas

Regexes and grammars are a whole programming paradigm that you have to learn (if you don't already know it very well).

To help you write robust regexes and grammars, here are some best practices that the authors have found useful. These range from small-scale code layout issues to what actually to match, and help to avoid common pitfalls and writing unreadable code.

## 31.13.1 Code layout

Without the :sigspace adverb, whitespace is not significant in Perl 6 regexes. Use that to your own advantage and insert whitespace where it increases readability. Also insert comments where necessary.

Compare the very compact

    my regex float { &lt;[+-]>?\d*'.'\d+[e&lt;[+-]>?\d+]? }

to the more readable

    my regex float {
         &lt;[+-]>?        # optional sign
         \d*            # leading digits, optional
         '.'
         \d+
         [              # optional exponent
            e &lt;[+-]>?  \d+
         ]?
    }

As a rule of thumb, use whitespace around atoms and inside groups. Put quantifiers directly after the atom, without inserting a blank. Vertically align opening and closing brackets and parentheses.

When you use a list of alternations inside a parenthesis or brackets, align the vertical bars:

    my regex example {
        &lt;preamble>
        [
        || &lt;choice_1>
        || &lt;choice_2>
        || &lt;choice_3>
        ]+
        &lt;postamble>
    }

## 31.13.2 Keep it small

Regexes come with very little boilerplate, so they are often more compact than regular code. Thus it is important to keep regexes short.

When you can come up with name for a part of a regex, it is usually best to put it into a separate, named regex.

For example you could take the float regex from earlier:

    my regex float {
         &lt;[+-]>?        # optional sign
         \d*            # leading digits, optional
         '.'
         \d+
         [              # optional exponent
            e &lt;[+-]>?  \d+
         ]?
    }

And decompose it into parts:

    my token sign { &lt;[+-]> }
    my token decimal { \d+ }
    my token exponent { 'e' &lt;sign>? &lt;decimal> }
    my regex float {
        &lt;sign>?
        &lt;decimal>?
        '.'
        &lt;decimal>
        &lt;exponent>?
    }

That helps especially when the regex becomes more complicated. For example you might want to make the decimal point optional if an exponent is there.

    my regex float {
        &lt;sign>?
        [
        || &lt;decimal>?  '.' &lt;decimal> &lt;exponent>?
        || &lt;decimal> &lt;exponent>
        ]
    }

## 31.13.3 What to match

Often the input data format has no clear-cut specification, or the specification is not known to the programmer. Then it is good to be liberal in what you expect, but only as long as there are no ambiguities possible.

For example in ini files:

    [section]
    key=value

What can be inside the section header? Allowing only a word might be too restrictive, somebody might write [two words], or use dashes, or so. Instead of asking what's allowed on the inside, it might be worth asking instead: what's not allowed?

Clearly, closing brackets are not allowed, because [a]b] would be rather ambiguous. By the same argument, opening brackets should be forbidden. This leaves us with

    token header { '[' &lt;-[ \[\] ]>+ ']' }

which is fine if you are only processing one line. But if you're processing a whole file, suddenly the regex parses

    [with a
    newline in between]

which might not be a good idea. A pragmatic compromise would be

    token header { '[' &lt;-[ \[\] \n ]>+ ']' }

and then, in the post-processing, strip leading and trailing spaces and tabs from the section header.

## 31.13.4 Matching Whitespace

The :sigspace adverb (or using the rule declarator instead of token or regex) is very handy for implicitly parsing whitespace that can appear in many places.

Going back to the example of parsing ini files, we have

    my regex kvpair { \s* &lt;key=identifier> '=' &lt;value=identifier> \n+ }

which is probably not as liberal as we want it to be. Since the user might put spaces around the equals sign, it should rather read

    my regex kvpair { \s* &lt;key=identifier> \s* '=' \s* &lt;value=identifier> \n+ }

That's growing unwieldy pretty quickly. So instead one can write

    my rule kvpair { &lt;key=identifier> '=' &lt;value=identifier> \n+ }

But wait! The implicit whitespace matching after the value uses up all whitespace, including newline characters, so the \n+ doesn't have anything left to match (and rule also disables backtracking, so no luck here).

Therefore it is important to redefine your definition of implicit whitespace to whitespace that is not significant in the input format.

This works by redefining the token ws, however it only works in grammars:

    grammar IniFormat {
        token ws { &lt;!ww> \h* }
        rule header { \s* '[' (\w+) ']' \n+ }
        token identifier  { \w+ }
        rule kvpair { \s* &lt;key=identifier> '=' &lt;value=identifier> \n+ }
        token section {
            &lt;header>
            &lt;kvpair>*
        }

        token TOP {
            &lt;section>*
        }
    }

    my $contents = q:to/EOI/;
        [passwords]
            jack = password1
            joy = muchmoresecure123
        [quotas]
            jack = 123
            joy = 42
    EOI
    say so IniFormat.parse($contents);

Besides putting all regexes into a grammar and turning them into tokens (because they don't need to backtrack anyway) the interesting new bit is

    token ws { &lt;!ww> \h* }

which gets called for implicit whitespace parsing. It matches when it is not between two word characters (<!ww> , negated "within word" assertion), and zero or more horizontal space characters. The limitation to horizontal whitespace is important, because newlines (which are vertical whitespace) delimit records and shouldn't be matched implicitly.

Still there is some whitespace-related trouble lurking. The regex \n+ won't match a string like "\n \n", because there is a blank between the two newlines. To allow such input strings, replace \n+ by \n\s*.

# 32 Sets, Bags, and Mixes

Unordered collections of unique and weighted objects in Perl 6

Often you want to collect objects in a container but you do not care about the order of these objects. For such cases, Perl 6 provides the unordered collection types Set , SetHash , Bag , BagHash , Mix , and MixHash . Being unordered, these containers can be more efficient than Lists for looking up elements or dealing with repeated items.

If you want to get the contained objects (elements) without duplicates and you only care whether an element is in the collection or not, you can use a Set or SetHash . (If you want to get rid of duplicates but still preserve order, take a look at the unique routine for Lists .)

=defn Set or SetHash Collection of distinct objects

If you want to keep track of the number of times each object appeared, you can use a Bag or BagHash . In these Baggy containers each element has a weight (an unsigned integer) indicating the number of times the same object has been included in the collection. The types Mix and MixHash are similar, but they also allow fractional weights.

=defn Bag or BagHash Collection of distinct objects mapped to integer weights =defn Mix or MixHash Collection of distinct objects mapped to real-number weights TODO: Partial type graph showing only QuantHash, Setty, Baggy, Mixy, Set, SetHash, Bag, BagHash, Mix, MixHash.

Set , Bag , and Mix are immutable types. Use the mutable variants SetHash , BagHash , and MixHash if you want to add or remove elements after the container has been constructed.

The six collection classes Set, SetHash, Bag, BagHash, Mix, MixHash, all share similar semantics.

For one thing, as far as they are concerned, identical objects refer to the same element -- where identity is determined using the WHICH methods (i.e. the same way that the === operator checks identity). For value types like Str, this means having the same value; for reference types like Array, it means referring to the same object instance.

Secondly, they provide a Hash-like interface where the actual elements of the collection (which can be objects of any type) are the 'keys', and the associated weights are the 'values':

type of $a | value of $a{$b} if $b is an element | value of $a{$b} if $b is not an element
--- | --- | ---
Set / SetHash | True | False
Bag / BagHash | a positive integer | 0
Mix / MixHash | a non-zero real number | 0

# 32.1 Set/Bag Operators

TODO: Update this after ab5tract's set/bag/mix operator redesign.

There are many infixes devoted to preforming common operations on Set s, such as unions and set differences. Other operations include boolean checks, like whether an object is an element of a Set, or whether one Set is a subset of another Set.

These infixes can be written using the UTF-8 character that represents the function (like ∈ , or ∪ ), or they can be written with an equivalent ASCII version (like (elem) or (|) ).

Most of the time, explicitly using Set objects with these infixes is unnecessary. All of the infix operators will work on any objects of type Any for its arguments (e.g., List s, Array s, Mix es, etc.) and coerce them to Sets where needed.

In some cases, if the type of an argument is a Bag, the infix operator will behave in a different but analogous way to the way it would behave with only Set arguments.

## 32.1.1 Operators that return Bool

### 32.1.1.1 infix (elem)

    multi sub infix:&lt;(elem)>($a, Any $b --> Bool)
    multi sub infix:&lt;(elem)>($a, Set $b --> Bool)

Membership operator.

Returns True if $a is an element of $b.

#### 32.1.1.1.1 infix ∈

    only sub infix:&lt;&lt;"∈">>($a, $b --> Bool)

Membership operator (alternate).

Equivalent to (elem), at codepoint U+2208 (ELEMENT OF).

#### 32.1.1.1.2 infix ∉

    only sub infix:&lt;&lt;"∉">>($a, $b --> Bool)

Non-membership operator.

Equivalent to !(elem), i.e., returns True if $a is not an element of $b, at codepoint U+2209 (NOT AN ELEMENT OF).

### 32.1.1.2 infix (cont)

    multi sub infix:&lt;(cont)>(Any $a, $b --> Bool)
    multi sub infix:&lt;(cont)>(Set $a, $b --> Bool)

Contains operator.

Returns True if $a contains $b as an element.

#### 32.1.1.2.1 infix ∋

    only sub infix:&lt;&lt;"∋">>($a, $b --> Bool)

Contains operator (alternate).

Equivalent to (cont), at codepoint U+220B (CONTAINS AS MEMBER).

#### 32.1.1.2.2 infix ∌

    only sub infix:&lt;&lt;"∌">>($a, $b --> Bool)

Does not contain operator.

Equivalent to !(cont), i.e., returns True if $a does not contain $b, at codepoint U+220C (DOES NOT CONTAIN AS MEMBER).

### 32.1.1.3 infix (<=)

    multi sub infix:&lt;&lt;(&lt;=)>>(Any $a, Any $b --> Bool)
    multi sub infix:&lt;&lt;(&lt;=)>>(Setty $a, Setty $b --> Bool)

Subset of or equal to operator.

Returns True if $a is a subset or is equal to $b, i.e., if all the elements of $a are elements of $b and $a is a smaller or equal sized set than $b.

#### 32.1.1.3.1 infix ⊆

    only sub infix:&lt;&lt;"⊆">>($a, $b --> Bool)

Subset of or equal to operator (alternate).

Equivalent to (<=), at codepoint U+2286 (SUBSET OF OR EQUAL TO).

#### 32.1.1.3.2 infix ⊈

    only sub infix:&lt;&lt;"⊈">>($a, $b --> Bool)

Neither subset of nor equal to operator.

Equivalent to !(<=), at codepoint U+2288 (NEITHER A SUBSET OF NOR EQUAL TO).

### 32.1.1.4 infix (<)

    multi sub infix:&lt;&lt;(&lt;)>>(Any $a, Any $b --> Bool)
    multi sub infix:&lt;&lt;(&lt;)>>(Setty $a, Setty $b --> Bool)

Subset of operator.

Returns True if $a is a strict subset of $b, i.e., that all the elements of $a are elements of $b but $a is a smaller set than $b.

#### 32.1.1.4.1 infix ⊂

    only sub infix:&lt;&lt;"⊂">>($a, $b --> Bool)

Subset of operator (alternate).

Equivalent to (<), at codepoint U+2282 (SUBSET OF).

#### 32.1.1.4.2 infix ⊄

    only sub infix:&lt;&lt;"⊄">>($a, $b --> Bool)

Not a subset of operator.

Equivalent to !(<), at codepoint U+2284 (NOT A SUBSET OF).

### 32.1.1.5 infix (>=)

    multi sub infix:&lt;&lt;(>=)>>(Any $a, Any $b --> Bool)
    multi sub infix:&lt;&lt;(>=)>>(Setty $a, Setty $b --> Bool)

Superset of or equal to operator.

Like (<=) with reversed arguments. Returns True if $a is a superset of or equal to $b.

#### 32.1.1.5.1 infix ⊇

    only sub infix:&lt;&lt;"⊇">>($a, $b --> Bool)

Superset of or equal to operator (alternate).

Equivalent to (>=), at codepoint U+2287 (SUPERSET OF OR EQUAL TO).

#### 32.1.1.5.2 infix ⊉

    only sub infix:&lt;&lt;"⊉">>($a, $b --> Bool)

Neither a superset of nor equal to operator.

Equivalent to !(>=), at codepoint U+2289 (NEITHER A SUPERSET OF NOR EQUAL TO).

### 32.1.1.6 infix (>)

    multi sub infix:&lt;&lt;(>)>>(Any $a, Any $b --> Bool)
    multi sub infix:&lt;&lt;(>)>>(Setty $a, Setty $b --> Bool)

Superset of operator.

Like (<) with reversed arguments. Returns True if $a is a strict superset of $b.

#### 32.1.1.6.1 infix ⊃

    only sub infix:&lt;&lt;"⊃">>($a, $b --> Bool)

Superset of operator (alternate).

Equivalent to (>), at codepoint U+2283 (SUPERSET OF).

#### 32.1.1.6.2 infix ⊅

    only sub infix:&lt;&lt;"⊅">>($a, $b --> Bool)

Not a superset of operator.

Equivalent to !(>), at codepoint U+2285 (NOT A SUPERSET OF).

### 32.1.1.7 infix (<+)

    multi sub infix:&lt;&lt;(&lt;+)>>(Any $a, Any $b --> Bool)
    multi sub infix:&lt;&lt;(&lt;+)>>(Baggy $a, Baggy $b --> Bool)

Baggy subset of operator.

Returns True if $a is a Baggy subset of $b, i.e., if all the elements of $a are in $b and each element of $b is weighed at least as heavily as the element is in $a.

#### 32.1.1.7.1 infix ≼

    only sub infix:&lt;&lt;"≼">>($a, $b --> Bool)

Baggy subset of operator (alternate).

Equivalent to (<+), at codepoint U+227C (PRECEDES OR EQUAL TO).

### 32.1.1.8 infix (>+)

    multi sub infix:&lt;&lt;(>+)>>(Baggy $a, Baggy $b --> Bool)
    multi sub infix:&lt;&lt;(>+)>>(Any $a, Any $b --> Bool)

Baggy superset of operator.

Returns True if $a is a Baggy superset of $b, i.e., if all the elements of $b are in $a and no element of $b is weighted heavier than that element is in $a.

#### 32.1.1.8.1 infix ≽

    only sub infix:&lt;&lt;"≽">>($a, $b --> Bool)

Baggy superset of operator (alternate).

Equivalent to (>+), at codepoint U+227D (SUCCEEDS OR EQUAL TO).

## 32.1.2 Operators that return Set or Bag

### 32.1.2.1 infix (|)

    only sub infix:&lt;(|)>(**@p)

Union operator.

Returns the union of all its arguments. Generally, this creates a new Set that contains all the elements its arguments contain.

    &lt;a a b c d> (|) &lt;h g f e d c> (|) &lt;i j> === set &lt;a b c d e f g h i j>

If any of its arguments are Baggy, it creates a new Bag that contains all the elements of the arguments, each weighed by the highest weight that appeared for that element.

    bag(&lt;a a b c a>) (|) bag(&lt;a a b c c>) === bag(&lt;a a a b c c>)

#### 32.1.2.1.1 infix ∪

    only sub infix:&lt;&lt;"∪">>(|p)

Union operator (alternate).

Equivalent to (|), at codepoint U+222A (UNION).

### 32.1.2.2 infix (&)

    only sub infix:&lt;(&amp;)>(**@p)

Intersection operator.

Returns the intersection of all of its arguments. Generally, this creates a new Set that contains only the elements common to all of the arguments.

    &lt;a b c> (&amp;) &lt;b c d> === set &lt;b c>
    &lt;a b c d> (&amp;) &lt;b c d e> (&amp;) &lt;c d e f> === set &lt;c d>

If any of the arguments are Baggy, the result is a new Bag containing the common elements, each weighted by the largest common weight (which is the minimum of the weights of that element over all arguments).

    bag(&lt;a a b c a>) (&amp;) bag(&lt;a a b c c>) === bag(&lt;a a b c>)

#### 32.1.2.2.1 infix ∩

    only sub infix:&lt;&lt;"∩">>(|p)

Intersection operator (alternate).

Equivalent to (&), at codepoint U+2229 (INTERSECTION).

### 32.1.2.3 infix (-)

    only sub infix:&lt;(-)>(**@p)

Set difference operator.

Returns the set difference of all its arguments. Generally, this returns the Set made up of all the elements the first argument has but the rest don't, i.e., of all the elements of the first argument, minus the elements from the other arguments.

If the first argument is Baggy, this returns a Bag that contains each element of the first argument with its weight subtracted by the weight of that element in each of the other arguments.

    bag(&lt;a a b c a d>) (-) bag(&lt;a a b c c>) = bag(&lt;a d>)
    bag(&lt;a a a a c d d d>) (-) bag(&lt;a b d a>) (-) bag(&lt;d c>) = bag(&lt;a a d d>)

#### 32.1.2.3.1 infix ∖

    only sub infix:&lt;&lt;"\x2216">>(|p)

Set difference operator (alternate).

Equivalent to (-).

### 32.1.2.4 infix (^)

    multi sub infix:&lt;(^)>(Any $a, Any $b --> Setty)
    multi sub infix:&lt;(^)>(Set $a, Set $b --> Setty)

Symmetric set difference operator.

Returns the symmetric set difference of all its arguments, i.e., a Set made up of all the elements that $a has but $b doesn't and all the elements $b has but $a doesn't. Equivalent to ($a ∖ $b) ∪ ($b ∖ $a).

#### 32.1.2.4.1 infix ⊖

    only sub infix:&lt;&lt;"⊖">>($a, $b --> Setty)

Symmetric set difference operator (alternate).

Equivalent to (^), at codepoint U+2296 (CIRCLED MINUS).

### 32.1.2.5 infix (.)

    only sub infix:&lt;(.)>(**@p)

Baggy multiplication operator.

Returns the Baggy multiplication of its arguments, i.e., a Bag that contains each element of the arguments with the weights of the element across the arguments multiplied together to get the new weight.

    &lt;a b c> (.) &lt;a b c d> === bag &lt;a b c> # Since 1 * 0 == 0, in the case of 'd'
    bag(&lt;a a b c a d>) (.) bag(&lt;a a b c c>) === bag(&lt;a a a a a a b c c>)

#### 32.1.2.5.1 infix ⊍

    only sub infix:&lt;&lt;"⊍">>(|p)

Baggy multiplication operator (alternate).

Equivalent to infix (.), at codepoint U+228D (MULTISET MULTIPLICATION).

### 32.1.2.6 infix (+)

    only sub infix:&lt;(+)>(**@p)

Baggy addition operator.

Returns the Baggy addition of its arguments, i.e., a Bag that contains each element of the arguments with the weights of the element across the arguments added together to get the new weight.

    bag(&lt;a a b c a d>) (.) bag(&lt;a a b c c>) === bag(&lt;a a a a a b b c c c d>)

#### 32.1.2.6.1 infix ⊎

    only sub infix:&lt;&lt;"⊎">>(|p)

Baggy addition operator (alternate).

Equivalent to (+), at codepoint U+228E (MULTISET UNION).

### 32.1.2.7 term ∅

Equivalent to set(), aka the empty set, at codepoint U+2205 (EMPTY SET).

# 33 Subscripts

Accessing data structure elements by index or key

Often one needs to refer to a specific element (or specific slice of elements) of a collection or data structure. Borrowing from mathematical notation where the components of a vector v would be referred to as v₁, v₂, v₃, this concept is called "subscripting" (or "indexing") in Perl 6.

# 33.1 Basics

Perl 6 provides two universal subscripting interfaces:

| elements are identified by | interface name | supported by
--- | --- | --- | ---
[ ] | zero-based indices | Positional | Array, List, Buf, Match, ...
{ } | string or object keys | Associative | Hash, Bag, Mix, Match, ...

- Positional subscripting (via postcircumfix [ ] ) addresses elements of an ordered collection by their position. Index 0 refers to the first element, index 1 to the second, and so on:

      my @chores = "buy groceries", "feed dog", "wash car";
      say @chores[0];  #-> buy groceries
      say @chores[1];  #-> feed dog
      say @chores[2];  #-> wash car

- Associative subscripting (via postcircumfix { } ), does not require the collection to keep its elements in any particular order - instead, it uses a unique key to address each value. The nature of the keys depends on the collection in question: For example a standard Hash uses string keys, whereas a Mix allows arbitrary objects as keys, etc.:

      my %grade = Zoe => "C", Ben => "B+";
      say %grade{"Zoe"};  #-> C
      say %grade{"Ben"};  #-> B+

      my $stats = ( Date.today => 4.18, Date.new(2015,  4,  5) => 17.253 ).Mix;
      say $stats{ Date.new(2015, 4, 4) + 1 };  #-> 17.253

  For passing single-word string keys to { }, you can also use the angle-bracketed word quoting constructs as if they were postcircumfix operators:

      say %grade&lt;Zoe>;    #-> C
      say %grade&lt;Ben>;    #-> B+

  This is really just syntactic sugar that gets turned into the corresponding { } form at compile-time:

      %hash&lt;foo bar>;     # same as %hash{ &lt;foo bar> }
      %hash«foo $var»;    # same as %hash{ «foo $var» }
      %hash&lt;&lt;foo $var>>;  # same as %hash{ &lt;&lt;foo $var>> }

  You may have noted above that we avoided having to quote Zoe by using the => operator, but that same operator did not just put invisible quotes around Date.new(2015, 4, 5), and we were able to find the same element using $stats{ Date.new(2015, 4, 4) + 1 }. This is because => only puts invisible quotes around single words, and by "word" we mean an identifier/name. The => operator is there to prevent us from accidentally calling functions or using constants with that name.

  Hash subscripts do not do the same thing as => . The default Hash has been made to behave the way new users have come to expect from using other languages, and for general ease of use. On a default Hash, subscripts coerce keys into strings, as long as those keys produce something Cool. You can use .perl on a collection to be sure whether the keys are strings or objects:

      ( 1  => 1 ).perl.say             #-> 1 => 1
      my %h; %h{1}   = 1; say %h.perl; #-> { "1" => 1 }
      ( 1/2 => 1 ).perl.say            #-> 0.5 => 1
      my %h; %h{1/2} = 1; say %h.perl; #-> { "0.5" => 1 }
      ( pi => 1 ).perl.say             #-> :pi(1)
      my %h; %h{pi}  = 1; say %h.perl; #-> { "3.14159265358979" => 1 }

  While the invisible quotes around single names is built into => , string conversion is not built into the curly braces: it is a behavior of the default Hash. Not all types of hashes or collections do so:

      my %h := MixHash.new;
      $h{pi} = 1; %h.perl.say;         #-> (3.14159265358979e0=>1).MixHash

  (Any name that => would convert to a string can also be used to build a pair using "adverbial notation" and will appear that way when viewed through .perl, which is why we see :pi(1) above.)

Subscripts can be applied to any expression that returns a subscriptable object, not just to variables:

    say "__Hello__".match(/__(.*)__/)[0];   #-> ｢Hello｣
    say "__Hello__".match(/__(.*)__/).[0];  # same, in method notation

Positional and associative subscripting are not mutually exclusive - for example, Match objects support both (each accessing a different set of data). Also, to make list processing more convenient, class Any provides a fallback implementation for positional subscripts which simply treats the invocant as a list of one element. (But there's no such fallback for associative subscripts, so they throw a run-time error when applied to an object that does not implement support for them.)

    say 42[0];    #-> 42
    say 42&lt;foo>;  # ERROR: postcircumfix { } not defined for type Int

# 33.2 Nonexistent elements

What happens when a nonexistent element is addressed by a subscript, is up to the collection type in question. Standard Array and Hash collections return the type object of their value type constraint (which, by default, is Any):

    my @array1;     say @array1[10];  #-> (Any)
    my Int @array2; say @array2[10];  #-> (Int)

    my %hash1;      say %hash1&lt;foo>;  #-> (Any)
    my Int %hash2;  say %hash2&lt;foo>;  #-> (Int)

However, other types of collections may react differently to subscripts that address nonexistent elements:

    say (0, 10, 20)[3];           #-> Nil
    say bag(&lt;a a b b b>)&lt;c>;      #-> 0
    say array[uint8].new(1, 2)[2] #-> 0

To silently skip nonexistent elements in a subscripting operation, see #Truncating slices and the #:v adverb.

# 33.3 From the end

Positional indices are counted from the start of the collection, but there's also a notation for addressing elements by their position relative to the end: *-1 refers to the last element, *-2 to the second-to-last element, and so on.

    my @alphabet = 'A' .. 'Z';
    say @alphabet[*-1];  #-> Z
    say @alphabet[*-2];  #-> Y
    say @alphabet[*-3];  #-> X

Note: The asterisk is important. Passing a bare negative integer (e.g. @alphabet[-1]) like you would do in many other programming languages, throws an error in Perl 6.

What actually happens here, is that an expression like *-1 declares a code object via Whatever-currying - and the [ ] subscript reacts to being given a code object as an index, by calling it with the length of the collection as argument and using the result value as the actual index. In other words, @alphabet[*-1] becomes @alphabet[@alphabet.elems - 1].

This means that you can use arbitrary expressions which depend on the size of the collection:

    say @array[* div 2];  # select the middlemost element
    say @array[$i % *];   # wrap around a given index ("modular arithmetic")
    say @array[ -> $size { $i % $size } ];  # same as previous

# 33.4 Slices

When multiple elements of a collection need to be accessed, there's a shortcut to doing multiple separate subscripting operations: Simply specify a list of indices/keys in the subscript, to get back a list of elements - also called a "slice" - in the same order.

For positional slices, you can mix normal indices with from-the-end ones:

    my @alphabet = 'a' .. 'z';
    dd @alphabet[15, 4, *-9, 11];  #-> ("p", "e", "r", "l")

For associative slices, the angle-brackets form often comes in handy:

    my %color = kiwi => "green", banana => "yellow", cherry => "red";
    dd %color{"cherry", "kiwi"};  #-> ("red", "green")
    dd %color&lt;cherry kiwi>;       #-> ("red", "green")
    dd %color{*};                 #-> ("green", "red", "yellow")

Be aware that slices are controlled by the type of what is passed to (one dimension of) the subscript, not its length:

subscript | result
--- | ---
any Iterable not mentioned below | normal slice
a Range | L<truncates|#Truncating slices> in [ ]
a lazy Iterable | L<truncates|#Truncating slices> in [ ]
* (Whatever-star) | full slice (as if all keys/indices were specified)
any other object | single-element access rather than a slice
empty | L<Zen slice|#Zen slices>

So even a one-element list returns a slice, whereas a bare scalar value doesn't:

    dd @alphabet[2,];  #-> ("c",)
    dd @alphabet[2];   #-> "c"

(The angle-bracket form for associative subscripts works out because word quoting conveniently returns a Str in case of a single word, but a List in case of multiple words.)

In fact, the list structure of (the current dimension of) the subscript is preserved across the slice operation (but the kind of Iterable is not -- the result is always just lists.)

    dd @alphabet[0, (1..2, (3,))];  #-> ("a", (("b", "c"), ("d",)))
    dd @alphabet[0, (1..2, [3,])];  #-> ("a", (("b", "c"), ("d",)))
    dd @alphabet[flat 0, (1..2, (3,))];  #-> ("a", "b", "c", "d")
    dd flat @alphabet[0, (1..2, (3,))];  #-> ("a", "b", "c", "d")

## 33.4.1 Truncating slices

Normally, referring to nonexistent elements in a slice subscript causes the output list to contain undefined values (or whatever else the collection in question chooses to return for nonexistent elements). However if the outer object passed to (one dimension of) of a positional subscript is a Range, it will be automatically truncated to the actual size of the collection:

    my @letters = &lt;a b c d e f>;
    dd @letters[3, 4, 5, 6, 7];  #-> ("d", "e", "f", Any, Any)
    dd @letters[3 .. 7];         #-> ("d", "e", "f")

From-the-end indices are allowed as range end-points.

    say @array[*-3 .. *];       # select the last three elements

A similar thing is done for lazy sequences, but it is often impossible to determine whether the sequence is infinite. Just as often, the first part of the sequence is already known, and it would be silly to pretend we did not know it. As a stopgap measure to prevent runaway generation of huge lists, a lazy subscript will not truncate as long as it does not have to lazily generate values, but once it starts generating values lazily, it will stop if it generates a value that points to a nonexistent index.

    dd @letters[0, 2, 4 ... *];     # Every other element of the array.

This feature is more for protection against accidental out-of-memory problems than for actual use. Since some lazy sequences cache their results, every time they are used in a truncation, they accumulate one more known element. Things like this should probably be avoided rather than used for effect:

    my @a = 2, 3 ... *;
    dd flat @letters[0, 7, @a]; #-> ("a", Any, "c", "d", "e", "f")
    dd flat @letters[0, 7, @a]; #-> ("a", Any, "c", "d", "e", "f", Any)

The runaway protection is not perfect. The indices are eagerly evaluated, with the only stop condition being truncation. This is to provide mostly consistent results when there is self-reference/mutation inside the indices. As such, the following will most likely hang until all memory has been consumed:

    @letters[0 xx *];

So, to safely use lazy indices, they should be one-shot things which are guaranteed to overrun the array. The following alternate formulation will produce a fully lazy result (but will not truncate):

    my $a = (0 xx *).map({ @letters[$_] }); # "a", "a", "a" ... forever

If you don't want to specify your slice as a range/sequence but still want to silently skip nonexistent elements, you can use the #:v adverb.

## 33.4.2 Zen slices

If you write a subscript without specifying any indices/keys at all, it simply returns the subscripted object itself. Since it is empty but returns everything, it is known as a "Zen slice".

It is different both from passing a Whatever-star (which, like a normal slice, always returns a List of elements no matter the type of the original object) and from passing an empty list (which returns an empty slice):

    my %bag := ("orange" => 1, "apple" => 3).Bag;
    dd %bag&lt;>;    #-> ("orange"=>1,"apple"=>3).Bag
    dd %bag{};    #-> ("orange"=>1,"apple"=>3).Bag
    dd %bag{*};   #-> (1, 3)
    dd %bag{()};  #-> ()

It is usually used to interpolate entire arrays / hashes into strings:

    my @words = "cruel", "world";
    say "Hello, @words[]!"  #-> Hello, cruel world!

# 33.5 Multiple dimensions

Dimensions in subscripts are separated by a semicolon, allowing to mix lists of elements and dimensions.

    my @twodim = (&lt;a b c>, (1, 2, 3));
    dd @twodim;
    # OUTPUT«Array @twodim = [("a", "b", "c"), (1, 2, 3)]␤»
    dd @twodim[0,1;1]; # 2nd element of both lists
    # OUTPUT«("b", 2)␤»

Multidimensional subscripts can be used to flatten nested lists.

    my @toomany = [[&lt;a b>], [1, 2]];
    dd @toomany;
    # OUTPUT«Array @toomany = [["a", "b"], [1, 2]]␤»
    dd @toomany[*;*];
    # OUTPUT«("a", "b", 1, 2)␤»

# 33.6 Modifying elements

TODO

# 33.7 Autovivification

Subscripts participate in "autovivification", i.e. the process by which arrays and hashes automatically spring into existence when needed, so that you can build nested data structures without having to pre-declare the collection type at each level:

    my $beatles;

    $beatles{"White Album"}[0] = "Back in the U.S.S.R.";  # autovivification!

    say $beatles.perl;  #-> {"White Album" => ["Back in the U.S.S.R."]}

$beatles started out undefined, but became a Hash object because it was subscripted with { } in the assignment. Similarly, $beatles{"White Album"} became an Array object due to being subscripted with [ ] in the assignment.

Note that the subscripting itself does not cause autovivification: It only happens when the result of the subscripting chain is assigned to (or otherwise mutated).

TODO: Add expanded documentation on autovivification (which affects more than just subscripts, i.e. also routines like `push`), at /language/datastructures.html, and link to it from here.

# 33.8 Binding

A subscripting expression may also be used as the left-hand-side of a binding statement. If supported by the subscripted collection's type, this replaces whatever value container would be naturally found at that "slot" of the collection, with the specified container.

The built-in Array and Hash types support this in order to allow building complex linked data structures:

    my @a = 10, 11, 12, 13;
    my $x = 1;

    @a[2] := $x;  # binding! (@a[2] and $x refer to the same container now.)

    $x++; @a[2]++;

    dd @a;  #-> [10, 11, 3, 13]&lt;>
    dd $x;  #-> 3

TODO: Come up with a more practical/motivational example snippet. TODO: Add expanded documentation on building complex data structures at /language/datastructures.html, and link to it from here.

See #method BIND-POS and #method BIND-KEY for the underlying mechanism.

# 33.9 Adverbs

The return value and possible side-effect of a subscripting operation can be controlled using adverbs.

Beware of the relatively loose precedence of operator adverbs, which may require you to add parens in compound expressions:

    if $foo || %hash&lt;key>:exists { ... }    # WRONG, tries to adverb the || op
    if $foo || (%hash&lt;key>:exists) { ... }  # correct
    if $foo or %hash&lt;key>:exists { ... }    # also correct

The supported adverbs are:

## 33.9.1 :exists

Return whether or not the requested element exists, instead of returning the element's actual value. This can be used to distinguish between elements with an undefined value, and elements that aren't part of the collection at all:

    my @foo = Any, 10;
    dd @foo[0].defined;    #-> False
    dd @foo[0]:exists;     #-> True
    dd @foo[2]:exists;     #-> False
    dd @foo[0, 2]:exists;  #-> (True, False)

    my %fruit = apple => Any, orange => 10;
    dd %fruit&lt;apple>.defined;       #-> False
    dd %fruit&lt;apple>:exists;        #-> True
    dd %fruit&lt;banana>:exists;       #-> False
    dd %fruit&lt;apple banana>:exists; #-> (True, False)

May also be negated to test for non-existence:

    dd %fruit&lt;apple banana>:!exists; #-> (False, True)

To check if all elements of a slice exist, use an all junction:

    if all %fruit&lt;apple orange banana>:exists { ... }

:exists can be combined with the #:delete and #:p/#:kv adverbs - in which case the behavior is determined by those adverbs, except that any returned element value is replaced with the corresponding Bool indicating element existence.

See #method EXISTS-POS and #method EXISTS-KEY for the underlying mechanism.

## 33.9.2 :delete

Delete the element from the collection or, if supported by the collection, creates a hole at the given index, in addition to returning its value.

    my @tens = 0, 10, 20, 30;
    dd @tens[3]:delete;     #-> 30
    dd @tens;               #-> [0, 10, 20]&lt;>

    my %fruit = apple => 5, orange => 10, banana => 4, peach => 17;
    dd %fruit&lt;apple>:delete;         #-> 5
    dd %fruit&lt;peach orange>:delete;  #-> (17, 10)
    dd %fruit;                       #-> {banana => 4}&lt;>

Note that assigning Nil will revert the container at the given index to it's default value. It will not create a hole. The created holes can be tested for with :exists but iteration will not skip them and produce undefined values instead.

    my @a = 1, 2, 3;
    @a[1]:delete;
    say @a[1]:exists;
    # OUTPUT«False␤»
    .say for @a;
    # OUTPUT«1␤(Any)␤3␤»

With the negated form of the adverb, the element is not actually deleted. This means you can pass a flag to make it conditional:

    dd %fruit&lt;apple> :delete($flag);  # deletes the element only if $flag is
                                      # true, but always returns the value.

Can be combined with the #:exists and #:p/#:kv/#:k/#:v adverbs - in which case the return value will be determined by those adverbs, but the element will at the same time also be deleted.

See #method DELETE-POS and #method DELETE-KEY for the underlying mechanism.

## 33.9.3 :p

Return both the index/key and the value of the element, in the form of a Pair, and silently skip nonexistent elements:

    my @tens = 0, 10, 20, 30;
    dd @tens[1]:p;        #-> 1 => 10
    dd @tens[0, 4, 2]:p;  #-> (0 => 0, 2 => 20)

    my %month = Jan => 1, Feb => 2, Mar => 3;
    dd %month&lt;Feb>:p;          #-> "Feb" => 2
    dd %month&lt;Jan Foo Mar>:p;  #-> ("Jan" => 1, "Mar" => 3)

If you don't want to skip nonexistent elements, use the negated form:

    dd %month&lt;Jan Foo Mar>:!p;  #-> ("Jan" => 1, "Foo" => Any, "Mar" => 3)

Can be combined with the #:exists and #:delete adverbs.

See also the pairs routine.

## 33.9.4 :kv

Return both the index/key and the value of the element, in the form of a List, and silently skip nonexistent elements. When used on a slice, the return value is a single flat list of interleaved keys and values:

    my @tens = 0, 10, 20, 30;
    dd @tens[1]:kv;        #-> (1, 10)
    dd @tens[0, 4, 2]:kv;  #-> (0, 0, 2, 20)

    my %month = Jan => 1, Feb => 2, Mar => 3;
    dd %month&lt;Feb>:kv;          #-> ("Feb", 2)
    dd %month&lt;Jan Foo Mar>:kv;  #-> ("Jan", 1, "Mar", 3)

If you don't want to skip nonexistent elements, use the negated form:

    dd %month&lt;Jan Foo Mar>:!kv;  #-> ("Jan", 1, "Foo", Any, "Mar", 3)

This adverb is commonly used to iterate over slices:

    for %month&lt;Feb Mar>:kv -> $month, $i {
        say "$month had {Date.new(2015, $i, 1).days-in-month} days in 2015"
    }

Can be combined with the #:exists and #:delete adverbs.

See also the kv routine.

## 33.9.5 :k

Return only the index/key of the element, rather than its value, and silently skip nonexistent elements:

    my @tens = 0, 10, 20, 30;
    dd @tens[1]:k;        #-> 1
    dd @tens[0, 4, 2]:k;  #-> (0, 2)

    my %month = Jan => 1, Feb => 2, Mar => 3;
    dd %month&lt;Feb>:k;          #-> "Feb"
    dd %month&lt;Jan Foo Mar>:k;  #-> ("Jan", "Mar")

If you don't want to skip nonexistent elements, use the negated form:

    dd %month&lt;Jan Foo Mar>:!k;  #-> ("Jan", "Foo", "Mar")

See also the keys routine.

## 33.9.6 :v

Return the bare value of the element (rather than potentially returning a mutable value container), and silently skip nonexistent elements:

    my @tens = 0, 10, 20, 30;
    dd @tens[1]:v;        #-> 10
    dd @tens[0, 4, 2]:v;  #-> (0, 20)
    @tens[3] = 31;        # OK
    @tens[3]:v = 31;      # ERROR, cannot assign to immutable integer value

    my %month = Jan => 1, Feb => 2, Mar => 3;
    dd %month&lt;Feb>:v;          #-> 2
    dd %month&lt;Jan Foo Mar>:v;  #-> (1, 3)

If you don't want to skip nonexistent elements, use the negated form:

    dd %month&lt;Jan Foo Mar>:!v;  #-> (1, Any, 3)

See also the values routine.

# 33.10 Custom types

The subscripting interfaces described on this page are not meant to be exclusive to Perl 6's built-in collection types - you can (and should) reuse them for any custom type that wants to provide access to data by index or key.

You don't have to manually overload the postcircumfix [ ] and postcircumfix { } operators and re-implement all their magic, to achieve that - instead, you can rely on the fact that their standard implementation dispatches to a well-defined set of low-level methods behind the scenes. For example:

when you write: | this gets called behind the scenes:
--- | ---
%foo<aa> | %foo.AT-KEY("aa")
%foo<aa>:delete | %foo.DELETE-KEY("aa")
@foo[3, 4, 5] | @foo.AT-POS(3), @foo.AT-POS(4), @foo.AT-POS(5)
@foo[*-1] | @foo.AT-POS(@foo.elems - 1)

So in order to make subscripting work, you only have to implement or delegate those low-level methods (detailed below) for your custom type.

If you do, you should also let your type compose the Positional or Associative role, respectively. This doesn't add any functionality per se, but announces (and may be used to check) that the type implements the corresponding subscripting interface.

## 33.10.1 Custom type example

TODO: Maybe factor this out into a tutorial page

Imagine a HTTP::Header type which, despite being a custom class with special behavior, can be indexed like a hash:

    my $request = HTTP::Request.new(GET => "perl6.org");
    say $request.header.WHAT;  #-> (HTTP::Header)

    $request.header&lt;Accept> = "text/plain";
    $request.header{'Accept-' X~ &lt;Charset Encoding Language>} = &lt;utf-8 gzip en>;
    $request.header.push('Accept-Language' => "fr");  # like .push on a Hash

    say $request.header&lt;Accept-Language>.perl;  #-> ["en", "fr"]

    my $rawheader = $request.header.Str;  # stringify according to HTTP spec

The simplest way to implement this class, would be to give it an attribute of type Hash, and delegate all subscripting and iterating related functionality to that attribute (using a custom type constraint to make sure users don't insert anything invalid into it):

    class HTTP::Header does Associative is Iterable {
        subset StrOrArrayOfStr where Str | ( Array &amp; {.all ~~ Str} );

        has %!fields of StrOrArrayOfStr
                     handles &lt;AT-KEY EXISTS-KEY DELETE-KEY push
                              iterator list kv keys values>;

        method Str { #`[not shown, for brevity] }
    }

However, HTTP header field names are supposed to be case-insensitive (and preferred in camel-case). We can accommodate this by taking the *-KEY and push methods out of the handles list, and implementing them separately like this:

    method AT-KEY     ($key) is rw { %!fields{normalize-key $key}        }
    method EXISTS-KEY ($key)       { %!fields{normalize-key $key}:exists }
    method DELETE-KEY ($key)       { %!fields{normalize-key $key}:delete }
    method push(*@_) { #`[not shown, for brevity] }

    sub normalize-key ($key) { $key.subst(/\w+/, *.tc, :g) }

Note that subscripting %!fields returns an appropriate rw container, which our AT-KEY can simply pass on.

However, we may prefer to be less strict about user input and instead take care of sanitizing the field values ourselves. In that case, we can remove the StrOrArrayOfStr type constraint on %!fields, and replace our AT-KEY implementation with one that returns a custom Proxy container which takes care of sanitising values on assignment:

    multi method AT-KEY (::?CLASS:D: $key) is rw {
        my $element := %!fields{normalize-key $key};

        Proxy.new(
            FETCH => method () { $element },

            STORE => method ($value) {
                $element = do given $value».split(/',' \s+/).flat {
                    when 1  { .[0] }    # a single value is stored as a string
                    default { .Array }  # multiple values are stored as an array
                }
            }
        );
    }

Note that declaring the method as multi and restricting it to :D (defined invocants) makes sure that the undefined case is passed through to the default implementation provided by Any (which is involved in auto-vivification).

## 33.10.2 Methods to implement for positional subscripting

In order to make index-based subscripting via postcircumfix [ ] work for your custom type, you should implement at least elems, AT-POS and EXISTS-POS - and optionally others as detailed below.

### 33.10.2.1 method elems

    multi method elems(::?CLASS:D:)

Expected to return a number indicating how many subscriptable elements there are in the object. May be called by users directly, and is also called by postcircumfix [ ] when indexing elements from the end, as in @foo[*-1].

If not implemented, your type will inherit the default implementation from Any that always returns 1 for defined invocants - which is most likely not what you want. So if the number of elements cannot be known for your positional type, add an implementation that fails or dies, to avoid silently doing the wrong thing.

### 33.10.2.2 method AT-POS

When modifying this section, please also adapt the AT-KEY section accordingly as they are very similar.

    multi method AT-POS (::?CLASS:D: $index)

TODO: Cover the case of multi-dim indices (also for all the other methods below), after jnthn's ongoing refactor is finished.

Expected to return the element at position $index. This is what postcircumfix [ ] normally calls.

If you want an element to be mutable (like they are for the built-in Array type), you'll have to make sure to return it in the form of an item container that evaluates to the element's value when read, and updates it when assigned to. (Remember to use return-rw or the is rw routine trait to make that work; see the example.)

### 33.10.2.3 method EXISTS-POS

When modifying this section, please also adapt the EXISTS-KEY section accordingly as they are very similar.

    multi method EXISTS-POS (::?CLASS:D: $index)

Expected to return a Bool indicating whether or not there is an element at position $index. This is what postcircumfix [ ] calls when invoked like @foo[42]:exists.

What "existence" of an element means, is up to your type.

If you don't implement this, your type will inherit the default implementation from Any, which returns True for 0 and False for any other index - which is probably not what you want. So if checking for element existence cannot be done for your type, add an implementation that fails or dies, to avoid silently doing the wrong thing.

### 33.10.2.4 method DELETE-POS

When modifying this section, please also adapt the DELETE-KEY section accordingly as they are very similar.

    multi method DELETE-POS (::?CLASS:D: $index)

Expected to delete the element at position $index, and return the value it had. This is what postcircumfix [ ] calls when invoked like @foo[42]:delete.

What "deleting" an element means, is up to your type.

Implementing this method is optional; if you don't, users trying to delete elements from an object of this type will get an appropriate error message.

### 33.10.2.5 method ASSIGN-POS

When modifying this section, please also adapt the ASSIGN-KEY section accordingly as they are very similar.

    multi method ASSIGN-POS (::?CLASS:D: $index, $new)

Expected to set the element at position $index to the value $new. Implementing this is entirely optional; if you don't, self.AT-POS($index) = $new is used instead, and if you do, you should make sure it has the same effect.

This is meant as an opt-in performance optimization, so that simple assignments like @numbers[5] = "five" can operate without having to call AT-POS (which would have to create and return a potentially expensive container object).

Note that implementing ASSIGN-POS does not relieve you from making AT-POS an rw method though, because less trivial assignments/modifications such as @numbers[5]++ will still use AT-POS.

### 33.10.2.6 method BIND-POS

When modifying this section, please also adapt the BIND-KEY section accordingly as they are very similar.

    multi method BIND-POS (::?CLASS:D: $index, \new)

Expected to bind the value or container new to the slot at position $index, replacing any container that would be naturally found there. This is what is called when you write:

    my $x = 10;
    @numbers[5] := $x;

The generic Array class supports this in order to allow building complex linked data structures, but for more domain-specific types it may not make sense, so don't feel compelled to implement it. If you don't, users will get an appropriate error message when they try to bind to a positional slot of an object of this type.

## 33.10.3 Methods to implement for associative subscripting

In order to make key-based subscripting via postcircumfix { } work for your custom type, you should implement at least AT-KEY and EXISTS-KEY - and optionally others as detailed below.

### 33.10.3.1 method AT-KEY

When modifying this section, please also adapt the AT-POS section accordingly as they are very similar.

    multi method AT-KEY (::?CLASS:D: $key)

Expected to return the element associated with $key. This is what postcircumfix { } normally calls.

If you want an element to be mutable (like they are for the built-in Hash type), you'll have to make sure to return it in the form of an item container that evaluates to the element's value when read, and updates it when assigned to. (Remember to use return-rw or the is rw routine trait to make that work; see the example.)

On the other hand if you want your collection to be read-only, feel free to return non-container values directly.

### 33.10.3.2 method EXISTS-KEY

When modifying this section, please also adapt the EXISTS-POS section accordingly as they are very similar.

    multi method EXISTS-KEY (::?CLASS:D: $key)

Expected to return a Bool indicating whether or not there is an element associated with $key. This is what postcircumfix { } calls when invoked like %foo<aa>:exists .

What "existence" of an element means, is up to your type.

If you don't implement this, your type will inherit the default implementation from Any, which always returns False - which is probably not what you want. So if checking for element existence cannot be done for your type, add an implementation that fails or dies, to avoid silently doing the wrong thing.

### 33.10.3.3 method DELETE-KEY

When modifying this section, please also adapt the DELETE-POS section accordingly as they are very similar.

    multi method DELETE-KEY (::?CLASS:D: $key)

Expected to delete the element associated with $key, and return the value it had. This is what postcircumfix { } calls when invoked like %foo<aa>:delete .

What "deleting" an element means, is up to your type - though it should usually cause EXISTS-KEY to become False for that key.

Implementing this method is optional; if you don't, users trying to delete elements from an object of this type will get an appropriate error message.

### 33.10.3.4 method ASSIGN-KEY

When modifying this section, please also adapt the ASSIGN-POS section accordingly as they are very similar.

    multi method ASSIGN-KEY (::?CLASS:D: $key, $new)

Expected to set the element associated with $key to the value $new. Implementing this is entirely optional; if you don't, self.AT-KEY($key) = $new is used instead, and if you do, you should make sure it has the same effect.

This is meant as an opt-in performance optimization, so that simple assignments %age<Claire> = 29 can operate without having to call AT-KEY (which would have to create and return a potentially expensive container object).

Note that implementing ASSIGN-KEY does not relieve you from making AT-KEY an rw method though, because less trivial assignments/modifications such as %age<Claire>++ will still use AT-KEY.

### 33.10.3.5 method BIND-KEY

When modifying this section, please also adapt the BIND-POS section accordingly as they are very similar.

    multi method BIND-KEY (::?CLASS:D: $key, \new)

Expected to bind the value or container new to the slot associated with $key, replacing any container that would be naturally found there. This is what is called when you write:

    my $x = 10;
    %age&lt;Claire> := $x;

The generic Hash class supports this in order to allow building complex linked data structures, but for more domain-specific types it may not make sense, so don't feel compelled to implement it. If you don't, users will get an appropriate error message when they try to bind to an associative slot of an object of this type.

# 34 Syntax

General rules of Perl 6 syntax

Perl 6 borrows many concepts from human language. Which is not surprising, considering it was designed by a linguist.

It reuses common elements in different contexts, has the notion of nouns (terms) and verbs (operators), is context-sensitive (in the every day sense, not necessarily in the Computer Science interpretation), so a symbol can have a different meaning depending on whether a noun or a verb is expected.

It is also self-clocking, so that the parser can detect most of the common errors and give good error messages.

# 34.1 Lexical Conventions

Perl 6 code is Unicode text, current implementations support UTF-8 as the input encoding.

## 34.1.1 Free Form

It is free-form, in the sense that you are mostly free to chose the amount of whitespace you chose, though in some cases, the presence or absence of whitespace carries meaning.

So you can write

    if True {
         say "Hello";
     }

or

        if True {
     say "Hello";
             }

or

    if True { say "Hello" }

or even

    if True {say "Hello"}

though you can't leave out any of the remaining whitespace.

## 34.1.2 Unspace

In many places where the compiler would not allow a space you can use any whitespace that is quoted with a backslash. Unspaces in tokens are not supported. Newlines that are unspaced still count when the compiler produces line numbers. Usecases for unspace are separation of postfix operators and routine argument lists.

    sub alignment(+@l) { +@l };$
    sub long-name-alignment(+@l) { +@l };$
    alignment\         (1,2,3,4)>>.say;$
    long-name-alignment(3,5)\   >>.say;$

## 34.1.3 Separating Statements

A Perl 6 program is a list of statements, separated by semicolons ;. A semicolon after the final statement (or after the final statement inside a block) is optional, though it's good form to include it.

A closing curly brace followed by a newline character implies a statement separator, which is why you don't need to write a semicolon after an if statement block.

    if True {
         say "Hello";
     }
     say "world";

Both semicolons are optional here, but leaving them out increases the chance of syntax errors when adding more lines later.

You do need to include a semicolon between the if block and the say statement if you want them all on one line.

    if True { say "Hello" }; say "world";
     #                     ^^^ this ; is required

## 34.1.4 Comments

Comments are parts of the program text only intended for human readers, and the Perl 6 compilers does not evaluate them as program text.

Comments count as whitespace in places where the absence of presence of whitespace disambiguates possible parses.

### 34.1.4.1 Single-line comments

The most common form of comments in Perl 6 starts with a single hash character # and goes until the end of the line.

    if $age > 250 {     # catch obvious outliers
         # this is another comment!
         die "That doesn't look right"
     }

### 34.1.4.2 Multi-line / embedded comments

Multi-line and embedded comments start with a hash character, followed by a backtick, and then some opening bracketing character, and end with the matching closing bracketing character. The content can not only span multiple lines, but can also be embedded inline.

    if #`( why would I ever write an inline comment here? ) True {
         say "something stupid";
     }

Brackets inside the comment can be nested, so in #`{ a { b } c }, the comment goes until the very end of the string. You may also use more complex brackets, such as #`{{ double-curly-brace }}, which might help disambiguate from nested brackets.

### 34.1.4.3 Pod comments

Pod syntax can be used for multi-line comments

    say "this is code";

     =begin comment

     Here are several
     lines
     of comment

     =end comment

     say 'code again';

## 34.1.5 Identifiers

Identifiers are a grammatical building block that occur in several places. An identifier is a primitive name, and must start with an alphabetic character (or an underscore), followed by zero or more word characters (alphabetic, underscore or number). You can also embed dashes - or single quotes ' in the middle, but not two in a row, and only if followed immediately by an alphabetic character.

    # valid identifiers:
    x
    something-longer
    with-numbers1234
    don't
    fish-food

    # not valid identifiers:
    with-numbers1234-5
    42
    is-prime?
    fish--food

Names of constants, types (including classes and modules) and routines (subs and methods) are identifiers, and they also appear in variable names (usually proceeded by a sigil; see variables for more details.)

Namespaces are provided by packages. By separating identifiers with double colons, the right most name is inserted into existing or automatically created packages.

    my Int $Foo::Bar::buzz = 42;
    dd $Foo::Bar::buzz; # OUTPUT«Int $v = 42␤»

# 34.2 Statements and Expressions

Perl 6 programs are made of lists of statements. A special case of a statement is an expression, which returns a value. For example if True { say 42 } is syntactically a statement, but not an expression, whereas 1 + 2 is an expression (and thus also a statement).

The do prefix turns statements into expressions. So while

    my $x = if True { 42 };     # Syntax error!

is an error,

    my $x = do if True { 42 };

assigns the return value of the if statement (here 42) to the variable $x.

# 34.3 Terms

Terms are the basic nouns that, optionally together with operators, can form expressions. Examples for terms are variables ($x), barewords such as type names (Int), literals (42), declarations (sub f() { }) and calls (f()).

For example, in the expression 2 * $salary, 2 and $salary are two terms (an integer literal and a variable).

## 34.3.1 Variables

Variables typically start with a special character called the sigil, and are followed by an identifier. Variables must be declared before you can use them.

    # declaration:
    my $number = 21;
    # usage:
    say $number * 2;

See the documentation on variables for more details.

## 34.3.2 Barewords (Constants, Type Names)

Pre-declared identifiers can be terms on their own. Those are typically type names or constants, but also the term self which refers to an object that a method was called on (see objects), and sigiless variables:

    say Int;                # (Int)
    #   ^^^ type name (built in)

    constant answer = 42;
    say answer;
    #   ^^^^^^ constant

    class Foo {
        method type-name {
            self.^name;
          # ^^^^ built-in term 'self'
        }
    }
    say Foo.type-name;     # Foo
    #   ^^^ type name

## 34.3.3 Packages and Qualified Names

Named entities, such as variables, constants, classes, modules, subs, etc, are part of a namespace. Nested parts of a name use :: to separate the hierarchy. Some examples:

    $foo                # simple identifiers
    $Foo::Bar::baz      # compound identifiers separated by ::
    $Foo::($bar)::baz   # compound identifiers that perform interpolations
    Foo::Bar::bob(23)   # function invocation given qualified name

See the documentation on packages for more details.

## 34.3.4 Literals

A literal is a representation of a constant value in source code. Perl 6 has literals for several built-in types, like strings, several numeric types, pairs and more.

### 34.3.4.1 String literals

String literals are surrounded by quotes:

    say 'a string literal';
    say "a string literal\nthat interprets escape sequences";

See quoting for many more options.

### 34.3.4.2 Number literals

Number literals are generally specified in base ten, unless a prefix like 0x (hexadecimal, base 16), 0o (octal, base 8) or 0b (binary, base 2) or an explicit base in adverbial notation like :16<A0> specifies it otherwise. Unlike other programming languages, leading zeros do not indicate base 8; instead a compile-time warning is issued

In all literal formats, you can use underscores to group digits; they don't carry any semantic; the following literals all evaluate to the same number:

    1000000
    1_000_000
    10_00000
    100_00_00

#### 34.3.4.2.1 Int literals

Integers default to signed base-10, but you can use other bases. For details, see Int.

    -2
    12345
    0xBEEF      # base 16
    0o755       # base 8
    :3&lt;1201>    # arbitrary base, here base 3

#### 34.3.4.2.2 Rat literals

Rat literals (rationals) are very common, and take the place of decimals or floats in many other languages. Integer division also results in a Rat.

    1.0
    3.14159
    -2.5
    :3&lt;21.0012> # Base 3 rational
    2/3         # Not actually a literal, but still a Rat

#### 34.3.4.2.3 Num literals

Scientific notation with an exponent to base ten after an e produces floating point number:

    1e0
    6.022e23
    1e-9
    -2e48

#### 34.3.4.2.4 Complex literals

Complex numbers are written either as an imaginary number (which is just a rational number with postfix i appended), or as a sum of a real and an imaginary number:

    1+2i
    6.123e5i

### 34.3.4.3 Pair literals

Pairs are made of a key and a value, and there are two basic forms for constructing them: key => 'value' and :key('value').

#### 34.3.4.3.1 Arrow pairs

Arrow pairs can have an expression or an identifier on the left-hand side:

    identifier => 42
    "identifier" => 42
    ('a' ~ 'b') => 1

#### 34.3.4.3.2 Adverbial pairs (colon pairs)

Short forms without explicit values:

    my $thing = 42;
    :$thing                 # same as  thing => $thing
    :thing                  # same as  thing => True
    :!thing                 # same as  thing => False

The variable form also works with other sigils, like :&callback or :@elements.

Long forms with explicit values:

    :thing($value)              # same as  thing => $value
    :thing&lt;quoted list>         # same as  thing => &lt;quoted list>
    :thing['some', 'values']    # same as  thing => ['some', 'values']
    :thing{a => 'b'}            # same as  thing => { a => 'b' }

### 34.3.4.4 Array literals

A pair of square brackets can surround an expression to form an itemized Array literal; typically there is a comma-delimited list inside:

    say ['a', 'b', 42].join(' ');   # a b 42
    #   ^^^^^^^^^^^^^^ Array constructor

The array constructor flattens non-itemized arrays and lists, but not itemized arrays themselves:

    my @a = 1, 2;
    # flattens:
    say [@a, 3, 4].elems;       # 4

    # does not flatten:
    say [[@a], [3, 4]].elems;   # 2

### 34.3.4.5 Hash literals

A pair of curly braces can surround a list of pairs to form a Hash literal; typically there is a comma-delimited list of pairs inside. If a non-pair is used, it is assumed to be a key and the next element is the value. Most often this is used with simple arrow pairs.

    say { a => 3, b => 23, :foo, :dog&lt;cat>, "french", "fries" };
    # a => 3, b => 23, dog => cat, foo => True, french => fries

    say {a => 73, foo => "fish"}.keys.join(" ");   # a foo
    #   ^^^^^^^^^^^^^^^^^^^^^^^^ Hash constructor

When assigning to a % sigil variable, the curly braces are optional.

    my %ages = fred => 23, jean => 87, ann => 4;

By default keys in { } are forced to strings. To compose a hash with non-string keys, use a colon prefix:

    my $when = :{ (now) => "Instant", (DateTime.now) => "DateTime" };

Note that with objects as keys, you cannot access non-string keys as strings:

    :{ -1 => 41, 0 => 42, 1 => 43 }&lt;0>  # Any
    :{ -1 => 41, 0 => 42, 1 => 43 }{0}  # 42

### 34.3.4.6 Regex literals

A Regex is declared with slashes like /foo/. Note that this // syntax is shorthand for the full rx// syntax.

    /foo/          # Short version
    rx/foo/        # Longer version
    Q :regex /foo/ # Even longer version

    my $r = /foo/; # Regexes can be assigned to variables

### 34.3.4.7 Signature literals

Signatures can be used standalone for pattern matching, in addition to the typical usage in sub and block declarations. A standalone signature is declared starting with a colon:

    say "match!" if 5, "fish" ~~ :(Int, Str) #=> match!

    my $sig = :(Int $a, Str);
    say "match!" if (5, "fish") ~~ $sig; #=> match!

    given "foo", 42 {
      when :(Str, Str) { "This won't match" }
      when :(Str, Int $n where $n > 20) { "This will!" }
    }

See the Signatures documentation for more about signatures.

## 34.3.5 Declarations

### 34.3.5.1 Variable declaration

    my $x;                          # simple lexical variable
    my $x = 7;                      # initialize the variable
    my Int $x = 7;                  # declare the type
    my Int:D $x = 7;                # specify that the value must be defined (not undef)
    my Int $x where { $_ > 3 } = 7; # constrain the value based on a function
    my Int $x where * > 3 = 7;      # same constraint, but using L&lt;Whatever> short-hand

See Variable Declarators and Scope for more details on other scopes (our, has).

### 34.3.5.2 Subroutine declaration

    # The signature is optional
    sub foo { say "Hello!" }

    sub say-hello($to-whom) { say "Hello $to-whom!" }

You can also assign subroutines to variables.

    my &amp;f = sub { say "Hello!" } # Un-named sub
    my &amp;f = -> { say "Hello!" }  # Lambda style syntax. The &amp; sigil indicates the variable holds a function
    my $f = -> { say "Hello!" }  # Functions can also be put into scalars

### 34.3.5.3 Module, Class, Role, and Grammar declaration

There are several types of compilation units (packages), each declared with a keyword, a name, some optional traits, and a body of functions.

    module Gar { }

    class Foo { }

    role Bar { }

    grammar Baz { }

You can declare a unit of things without explicit curly brackets.

    unit module Gar;
    # ... stuff goes here instead of in {}'s

### 34.3.5.4 Multi-dispatch declaration

See also Multi-dispatch.

Subroutines can be declared with multiple signatures.

    multi sub foo() { say "Hello!" }
    multi sub foo($name) { say "Hello $name!" }

Inside of a class, you can also declare multi-dispatch methods.

    multi method greet { }
    multi method greet(Str $name) { }

# 34.4 Subroutine calls

See functions.

TODO

    foo;   # Invoke the function foo with no arguments
    foo(); # Invoke the function foo with no arguments
    &amp;f();  # Invoke &amp;f, which contains a function
    &amp;f.(); # Same as above, needed to make the following work
    my @functions = ({say 1}, {say 2}, {say 3});
    @functions>>.();

    # Method invocation. Object (instance) is $person, method is set-name-age
    $person.set-name-age('jane', 98);  # Most common way
    $person.set-name: 'jane', 98;      # Precedence drop
    set-name($person: 'jane', 98);     # Invocant marker

# 34.5 Operators

See Operators for lots of details.

Operators are functions with a more symbol heavy and composable syntax. Like other functions, operators can be multi-dispatch to allow for context-specific usage.

There are five types (arrangements) for operators, each taking either one or two arguments.

    ++$x           # prefix, operator comes before single input
    5 + 3          # infix, operator is between two inputs
    $x++           # postfix, operator is after single input
    &lt;the blue sky> # circumfix, operator surrounds single input
    %foo&lt;bar>      # postcircumfix, operator comes after first input and surrounds second

## 34.5.1 Meta Operators

Operators can be composed. A common example of this is combining an infix (binary) operator with assignment. You can combine assignment with any binary operator.

    $x += 5     # Adds 5 to $x, same as $x = $x + 5
    $x min= 3   # Sets $x to the smaller of $x and 3, same as $x = $x min 3
    $x .= child # Equivalent to $x = $x.child

Wrap an infix operator in [ ] to create a new reduction operator that works on a single list of inputs, resulting in a single value.

    [+] &lt;1 2 3 4 5>         # 15
    (((1 + 2) + 3) + 4) + 5 # equivalent expanded version

Wrap an infix operator in « » (or the ASCII equivalent ) to create a new hyper operator that works pairwise on two lists.

    &lt;1 2 3> «+» &lt;4 5 6> # &lt;5 7 9>

The direction of the arrows indicates what to do when the lists are not the same size.

    @a «+« @b # Result is the size of @b, elements from @a will be re-used
    @a »+» @b # Result is the size of @a, elements from @b will be re-used
    @a «+» @b # Result is the size of the biggest input, the smaller one is re-used
    @a »+« @b # Exception if @a and @b are different sizes

You can also wrap a unary operator with a hyper operator.

    -« &lt;1 2 3> # &lt;-1 -2 -3>

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

# 35.1 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., ' ')].

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

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

4. Consecutive row separator lines are illegal.

5. Having unequal numbers of columns in table rows is illegal.

# 35.2 Best Practices

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

- Heading and single-line content

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

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

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

# 35.3 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
         =======================
         Zebra  +   4  + Cookies
         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

# 35.4 Bad Tables

Following are examples of invalid (Bad) tables, and they should trigger an unhandled exception during parsing. They are taken from tests used in the table-pod-fix project mentioned above. After acceptance of the project's code into the Rakudo source, they will be added to the current Specification Tests. Note they may not trigge an exception at the moment, but they will after the project's code is integrated.

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

    =begin table
     r0c0 +  r0c1 | r0c3
     =end table

- Mixed visual and whitespace column separator type in the same table are not allowed:

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

- Different numbers of columns in two or more rows are not allowed:

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

- Two consecutive row separators are not allowed:

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

# 35.5 Ugly Tables

Following are examples of valid tables that are probably intended to be two columns, but the columns are not aligned well so the tables will either parse as a single-column table or trigger an exception depending on whether the table uses WS column seprartors or visible column separators.

- 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 doen't have an adjacent WS character on both sides of it. This is an invalid table because the first row has two columns while the second row has only one column, and it will trigger an exception..

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

# 36 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.

# 36.1 Literals

## 36.1.1 Int

    42
    12_300_00
    :16&lt;DEAD_BEEF>

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

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

## 36.1.3 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.

## 36.1.4 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.

## 36.1.5 Regex

    / match some text /
    rx/slurp \s rest (.*) $/

These forms produce regex literals. See Quoting Constructs.

## 36.1.6 Pair

    a => 1
    'a' => 'b'
    :identifier
    :!identifier
    :identifier&lt;value>
    :identifier&lt;value1 value2>
    :identifier($value)
    :identifier['val1', 'val2']
    :identifier{key1 => 'val1', key2 => 'value2'}
    :$item
    :@array
    :%hash
    :&amp;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 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).

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 .

## 36.1.7 List

    ()
    1, 2, 3
    &lt;a b c>
    «a b c»
    qw/a b c/

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

## 36.1.8 term *

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

# 36.2 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:&lt;forty-two> { 42 };
    say forty-two

or as constants:

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

## 36.2.1 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.

## 36.2.2 term now

Returns an Instant object representing the current time.

## 36.2.3 term time

Returns the current POSIX time as an Int.

## 36.2.4 term rand

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

## 36.2.5 term π

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

## 36.2.6 term pi

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

## 36.2.7 term τ

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

## 36.2.8 term tau

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

## 36.2.9 term e

Returns Euler's number.

## 36.2.10 term i

Returns the imaginary unit (for Complex numbers).

# 36.3 Variables

Variables are discussed in the variable language docs.

# 36.4 Constants

Constants are declared with constant and do not require a sigil. The RHS is evaluated at compile time, what may be too early to make sense.

    constant Pi = 3.123; # if you happen to be Babylonian

# 37 Testing

Writing and running tests in Perl 6

Testing code is an integral part of software development. For instance, how can one be sure the code works if there isn't some way to verify it behaves as desired? This is the role of tests: to provide automated, repeatable verifications of code behaviour.

In Perl 6, the Test module provides a testing framework similar to the traditional Perl 5 Test::More module. Thus, anyone familiar with Test::More (and friends) should be comfortable with Perl 6's Test module. The Test module is the testing module used by the official spectest suite.

The testing functions emit output conforming to the Test Anything Protocol.

# 37.1 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;
    use Test;      # a Standard module included with Rakudo
    use lib 'lib';

    plan $num-tests;

    # .... tests

We ensure that we're using Perl 6, via the use v6 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 tell the framework that we are done testing.

# 37.2 Running tests

One can run tests individually by specifying the test filename on the command line:

    $ perl6 t/test-filename.t

Or via the prove command from Perl 5, where one specifies perl6 as the executable to run the tests:

    $ prove --exec perl6 -r t

# 37.3 Test plans

- plan($count)

Specify the total number of tests. Usually written at the beginning of a test file.

    plan 15;   # expect to run 15 tests

In subtests, plan is used to specify the total number of tests within the subtest.

If a plan is used, it is not necessary to denote the end of testing with done-testing.

- done-testing

Specify that testing has finished. Use this function when you do not as yet have a plan for the number of tests to run. A plan is thus not required when using done-testing.

# 37.4 Testing return values

The Test module exports various functions that check the return value of a given expression, and produce standardized test output accordingly.

In practice, the expression will often be a call to a function or method that you want to unit-test.

## 37.4.1 By truthiness

- ok($value, $description?), nok($condition, $description?)

The ok function marks a test as passed if the given $value evaluates to True in a boolean context. The nok function marks a test as passed if the given value evaluates to False. Both functions accept an optional $description of the test.

    ok  $response.success, 'HTTP response was successful';
    nok $query.error,      'Query completed without error';

In principle you could use ok for every kind of comparison test, by including the comparison in the expression passed to $value:

    ok factorial(6) == 720, 'Factorial - small integer';

However, where possible it is better to use one of the specialized comparison test functions below, because they can print more helpful diagnostics output in case the comparison fails.

## 37.4.2 By string comparison

- is($value, $expected, $description?)

Marks a test as passed if $value and $expected compare positively with the eq operator. The function accepts an optional $description of the test.

    is $pdf-document.author, "Joe", 'Retrieving the author field';
    is factorial(6),         720,   'Factorial - small integer';

As a special case, if $expected is a type object, the comparison uses the === operator instead:

    my Int $a;
    is $a, Int, 'The variable $a is an unassigned Int';

- isnt($value, $expected, $description?)

Marks a test as passed if $value and $expected are not equal using the same rules as is(). The function accepts an optional $description of the test.

    isnt pi, 3, 'The constant π is not equal to 3';

    my Int $a = 23;
    $a = Nil;
    isnt $a, Nil, 'Nil should not survive being put in a container';

## 37.4.3 By approximate numeric comparison

- is-approx($value, $expected, $description?)

Marks a test as passed if the $value and $expected numerical values are approximately equal to each other. The subroutine can be called in numerous ways that let you test using relative tolerance ($rel-tol) or absolute tolerance ($abs-tol) of different values.

If no tolerance is set, it will default to an absolute tolerance of 1e-5.

    my Numeric ($value, $expected, $abs-tol, $rel-tol) = ...

    is-approx $value, $expected;
    is-approx $value, $expected, 'test description';

    is-approx $value, $expected, $abs-tol;
    is-approx $value, $expected, $abs-tol, 'test description';

    is-approx $value, $expected, :$rel-tol;
    is-approx $value, $expected, :$rel-tol, 'test description';

    is-approx $value, $expected, :$abs-tol;
    is-approx $value, $expected, :$abs-tol, 'test description';

    is-approx $value, $expected, :$abs-tol, :$rel-tol;
    is-approx $value, $expected, :$abs-tol, :$rel-tol, 'test description';

### 37.4.3.1 Absolute Tolerance

When an absolute tolerance is set, it's used as the actual maximum value by which the $value and $expected can differ. For example:

    is-approx 3, 4, 2; # success
    is-approx 3, 6, 2; # fail

    is-approx 300, 302, 2; # success
    is-approx 300, 400, 2; # fail
    is-approx 300, 600, 2; # fail

Regardless of values given, the difference between them cannot be more than 2.

### 37.4.3.2 Relative Tolerance

When a relative tolerance is set, the test checks the relative difference between values. Given the same tolerance, the larger the numbers given, the larger the value they can differ by can be.

For example:

    is-approx 10, 10.5, :rel-tol&lt;0.1>; # success
    is-approx 10, 11.5, :rel-tol&lt;0.1>; # fail

    is-approx 100, 105, :rel-tol&lt;0.1>; # success
    is-approx 100, 115, :rel-tol&lt;0.1>; # fail

Both versions use 0.1 for relative tolerance, yet the first can differ by about 1 while the second can differ by about 10. The function used to calculate the difference is:

                  |value - expected|
     ⁣rel-diff = ────────────────────────
                max(|value|, |expected|)

and the test will fail if rel-diff is higher than $rel-tol.

### 37.4.3.3 Both Absolute and Relative Tolerance Specified

    is-approx $value, $expected, :rel-tol&lt;.5>, :abs-tol&lt;10>;

When both absolute and relative tolerances are specified, each will be tested independently, and the is-approx test will succeed only if both pass.

## 37.4.4 By structural comparison

- is-deeply($value, $expected, $description?)

Marks a test as passed if $value and $expected compare positively with the eqv operator. This is the best way to check for equality of (deep) data structures. The function accepts an optional $description of the test.

    use v6;
     use Test;
     plan 1;

     sub count-chars(Str() $x) {
         my %chars;
         %chars{$_}++ for $x.comb;
         return %chars;
     }
     my %expected =
         f   => 1,
         l   => 1,
         e   => 3,
         c   => 1,
         ;
     is-deeply count-chars('fleece'), %expected, 'count-chars works on "fleece"';

Note that string comparison here would have been fragile, because hashes are not sorted, and converting a Hash to a string loses information.

## 37.4.5 By arbitrary comparison

- cmp-ok($value, $comparison, $expected, $description?)

Compares $value and $expected with the given $comparison comparator and passes the test if the comparison yields a True value. The $description of the test is optional.

The $comparison comparator can be either a Callable or a Str containing an infix operator, such as '==', a '~~', or a user-defined infix.

    cmp-ok 'my spelling is apperling', '~~', /perl/, "bad speller";

A Callable $comparison lets you use custom comparisons:

    sub my-comp { $^a / $^b  &lt; rand };
    cmp-ok 1, &amp;my-comp, 2, 'the dice giveth and the dice taketh away'

    cmp-ok 2, -> $a, $b { $a.is-prime and $b.is-prime and $a &lt; $b }, 7,
        'we got primes, one larger than the other!';

## 37.4.6 By object type

- isa-ok($value, $expected-type, $description?)

Marks a test as passed if the given object $value is, or inherits from, the given $expected-type. For convenience, types may also be specified as a string. The function accepts an optional $description of the test.

    class Womble {}
    class GreatUncleBulgaria is Womble {}
    my $womble = GreatUncleBulgaria.new;

    isa-ok $womble, Womble, "Great Uncle Bulgaria is a womble";
    isa-ok $womble, 'Womble';     # equivalent

## 37.4.7 By method name

- can-ok($variable, $method-name, $description?)

Marks a test as passed if the given $variable can run the given $method-name. The function accepts an optional $description. For instance:

    my $womble = Womble.new;

    # with automatically generated test description
    can-ok $womble, 'collect-rubbish';
    #  => An object of type 'Womble' can do the method 'collect-rubbish'

    # with human-generated test description
    can-ok $womble, 'collect-rubbish', "Wombles can collect rubbish";
    #  => Wombles can collect rubbish

## 37.4.8 By role

- does-ok($variable, $role, $description?)

Marks a test as passed if the given $variable can do the given $role. The function accepts an optional $description of the test.

    # create a Womble who can invent
    role Invent {
        method brainstorm { say "Aha!" }
    }
    class Womble {}
    class Tobermory is Womble does Invent {}

    # ... and later in the tests
    use Test;

    my $tobermory = Tobermory.new;

    # with automatically generated test description
    does-ok $tobermory, Invent;
    #  => The object does role Type

    does-ok $tobermory, Invent, "Tobermory can invent";
    #  => Tobermory can invent

## 37.4.9 By regex

- like($value, $expected-regex, $description?)

    like 'foo', /fo/, 'foo looks like fo';

Marks a test as passed if the $value, when coerced to a string, matches the $expected-regex. The function accepts an optional $description of the test.

- unlike($value, $expected-regex, $description?)

    unlike 'foo', /bar/, 'foo does not look like bar';

Marks a test as passed if the $value, when coerced to a string, does not match the $expected-regex. The function accepts an optional $description of the test.

# 37.5 Testing modules

- use-ok($module)

Marks a test as passed if the given $module is correctly loaded.

    use-ok 'Full::Qualified::ModuleName';

# 37.6 Testing exceptions

- dies-ok($code, $description?)

Marks a test as passed if the given $code throws an exception.

The function accepts an optional $description of the test.

    sub saruman(Bool :$ents-destroy-isengard) {
         die "Killed by Wormtongue" if $ents-destroy-isengard;
     }

     dies-ok { saruman(ents-destroy-isengard => True) }, "Saruman dies";

- lives-ok($code, $description?)

Marks a test as passed if the given $code does not throw an exception.

The function accepts an optional $description of the test.

    sub frodo(Bool :$destroys-ring) {
         die "Oops, that wasn't supposed to happen" unless $destroys-ring;
     }

     lives-ok { frodo(destroys-ring => True) }, "Frodo survives";

- eval-dies-ok($string, $description?)

Marks a test as passed if the given $string throws an exception when evaled as code.

The function accepts an optional $description of the test.

    eval-dies-ok q[my $joffrey = "nasty";
                    die "bye bye Ned" if $joffrey ~~ /nasty/],
         "Ned Stark dies";

- eval-lives-ok($string, $description?)

Marks a test as passed if the given $string does not throw an exception when evaled as code.

The function accepts an optional $description of the test.

    eval-lives-ok q[my $daenerys-burns = False;
                     die "Oops, Khaleesi now ashes" if $daenerys-burns],
         "Dany is blood of the dragon";

- throws-like($code, $expected-exception, $description?, *%matcher)

Marks a test as passed if the given $code throws the specific exception $expected-exception. The code $code may be specified as something Callable, or as a string to be EVALed. The exception may be specified as a type object, or as a string containing its type name.

If an exception was thrown, it will also try to match the matcher hash, in which the key is the name of the method to be called on the exception, and the value is the value it should have to pass. For example:

    sub frodo { fail "Oops. Frodo dies" unless $destroys-ring };
     throws-like { frodo }, Exception, message => /dies/;

Someone needs to clarify the preceding paragraph, because I have no idea what it is talking about... ;)

The function accepts an optional $description of the test.

Please note that you can only use the string form (for EVAL) if you are not referencing any symbols in the surrounding scope. If you are, you should encapsulate your string with a block and an EVAL instead. For instance:

    throws-like { EVAL q[ fac("foo") ] }, X::TypeCheck::Argument;

# 37.7 Grouping tests

The result of a group of subtests is only ok if all subtests are ok.

- subtest(&subtests, $description?)

The subtest function executes the given block, consisting of usually more than one test, possibly including a plan or done, and counts as one test in plan, todo, or skip counts. It will pass the test only if all tests in the block, pass. The function accepts an optional $description of the test.

    class Womble {}

     class GreatUncleBulgaria is Womble {
         has $.location = "Wimbledon Common";
         has $.spectacles = True;
     }

     subtest {
         my $womble = GreatUncleBulgaria.new;

         isa-ok $womble,            Womble,             "Correct type";
         is     $womble.location,   "Wimbledon Common", "Correct location";
         ok     $womble.spectacles,                     "Correct eyewear";

     }, "Check Great Uncle Bulgaria";

You can also place description as the first positional argument, or use a Pair with description as key and subtest's code as value. This can be useful for subtests with large bodies.

    subtest 'A bunch of tests', {
         plan 42;
         ...
         ...
     }

     subtest 'Another bunch of tests' => {
         plan 72;
         ...
         ...
     }

# 37.8 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.

- todo($reason, $count = 1)

Mark $count tests as TODO, giving a $reason as to why. By default only one test will be marked TODO.

    sub my-custom-pi { 3 };

    todo 'not yet precise enough';         # Mark the test as TODO.
    is my-custom-pi(), pi, 'my-custom-pi'; # Run the test, but don't report
                                           # failure in test harness.

The result from the test code above will be something like:

    not ok 1 - my-custom-pi# TODO not yet precise enough

    # Failed test 'my-custom-pi'
    # at test-todo.t line 7
    # expected: '3.14159265358979'
    #      got: '3'

- skip($reason, $count = 1)

Skip $count tests, giving a $reason as to why. By default only one test will be skipped. Use such functionality when a test (or tests) would die if run.

    if $*KERNEL ~~ 'linux' {
         is num-forward-slashes("/a/b"),             2;
         is num-forward-slashes(normalize("/a//b")), 2;
     }
     else {
         skip "Can't use forward slashes on Windows", 2;
     }

Note that if you mark a test as skipped, you must also prevent that test from running.

- skip-rest($reason?)

Skip the remaining tests. If the remainder of the tests in the test file would all fail due to some condition, use this function to skip them, providing an optional $reason as to why.

    unless $location ~~ "Wimbledon Common" {
         skip-rest "We can't womble, the remaining tests will fail";
         exit;
     }

     # tests requiring functional wombling
     ok womble();
     # ...

Note that skip-rest requires a plan to be set, otherwise the skip-rest call will throw an error. If no plan was set, you can use done to indicate the end of the test run (though of course the test summary will not count skipped tests). Note also the exit is required in the example to prevent the skipped tests from running. Alternatively, you could enclose the remaining tests in an else branch.

- bail-out($reason?)

If you already know the tests will fail, you can bail out of the test run using bail-out():

        $has-db-connection or bail-out 'Must have database connection for testing';

The function aborts the current test run, signaling failure to the harness. Takes an optional reason for bailing out. The subroutine will call exit(), so if you need to do a clean-up, do it before calling bail-out().

# 37.9 Manual control

If the convenience functionality documented above does not suit your needs, you can instead use the following functions to direct the test harness output manually.

- pass($description?), flunk($description?)

The pass function marks a test as passed. flunk marks a test as not passed. Both functions accept an optional test $description.

    pass "Actually, this test has passed";

    flunk "But this one hasn't passed";

Since these subroutines do not provide indication of what value was received and what was expected, they should be used sparingly, such as when evaluating a complex test condition.

- diag($message)

Display diagnostic information in a TAP-compatible manner on the standard error stream. It is usually used when a particular test has failed to provide information that the test itself did not provide. Or it can be used to provide visual markers on how the testing of a test-file is progressing (which can be important when doing stress testing).

    diag "Yay!  The tests got to here!";

# 38 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.

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.

# 38.1 Objects

## 38.1.1 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

    use v6;
    class Point {
        has $.x;
        has $.y;
        method double {
            $.x *= 2;   # WRONG
            $.y *= 2;   # WRONG
            self;
        }
    }

    say Point.new(x => 1, y => -2).double.x

dies with

    Cannot modify an immutable Int

in the first line 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 method double is

    method double {
        $!x *= 2;
        $!y *= 2;
        self;
    }

which operates on the attributes directly.

## 38.1.2 BUILD prevents automatic attribute initialization from constructor arguments

When you define your own BUILD submethod, you must take care of initializing all attributes yourself. For example

    use v6;
    class A {
        has $.x;
        has $.y;
        submethod BUILD {
            $!y = 18;
        }
    }

    say A.new(x => 42).x;       # Any

leaves $!x uninitialized, because the custom BUILD doesn't initialize it.

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;
    }

Another, more general approach is to leave BUILD alone, and hook into the BUILDALL mechanism instead:

    use v6;
    class A {
        has $.x;
        has $.y;
        method BUILDALL(|c) {
            callsame;
            $!y = 18;
            self
        }
    }

    say A.new(x => 42).x;       # 42

(Note that BUILDALL is a method, not a submethod. That's because by default, there is only one such method per class hierarchy, whereas BUILD is explicitly called per class. Which also explains why you need the nextsame inside BUILDALL, but not inside BUILD).

# 38.2 Regexes

## 38.2.1 Whitespace in Regexes does not match literally

    $ perl6 -e "say 'a b' ~~ /a b/"
    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

# 38.3 Captures

## 38.3.1 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:

    $ perl6 -e 'my $a = 2; say join ",", ($a, ++$a)'
    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 so it may already be incremented.

Instead, use an expression that produces a value when you want a value.

    $ perl6 -e 'my $a = 2; say join ",", (+$a, ++$a)'
    2,3

# 38.4 Arrays

## 38.4.1 Referencing the last element of an array

In Perl 5 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];    #->  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];   #->  eve

## 38.4.2 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);                    #-> 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.

# 38.5 Strings

## 38.5.1 Capitalizing a string

In Perl 5 one could capitalize a string by using the ucfirst function

    say ucfirst "alice"; #-> Alice

The ucfirst function does not exist in Perl 6; one needs to use the tc method:

    say "alice".tc;      #-> Alice

which is equivalent to

    say tc "alice";      #-> Alice

Here, tc means "title case".

## 38.5.2 Quotes and interpolation

Interpolation in string literals can be too clever for your good.

    "$foo&lt;html>&lt;/html>" # Perl 6 understands that as:
    $foo&lt;html> ~ '&lt;/html>'

    "$foo(" ~ @args ~ ")" # Perl 6 understands that as:
    $foo( ~ @args ~ ")"   # and will produce very confusing error messages

You can avoid those problems by surrounding all variables with {}, with or without using Q:c as your quoting construct.

    my $a = 1;
    say Q:c«{$a}()$b()»;
    OUTPUT«1()$b()␤»

## 38.5.3 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 sort, reverse and friends, you need to split the string into a list first.

    say "cba".sort;              #   cba (what is wrong)
    say "cba".comb.sort.join;    #   abc

# 38.6 Operators

Some operators commonly shared among other languages were repurposed in Perl 6 for other, more common, things:

## 38.6.1 Junctions

The ^, |, and & are not bitwise operators, they create Junctions. The corresponding bitwise operators in Perl 6 are: +^, +|, +& for integers and ?^, ?|, ?& for booleans.

## 38.6.2 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"
    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"'
    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"
    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")
    az, ba, bb, bc

# 38.7 Common Precedence Mistakes

## 38.7.1 Adverbs and Precedence

Adverbs do have a precedence that may not follow the order of operators that is displayed on your screen. If two operators of equal precedence are followed by an adverb it will pick the first operator it finds in the abstract syntax tree. Use parentheses to help Perl 6 understand what you mean or use operators with looser precedence.

    my %x = a => 42;
    say !%x&lt;b>:exists;            # dies with X::AdHoc
    say %x&lt;b>:!exists;            # this works
    say !(%x&lt;b>:exists);          # works too
    say not %x&lt;b>:exists;         # works as well
    say True unless %x&lt;b>:exists; # avoid negation altogether

## 38.7.2 Ranges and Precedence

The loose precedence of .. can lead to some errors. It is usually best to parenthesize ranges when you want to operate on the entire range.

    1..3.say    # says "3" (and warns about useless "..")
    (1..3).say  # says "1..3"

## 38.7.3 Loose boolean operators

The precedence of and, or, etc. is looser then routine calls. This can have surprising results for calls to routines that would be operators or statements in other languages like return, last and many others.

    sub f {
        return True and False;
        # this is actually
        # (return True) and False;
    }
    say f; # OUTPUT«True␤»

# 38.8 Subroutine and method calls

Subroutine and method calls can be made using one of two forms:

    foo(...); # function call form, where ... represent the required arguments
    foo ...;  # list op form, where ... represent the required arguments

The function call form can cause problems for the unwary when whitespace is added after the function or method name and before the opening parenthesis.

First we consider functions with zero or one parameter:

    sub foo() { say 'no arg' }
    sub bar($a) { say "one arg: $a" }

Then execute each with and without a space after the name:

    foo();    # okay: no arg
    foo ();   # FAIL: Too many positionals passed; expected 0 arguments but got 1
    bar($a);  # okay: one arg: 1
    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.

## 38.8.1 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&lt;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, it means "treat this hash as holding 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(|$arg, :$b); # okay: we passed the pair 'b' => 2 to the first argument
    foo(1, |$arg);   # FAIL: Too many positionals passed; expected 1 argument but got 2

    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.

# 39 Typesystem

Introduction to the type system of Perl 6

# 39.1 Definition of a Perl 6 Type

## 39.1.1 Type objects

To test if an object is a type object, test for definedness and check for identity between the object and it's .WHAT pseudo-method. Note that the method .defined can be overloaded and may provide false information.

    my $a = Int;
    say so $a // $a === $a.WHAT;
    # OUTPUT«True␤»

# 39.2 Type Declarators

TODO

## 39.2.1 class

TODO

### 39.2.1.1 Methods

#### 39.2.1.1.1 Reserved Method Names

Some built-in introspection methods are actually special syntax provided by the compiler, namely WHAT, WHO, HOW and VAR. Declaring methods with those names will silently fail. A dynamic call will work, what allows to call methods from foreign objects.

    class A {
        method WHAT { "ain't gonna happen" }
    };

    say A.new.WHAT; # OUTPUT«(A)␤»
    say A.new."WHAT"() # OUTPUT«ain't gonna happen␤»

#### 39.2.1.1.2 Setting Attributes with Namesake Variables and Methods

Instead of writing attr => $attr or :attr($attr), you can save some typing if the variable (or method call) you're setting the attribute with shares the name with the attribute:

    class A { has $.i = 42 };
    class B {
        has $.i = "answer";
        method m() { A.new(:$.i) }
    };
    my $a = B.new.m;
    say $a.i; # OUTPUT«answer␤»

Since $.i method call is named i and the attribute is named i, Perl 6 lets us shortcut. The same applies to :$var, :$!private-attribute, :&attr-with-code-in-it, and so on.

#### 39.2.1.1.3 trait is nodal

Mark a method for hyperoperators as to be avoided for decending into.

    dd [[1,2,3],[4,5]]>>.elems;
    # OUTPUT«(3, 2)␤»

### 39.2.1.2 trait handles

Defined as:

    multi sub trait_mod:&lt;handles>(Attribute:D $target, $thunk)

The trait handles applied to an attribute of a class will delegate all calls to the provided method name to the method with the same name of the attribute. The object referenced by the attribute must be initialized. A type constraint for the object that the call is delegated to can be provided.

    class A      { method m(){ 'A::m has been called.' } }
    class B is A { method m(){ 'B::m has been called.' } }
    class C {
        has A $.delegate handles 'm';
        method new($delegate){ self.bless(delegate => $delegate) }
    };
    say C.new(B.new).m(); # OUTPUT«B::m has been called.␤»

Instead of a method name a list of names, a Regex or a Whatever can be provided. In the latter case existing methods, both in the class itself and it's inheritance chain, will take precedence. If even local FALLBACKs should be searched use a HyperWhatever.

    class A {
        method m1(){}
        method m2(){}
    }

    class C {
        has $.delegate handles &lt;m1 m2> = A.new()
    }
    C.new.m2;

    class D {
        has $.delegate handles /m\d/ = A.new()
    }
    D.new.m1;

### 39.2.1.3 trait is

Defined as:

    multi sub trait_mod:&lt;is>(Mu:U $child, Mu:U $parent)

The trait is accepts a type object to be added as a parent class of a class in it's definition. To allow multiple inheritance the trait can be applied more then once. Adding parents to a class will import their methods into the target class. If the same method name occurs in multiple parents, the first added parent will win.

If no is trait is provided the default of Any will be used as a parent class. This forces all Perl 6 objects to have the same set of basic methods to provide an interface for introspection and coercion to basic types.

    class A {
        multi method from-a(){ 'A::from-a' }
    }
    dd A.new.^parents(:all);
    # OUTPUT«(Any, Mu)␤»

    class B {
        method from-b(){ 'B::from-b ' }
        multi method from-a(){ 'B::from-A' }
    }

    class C is A is B {}
    dd C.new.from-a();
    # OUTPUT«"A::from-a"␤»

### 39.2.1.4 trait is rw

Defined as:

    sub trait_mod:&lt;is>(Mu:U $type, :$rw!)

The trait is rw on a class will create writeable accessor methods on all public attributes of that class.

    class C is rw {
        has $.a;
    };
    my $c = C.new.a = 42;
    dd $c; # OUTPUT«Int $c = 42␤»

### 39.2.1.5 trait is required

TODO

### 39.2.1.6 trait does

TODO

### 39.2.1.7 trait hides

TODO

### 39.2.1.8 trait trusts

TODO

### 39.2.1.9 Versioning and Authership

Versioning and authership can be applied via adverbs :ver<> and :auth<>. Both take a string as argument, for C<:ver> the string is converted to a L<Version|/type/Version> object. To query a class version and auther use C<.^ver> and C<^.auth>. class C:ver<4.2.3>:auth<me@here.local> {} say [C.^ver, C.^auth]; # OUTPUT«[v4.2.3 me@here.local]␤

## 39.2.2 role

TODO

Versioning and authership can be applied via adverbs :ver<> and :auth<>. Both take a string as argument, for C<:ver> the string is converted to a L<Version|/type/Version> object. To query a roles version and auther use C<.^ver> and C<^.auth>. class R:ver<4.2.3>:auth<me@here.local> {} say [R.^ver, R.^auth]; # OUTPUT«[v4.2.3 me@here.local]␤

## 39.2.3 enum

Enumerations provide constant key-value-pairs with an associated type. Any key is of that type and injected as a symbol into the current scope. If the symbol is used, it is treated as a constant expression and the symbol is replaced with the value of the enum-pair. Any Enumeration inherits methods from the role Enumeration. Complex expressions for generating key-value-pairs are not supported.

Stringification of the symbol will provide the key of the enum-pair.

    enum Names ( name1 => 1, name2 => 2 );
    say name1, ' ', name2; # OUTPUT«name1 name2»
    say name1.value, ' ', name2.value; # OUTPUT«1 2␤»

Comparing symbols will use type information and the value of the enum-pair. As value types Numerical an Str are supported.

    sub same(Names $a, Names $b){
       $a eqv $b
    }

    say same(name1, name1); # OUTPUT«True␤»
    say same(name1, name2); # OUTPUT«False␤»
    my $a = name1;
    say $a ~~ Names; # OUTPUT«True␤»
    say $a.WHAT; # OUTPUT«Names␤»

All keys have to be of the same type.

    enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );
    dd Mass.enums; # OUTPUT«{:g(1.0), :kg(1000.0), :mg(0.001)}␤»

If no value is given Int will be assumed as the values type and incremented by one per key starting at zero.

    enum Numbers &lt;one two three four>;
    dd Numbers.enums; # OUTPUT«{:four(3), :one(0), :three(2), :two(1)}␤»

A different starting value can be provided.

    enum Numbers «:one(1) two three four»;
    dd Numbers.enums; # OUTPUT«{:four(4), :one(1), :three(3), :two(2)}␤»

Enums can be anonymous. They will be no type created, resulting in a lack of introspectiveness. The returned object is of type Map.

    my $e = enum &lt;one two three>;
    say two; # OUTPUT«two()(Map)␤»
    say one.WHAT; # OUTPUT«()␤»
    say $e.WHAT; # OUTPUT«(Map)␤»

### 39.2.3.1 Methods

#### 39.2.3.1.1 method enums

Defined as:

    method enums()

Returns the list of enum-pairs. Works both on the enum type and any key.

    enum Mass ( mg => 1/1000, g => 1/1, kg => 1000/1 );
    say Mass.enums, g.enums; # OUTPUT«{g => 1, kg => 1000, mg => 0.001}{g => 1, kg => 1000, mg => 0.001}␤»

#### 39.2.3.1.2 method key

Returns the key of an enum-pair.

    say g.key; # OUTPUT«g␤»

#### 39.2.3.1.3 method value

Returns the value of an enum-pair.

    say g.value; # OUTPUT«1␤»

#### 39.2.3.1.4 method pair

Defined as:

    method pair(::?CLASS:D:)

Returns a Pair of the enum-pair.

    say g.pair; # OUTPUT«g => 1␤»

#### 39.2.3.1.5 method kv

Defined as:

    multi method kv(::?CLASS:D:)

Returns a list with key and value of the enum-pair.

    say g.kv; # OUTPUT«(g 1)␤»

## 39.2.4 module

TODO

### 39.2.4.1 Versioning and Authorship

Versioning and authorship can be applied via adverbs :ver<> and :auth<>. Both take a string as argument, for C<:ver> the string is converted to a L<Version|/type/Version> object. To query a modules version and author use C<.^ver> and C<^.auth>. module M:ver<4.2.3>:auth<me@here.local> {} say [M.^ver, M.^auth]; # OUTPUT«[v4.2.3 me@here.local]␤

## 39.2.5 package

### 39.2.5.1 Versioning and Authorship

TODO

## 39.2.6 grammar

TODO

### 39.2.6.1 Versioning and Authorship

Versioning and authorship can be applied via adverbs :ver<> and :auth<>. Both take a string as argument, for :ver the string is converted to a Version object. To query a grammars version and author use .^ver and ^.auth.

    grammar G:ver&lt;4.2.3>:auth&lt;me@here.local> {}
    say [G.^ver, G.^auth];
    # OUTPUT«[v4.2.3 me@here.local]␤»

## 39.2.7 subset

A subset declares a new type that will re-dispatch to its base type. If a where clause is supplied any assignment will be checked against the given code object.

    subset Positive of Int where * > -1;
    my Positive $i = 1;
    $i = -42; # OUTPUT«Type check failed in assignment to $i; expected Positive but got Int (-42)␤ …»

# 40 Entering Unicode Characters

Input methods for unicode characters in editors and the shell

Perl 6 allows the use of unicode characters as variable names. Many operators are defined with unicode symbols (in particular the set/bag operators) as well as some quoting constructs. Hence it is good to know how to enter these symbols into editors, the Perl 6 shell and the command line, especially if the symbols aren't available as actual characters on a keyboard.

General information about entering unicode under various operating systems and environments can be found on the Wikipedia unicode input page.

# 40.1 XCompose

Xorg includes digraph support using a Compose key . The default of AltGr + Shift can be remapped to something easier such as Capslock. In GNOME 2 and MATE this can be setup under Preferences → Keyboard → Layouts → Options → Position of Compose Key. So, for example, to input »+« you could type CAPSLOCK > > + CAPSLOCK < <

XCompose allows customising the digraph sequences using a .XCompose file and https://github.com/kragen/xcompose/blob/master/dotXCompose is an extremely complete one. In GNOME, XCompose was overridden and replaced with a hardcoded list, but it is possible to restore XCompose by setting GTK_IM_MODULE=xim in your environment. It might be necessary to install a xim bridge as well, such as uim-xim.

# 40.2 Editors and shells

## 40.2.1 Vim

In Vim, unicode characters are entered (in insert-mode) by pressing first Ctrl-V (also denoted ^V), then u and then the hexadecimal value of the unicode character to be entered. For example, the Greek letter λ (lambda) is entered via the key combination:

    ^Vu03BB

You can also use Ctrl-K/^K along with a digraph to type in some characters. So an alternative to the above using digraphs looks like this:

    ^Kl*

The list of digraphs Vim provides is documented here; you can add your own with the :digraph command.

Further information about entering special characters in Vim can be found on the Vim Wikia page about entering special characters.

## 40.2.2 Emacs

In Emacs, unicode characters are entered by first entering the chord C-x 8 RET at which point the text Unicode (name or hex): appears in the minibuffer. One then enters the unicode code point hexadecimal number followed by the enter key. The unicode character will now appear in the document. Thus, to enter the Greek letter λ (lambda), one uses the following key combination:

    C-x 8 RET 3bb RET

Further information about unicode and its entry into Emacs can be found on the Unicode Encoding Emacs wiki page.

You can also use RFC 1345 character mnemonics by typing:

    C-x RET C-\ rfc1345 RET

Or C-u C-\ rfc1345 RET.

To type special characters, type & followed by a mnemonic. Emacs will show the possible characters in the echo area. For example, Greek letter λ (lambda) can be entered by typing:

    &amp;l*

You can use C-\ to toggle input method.

Another input method you can use to insert special characters is TeX. Select it by typing C-u C-\ TeX RET. You can enter a special character by using a prefix such as \. For example, to enter λ, type:

    \lambda

To view characters and sequences provided by an input method, run the describe-input-method command:

    C-h I TeX

## 40.2.3 Unix shell

At the bash shell, one enters unicode characters by using entering Ctrl-Shift-u, then the unicode code point value followed by enter. For instance, to enter the character for the element-of operator (∈) use the following key combination (whitespace has been added for clarity):

    Ctrl-Shift-u 2208 Enter

This also the method one would use to enter unicode characters into the perl6 REPL, if one has started the REPL inside a Unix shell.

# 40.3 Unicode characters useful in Perl 6

## 40.3.1 Guillemets

These characters are used in French and German as quotation marks. In Perl 6 they are also used as quotation marks (in POD as an alternative to the angle brackets and in normal code as an alternative to double quotes) as well as to denote the hyperoperators. The symbols and their unicode hex values are as follows:

symbol | unicode code point | ascii equivalent
--- | --- | ---
« | U+00AB | <<
» | U+00BB | >>

Thus constructs such as these are now possible:

    C« fixed-width POD text »
    say (1, 2) »+« (3, 4);     # 4 6 ; element-wise add
    @array »+=» 42;            # add 42 to each element of @array
    say «moo»;                 # moo
    my $baa = 123; say «$baa»; # 123

## 40.3.2 Set/bag operators

The set/bag operators operators all have set-theory-related symbols, the unicode code points and their ascii equivalents are listed below. To compose such a character, it is merely necessary to enter the character composition chord (e.g. Ctrl-V u in Vim; Ctrl-Shift-u in Bash) then the unicode code point hexadecimal number.

operator | unicode code point | ascii equivalent
--- | --- | ---
∈ | U+2208 | (elem)
∉ | U+2209 | !(elem)
∋ | U+220B | (cont)
∌ | U+220C | !(cont)
⊆ | U+2286 | (<=)
⊈ | U+2288 | !(<=)
⊂ | U+2282 | (<)
⊄ | U+2284 | !(<)
⊇ | U+2287 | (>=)
⊉ | U+2289 | !(>=)
⊃ | U+2283 | (>)
⊅ | U+2285 | !(>)
≼ | U+227C | (<+)
≽ | U+227D | (>+)
∪ | U+222A | (|)
∩ | U+2229 | (&)
∖ | U+2216 | (-)
⊖ | U+2296 | (^)
⊍ | U+228D | (.)
⊎ | U+228E | (+)

## 40.3.3 Mathematical symbols

Wikipedia contains a full list of mathematical operators and symbols in unicode as well as links to their mathematical meaning.

## 40.3.4 Greek characters

Greek characters may be used as variable names. For a list of Greek and Coptic characters and their unicode code points see the Greek in Unicode Wikipedia article.

For example, to assign the value 3 to π, enter the following in Vim (whitespace added to the compose sequences for clarity):

        my $ <b>Ctrl-V u 03C0</b>  = 3;  # same as: my $π = 3;
         say $ <b>Ctrl-V u 03C0</b> ;     # 3    same as: say $π;

## 40.3.5 Superscripts and subscripts

A limited set of superscripts and subscripts can be created directly in unicode by using the U+207x, U+208x and (less often) the U+209x ranges. However, to produce a value squared (to the power of 2) or cubed (to the power of 3), one needs to use U+00B2 and U+00B3 since these are defined in the Latin1 supplement Unicode block.

Thus, to write the Taylor series expansion around zero of the function exp(x) one would input into e.g. vim the following:

        exp(x) = 1 + x + x <b>Ctrl-V u 00B2</b> /2! + x <b>Ctrl-V u 00B3</b> /3!
         + ... + x <b>Ctrl-V u 207F</b> /n!
         # which would appear as
         exp(x) = 1 + x + x²/2! + x³/3! + ... + xⁿ/n!

Or to specify the elements in a list from 1 up to k:

        A <b>Ctrl-V u 2081</b> , A <b>Ctrl-V u 2082</b> , ..., A <b>Ctrl-V u 2096</b>
         # which would appear as
         A₁, A₂, ..., Aₖ

# 41 Unicode versus Texas symbols

Unicode symbols and their Texas (ASCII) counterparts

The following unicode symbols can be used in Perl 6 without needing to load any additional modules. Please note that the Since column applies to the version of Perl the symbol was known to be available. It is only mentioned if it is different from 6.c.

Reference is made below to various properties of unicode codepoints. The definitive list can be found here: http://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.

# 41.1 Alphabetic Characters

Any codepoint that has the Ll (Letter, lowercase), Lu (Letter, uppercase), Lt (Letter, titlecase), Lm (Letter, modifier), or the Lo (Letter, other) property can be used just like any other alphabetic character from the ASCII range.

# 41.2 Numeric characters

Any codepoint that has the Nd (Number, decimal digit) property, can be used as a digit in any number. For example:

      my $var = １９; # U+FF11 U+FF19
       say $var + 2;  # 21

# 41.3 Numeric values

Any codepoint that has the No (Number, other) property can be used standalone as a numeric value, such as ½ and ⅓. (These aren't decimal digit characters, so can't be combined.) For example:

      my $var = ⅒ + 2;
       say $var; # 2.1

# 41.4 Whitespace characters

Besides spaces and tabs you can use any other unicode whitespace character that has the Zs (Separator, space), Zl (Separator, line), or Zp (Separator, paragraph) property.

# 41.5 Other acceptable single codepoints

This list contains the single codepoints [and their Texas (ASCII) equivalents] that have a special meaning in Perl 6.

Symbol | Codepoint | Texas | Since | Remarks
--- | --- | --- | --- | ---
« | U+00AB | << | v6.c | as part of «» or .«
» | U+00BB | >> | v6.c | as part of «» or .»
× | U+00D7 | * | v6.c |
÷ | U+00F7 | / | v6.c |
− | U+2212 | - | v6.c |
∘ | U+2218 | o | v6.c |
≅ | U+2245 | =~= | v6.c |
π | U+03C0 | pi | v6.c | 3.14159_26535_89793_238e0
τ | U+03C4 | tau | v6.c | 6.28318_53071_79586_476e0
𝑒 | U+1D452 | e | v6.c | 2.71828_18284_59045_235e0
∞ | U+221E | Inf | v6.c |
… | U+2026 | ... | v6.c |
‘ | U+2018 | ' | v6.c | as part of ‘’ or ‚’ or ’‘
’ | U+2019 | ' | v6.c | as part of ’‘ or ’’
‚ | U+201A | ' | v6.c | as part of ‚‘ or ‚’
“ | U+201C | " | v6.c | as part of “” or „” or ”“
” | U+201D | " | v6.c | as part of ”“ or ””
„ | U+201E | " | v6.c | as part of „“ or „”
｢ | U+FF62 | Q// | v6.c | as part of ｢｣
｣ | U+FF63 | Q// | v6.c | as part of ｢｣
⁺ | U+207A | + | v6.c | (must use explicit number) as part of exponentiation
⁻ | U+207B | - | v6.c | (must use explicit number) as part of exponentiation
¯ | U+00AF | - | v6.c | (must use explicit number) as part of exponentiation (macron is an alternative way of writing a minus)
⁰ | U+2070 | **0 | v6.c | can be combined with ⁰..⁹
¹ | U+2071 | **1 | v6.c | can be combined with ⁰..⁹
² | U+2072 | **2 | v6.c | can be combined with ⁰..⁹
³ | U+2073 | **3 | v6.c | can be combined with ⁰..⁹
⁴ | U+2074 | **4 | v6.c | can be combined with ⁰..⁹
⁵ | U+2075 | **5 | v6.c | can be combined with ⁰..⁹
⁶ | U+2076 | **6 | v6.c | can be combined with ⁰..⁹
⁷ | U+2077 | **7 | v6.c | can be combined with ⁰..⁹
⁸ | U+2078 | **8 | v6.c | can be combined with ⁰..⁹
⁹ | U+2079 | **9 | v6.c | can be combined with ⁰..⁹
∘ | U+2218 | o | v6.c |
∅ | U+2205 | set() | v6.c | (empty set)
∈ | U+2208 | (elem) | v6.c |
∉ | U+2209 | !(elem) | v6.c |
∋ | U+220B | (cont) | v6.c |
∌ | U+220C | !(cont) | v6.c |
⊆ | U+2286 | (<=) | v6.c |
⊈ | U+2288 | !(<=) | v6.c |
⊂ | U+2282 | (<) | v6.c |
⊄ | U+2284 | !(<) | v6.c |
⊇ | U+2287 | (>=) | v6.c |
⊉ | U+2289 | !(>=) | v6.c |
⊃ | U+2283 | (>) | v6.c |
⊅ | U+2285 | !(>) | v6.c |
≼ | U+227C | (<+) | v6.c |
≽ | U+227D | (>+) | v6.c |
∪ | U+222A | (|) | v6.c |
∩ | U+2229 | (&) | v6.c |
∖ | U+2216 | (-) | v6.c |
⊖ | U+2296 | (^) | v6.c |
⊍ | U+228D | (.) | v6.c |
⊎ | U+228E | (+) | v6.c |

# 41.6 Multiple codepoints

This list contains multiple-codepoint operators that require special composition for their Texas (ASCII) equivalents. Note the codepoints are shown space-separated but should be entered as adjacent codepoints when used.

Symbol | Codepoints | Texas | Since | Remarks
--- | --- | --- | --- | ---
»=» | U+00BB = U+00BB | >>[=]>> | v6.c | uses ASCII '='

# 42 Variables

Variables in Perl 6

Variable names start with a special character called a sigil, followed optionally by a second special character named twigil and then an identifier.

# 42.1 Sigils <X|$ (sigil),@ (sigil),% (sigil),& (sigil)>

The sigil serves as a variable indicator and type constraint.

Sigil | Type constraint | Default type | Assignment | Examples
--- | --- | --- | --- | ---
$ | Mu (no type constraint) | Any | item | Int, Str, Array, Hash
@ | Positional | Array | list | List, Array, Range, Buf
% | Associative | Hash | list | Hash, Map, Pair
& | Callable | Callable | item | Sub, Method, Block, Routine

Examples:

    my $square = 9 ** 2;
    my @array  = 1, 2, 3;   # Array variable with three elements
    my %hash   = London => 'UK', Berlin => 'Germany';

The default type can be set with is.

    class FailHash is Hash {
        has Bool $!final = False;
        multi method AT-KEY ( ::?CLASS:D: Str:D \key ){
            fail X::OutOfRange.new(:what("Hash key"), :got(key), :range(self.keys)) if $!final &amp;&amp; !self.EXISTS-KEY(key);
            callsame
        }

        method finalize() {
            $!final = True
        }
    }

    my %h is FailHash = oranges => "round", bananas => "bendy";
    say %h&lt;oranges>;
    # OUTPUT «round␤»
    %h.finalize;
    say %h&lt;cherry>;
    # OUTPUT «Hash key out of range. Is: cherry, should be in (oranges bananas)␤  in method AT-KEY at failhash.p6 line 4 [...]»

Variables without sigils are also possible, see sigilless variables.

## 42.1.1 Item and List Assignment

There are two types of assignment, item assignment and list assignment. Both use the equal sign = as operator. The distinction whether an = means item or list assignment is based on the syntax of the left-hand side.

Item assignment places the value from the right-hand side into the variable (container) on the left.

List assignment leaves the choice of what to do to the variable on the left.

For example, Array variables (@ sigil) empty themselves on list assignment and then put all the values from the right-hand side into themselves.

The type of assignment (item or list) is decided by the first context seen in the current expression or declarator:

    my $foo = 5;            # item assignment
    say $foo.perl;          # 5

    my @bar = 7, 9;         # list assignment
    say @bar.WHAT;          # Array
    say @bar.perl;          # [7, 9]&lt;>

    (my $baz) = 11, 13;     # list assignment
    say $baz.WHAT;          # (List)
    say $baz.perl;          # (11, 13)

Thus, the behavior of an assignment contained within a list assignment depends on the expression or declarator that contains it.

For instance, if the internal assignment is a declarator, item assignment is used, which has tighter precedence than both the comma and the list assignment:

    my @array;
    @array = my $num = 42, "str";   # item assignment: uses declarator
    say @array.perl;                # [42, "str"]&lt;> (an Array)
    say $num.perl;                  # 42 (a Num)

Similarly, if the internal assignment is an expression that is being used as an initializer for a declarator, the context of the internal expression determines the type of assignment:

    my $num;
    my @array = $num = 42, "str";    # item assignment: uses expression
    say @array.perl;                 # [42, "str"]&lt;> (an Array)
    say $num.perl;                   # 42 (a Num)

    my ( @foo, $bar );
    @foo = ($bar) = 42, "str";       # list assignment: uses parens
    say @foo.perl;                   # [42, "str"]&lt;> (an Array)
    say $bar.perl;                   # $(42, "str")  (a List)

However, if the internal assignment is neither a declarator nor an expression, but is part of a larger expression, the context of the larger expression determines the type of assignment:

    my ( @array, $num );
    @array = $num = 42, "str";    # list assignment
    say @array.perl;              # [42, "str"]&lt;> (an Array)
    say $num.perl;                # [42, "str"]&lt;> (an Array)

This is because the whole expression is @array = $num = 42, "str", while $num = 42 is not is own separate expression.

See operators for more details on precedence.

## 42.1.2 Sigilless variables

It is possible to create "variables" in Perl 6 that do not have sigils:

    my \degrees = pi / 180;
    my \θ       = 15 * degrees;

Note, however, that these do not create containers. That means degrees and θ above actually directly represent Nums. To illustrate, try assigning to one after you've defined it:

    θ = 3; # Dies with the error "Cannot modify an immutable Num"

Sigilless variables do not enforce context, so they can be used to pass something on as-is:

    sub logged(&amp;f, |args) {
        say('Calling ' ~ &amp;f.name ~ ' with arguments ' ~ args.perl);
        my \result = f(|args);
        #  ^^^^^^^ not enforcing any context here
        say(&amp;f.name ~ ' returned ' ~ result.perl);
        return |result;
    }

# 42.2 Twigils

Twigils influence the scoping of a variable. Please be aware that twigils have no influence over whether the primary sigil interpolates. That is, if $a interpolates, so do $^a, $*a, $=a, $?a, $.a, etc. It only depends on the $.

Twigil | Scope
--- | ---
none | Based only on declarator
* | Dynamic
! | Attribute (class member)
? | Compile-time variable
. | Method (not really a variable)
< | Index into match object (not really a variable)
^ | Self-declared formal positional parameter
: | Self-declared formal named parameter
= | Pod variables
~ | The sublanguage seen by the parser at this lexical spot

## 42.2.1 The * Twigil

Dynamic variables are looked up through the caller, not through the outer scope. For example:

    my $lexical   = 1;
     my $*dynamic1 = 10;
     my $*dynamic2 = 100;

     sub say-all() {
         say "$lexical, $*dynamic1, $*dynamic2";
     }

     # prints 1, 10, 100
     say-all();

     {
         my $lexical   = 2;
         my $*dynamic1 = 11;
         $*dynamic2    = 101;

         # prints 1, 11, 101
         say-all();
     }

     # prints 1, 10, 101
     say-all();

The first time &say-all is called, it prints "1, 10, 100" just as one would expect. The second time though, it prints "1, 11, 101". This is because $lexical isn't looked up in the caller's scope but in the scope &say-all was defined in. The two dynamic variables are looked up in the caller's scope and therefore have the values 11 and 101. The third time &say-all is called $*dynamic1 isn't 11 anymore, but $*dynamic2 is still 101. This stems from the fact that we declared a new dynamic variable $*dynamic1 in the block and did not assign to the old variable as we did with $*dynamic2.

The dynamic variables differ from other variable types in that referring to an undeclared dynamic variable is not a compile time error but a runtime failure, so a dynamic variable can be used undeclared as long as it is checked for definedness or used in a boolean context before using it for anything else:

    sub foo() {
         $*FOO // 'foo';
     }

     say foo; # -> 'foo'

     my $*FOO = 'bar';

     say foo; # -> 'bar'

## 42.2.2 The ! Twigil

Attributes are variables that exist per instance of a class. They may be directly accessed from within the class via !:

    class Point {
         has $.x;
         has $.y;

         method Str() {
             "($!x, $!y)"
         }
     }

Note how the attributes are declared as $.x and $.y but are still accessed via $!x and $!y. This is because in Perl 6 all attributes are private and can be directly accessed within the class by using $!attribute-name. Perl 6 may automatically generate accessor methods for you though. For more details on objects, classes and their attributes see object orientation.

## 42.2.3 The ? Twigil

Compile-time variables may be addressed via the ? twigil. They are known to the compiler and may not be modified after being compiled in. A popular example for this is:

    say "$?FILE: $?LINE"; # prints "hello.pl: 23" if this is the 23 line of a
                          # file named "hello.pl".

Although they may not be changed at runtime, the user is allowed to (re)define such variables.

    constant $?TABSTOP = 4; # this causes leading tabs in a heredoc or in a POD
                            # block's virtual margin to be counted as 4 spaces.

For a list of these special variables see compile-time variables.

## 42.2.4 The . Twigil

The . twigil isn't really for variables at all. In fact, something along the lines of

    class Point {
         has $.x;
         has $.y;

         method Str() {
             "($.x, $.y)" # note that we use the . instead of ! this time
         }
     }

just calls the methods x and y on self, which are automatically generated for you because you used the . twigil when the attributes were declared. Note, however, that subclasses may override those methods. If you don't want this to happen, use $!x and $!y instead.

The fact that the . twigil just does a method call also implies that the following is possible too:

    class SaySomething {
         method a() { say "a"; }
         method b() { $.a; }
     }

     SaySomething.b; # prints "a"

For more details on objects, classes and their attributes and methods see object orientation.

## 42.2.5 The < Twigil

The < twigil is just an alias for $/<...> where $/ is the match variable. For more information about the match variable see $/ and type Match.

## 42.2.6 The ^ Twigil

The ^ twigil declares a formal positional parameter to blocks or subroutines. Variables of the form $^variable are a type of placeholder variable. They may be used in bare blocks to declare formal parameters to that block. So the block in the code

        for ^4 {
             say " <b>$^b</b>  follows  <b>$^a</b> ";
         }

which prints

    1 follows 0
    3 follows 2

has two formal parameters, namely $a and $b. Note that even though $^b appears before $^a in the code, $^a is still the first formal parameter to that block. This is because the placeholder variables are sorted in Unicode order. If you have self-declared a parameter using $^a once, you may refer to it using only $a thereafter.

Although it is possible to use nearly any valid identifier as a placeholder variable, it's recommended to use short names or ones that can be trivially understood in the correct order, to avoid surprise on behalf of the reader.

Subroutines may also make use of placeholder variables but only if they do not have an explicit parameter list. This is true for normal blocks too.

    sub say-it    { say $^a; } # valid
    sub say-it()  { say $^a; } # invalid
                  { say $^a; } # valid
    -> $x, $y, $x { say $^a; } # invalid

Placeholder variables syntactically cannot have any type constraints. Be also aware that one cannot have placeholder variables with a single upper-case letter. This is disallowed in favor of being to able to catch some Perl 5-isms.

## 42.2.7 The : Twigil

The : twigil declares a formal named parameter to a block or subroutine. Variables declared using this form are a type of placeholder variable too. Therefore the same things that apply to variables declared using the ^ twigil also apply here (with the exception that they are not positional and therefore not ordered using Unicode order, of course). So this:

        say {  <b>$:add</b>  ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add

Will print "-1".

See ^ for more details about placeholder variables.

## 42.2.8 The = Twigil

The = twigil is used to access Pod variables. Every Pod block in the current file can be accessed via a Pod object, such as $=data, $=SYNOPSIS or =UserBlock. That is: a variable with the same name of the desired block and a = twigil.

    =begin Foo
     ...
     =end Foo

     #after that, $=Foo gives you all Foo-Pod-blocks

You may access the Pod tree which contains all Pod structures as a hierarchical data structure through $=pod.

Note that all those $=someBlockName support the Positional and the Associative roles.

## 42.2.9 The ~ Twigil

Note: Slangs are NYI in Rakudo.

The ~ twigil is for referring to sublanguages (called slangs). The following are useful:

    $~MAIN       the current main language (e.g. Perl statements)
    $~Quote      the current root of quoting language
    $~Quasi      the current root of quasiquoting language
    $~Regex      the current root of regex language
    $~Trans      the current root of transliteration language
    $~P5Regex    the current root of the Perl 5 regex language

You may supersede or augment these languages in your current lexical scope by using

    augment slang Regex {  # derive from $~Regex and then modify $~Regex
        token backslash:std&lt;\Y> { YY };
    }

or

    supersede slang Regex { # completely substitute $~Regex
        ...
    }

# 42.3 Variable Declarators and Scope

Most of the time it's enough to create a new variable using the my keyword:

         <b>my</b>  $amazing-variable = "World";
         say "Hello $amazing-variable!"; # Hello World!

However, there are many declarators that change the details of scoping beyond what #Twigils can do.

Declarator | Effect
--- | ---
my | Introduces lexically scoped names
our | Introduces package-scoped names
has | Introduces attribute names
anon | Introduces names that are private to the construct
state | Introduces lexically scoped but persistent names
augment | Adds definitions to an existing name
supersede | Replaces definitions of an existing name

There are also two prefixes that resemble declarators but act on predefined variables:

Prefix | Effect
--- | ---
temp | Restores a variable's value at the end of scope
let | Restores a variable's value at the end of scope if the block exits unsuccessfully

## 42.3.1 The my Declarator

Declaring a variable with my gives it lexical scope. This means it only exists within the current block. For example:

    {
        my $foo = "bar";
        say $foo; # -> "bar"
    }
    say $foo; # !!! "Variable '$foo' is not declared"

This dies because $foo is only defined as long as we are in the same scope.

Additionally, lexical scoping means that variables can be temporarily redefined in a new scope:

    my $location = "outside";

     sub outer-location {
         # Not redefined:
         say $location;
     }

     outer-location; # -> "outside"

     sub in-building {
         my $location = "inside";
         say $location;
     }

     in-building; # -> "inside"

     outer-location; # -> "outside"

If a variable has been redefined, any code that referenced the outer variable will continue to reference the outer variable. So here, &outer-location still prints the outer $location:

    sub new-location {
         my $location = "nowhere"
         outer-location;
     }

     new-location; # -> "outside"

To make new-location() print nowhere, make $location a dynamic variable using the * twigil.

my is the default scope for subroutines, so my sub x() {} and sub x() {} do exactly the same thing.

## 42.3.2 The our Declarator

our variables work just like my variables, except that they also introduce an alias into the symbol table.

    module M {
        our $Var;
        # $Var available here
    }

    # Available as $M::Var here.

## 42.3.3 The has Declarator

has scopes attributes to instances of a class or role, and methods to classes or roles. has is implied for methods, so has method x() {} and method x() {} do the same thing.

See object orientation for more documentation and some examples.

## 42.3.4 The anon Declarator

The anon declarator prevents a symbol from getting installed in the lexical scope, the method table and everywhere else.

For example you can use it to declare subroutines which know their own name, but still aren't installed in a scope:

    my %operations =
        half   => anon sub half($x) { $x / 2 },
        square => anon sub square($x) { $x * $x },
        ;
    say %operations&lt;square>.name;       # square
    say %operations&lt;square>(8);         # 64

## 42.3.5 The state Declarator

state declares lexically scoped variables, just like my. However, initialization happens exactly once the first time the initialization is encountered in the normal flow of execution. Thus, state variables will retain their value across multiple executions of the enclosing block or routine.

Therefore, the subroutine

    sub a {
         state @x;
         state $l = 'A';
         @x.push($l++);
     };

     say a for 1..6;

     This works per "clone" of the containing code object, so:

         ({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # says 1 then 2 thrice

     Note that this is B&lt;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.

will continue to increment $l and append it to @x each time it is called. So it will output

    [A]
     [A B]
     [A B C]
     [A B C D]
     [A B C D E]
     [A B C D E F]

As with my, declaring multiple state variables must be placed in parentheses and for declaring a single variable, parentheses may be omitted.

Please note that many operators come with implicit binding, what will lead to actions at a distance. Use .clone or coercion to create a new container that can be bound to.

    my @a;
    sub f() {
        state $i;
        $i++;
        @a.push: "k$i" => $i # &lt;-- .clone goes here
    };
    f for 1..3;
    dd @a; # «Array $var = $[:k1(3), :k2(3), :k3(3)]»

All state variables are shared between threads. The result can be undesired or dangerous.

    sub code(){ state $i = 0; say ++$i; $i };
    await
        start { loop { last if code() >= 5 } },
        start { loop { last if code() >= 5 } };

    # OUTPUT«1␤2␤3␤4␤4␤3␤5␤»
    # OUTPUT«2␤1␤3␤4␤5␤»
    # many other more or less odd variations can be produced

### 42.3.5.1 The $ Variable

As well as explicitly declared named state variables $ can be used as an anonymous state variable without an explicit state declaration:

    perl6 -e 'sub foo() { say ++$  }; foo() for ^3'

produces:

    1
     2
     3

Furthermore, state variables are not required to exist in subroutines. You could, for example, use $ in a one-liner to number the lines in a file:

    perl6 -ne 'say ++$ ~ " $_"' example.txt

Each reference to $ within a lexical scope in effect is a separate variable, as illustrated by:

    perl6 -e '{ say ++$; say $++  } for ^5'

which produces:

    1
     0
     2
     1
     3
     2
     4
     3
     5
     4

If you need to refer to the value of $ more than once within the scope it should be copied to a new variable, for example:

    sub foo() {
         given ++$ {
             when 1 {
                 say "one";
             }
             when 2 {
                 say "two";
             }
             when 3 {
                 say "three";
             }
             default {
                 say "many";
             }
         }
     }

     foo() for ^3;

produces:

    one
     two
     three

### 42.3.5.2 The @ Variable

In a similar manner to the $ variable there is also a Positional anonymous state variable @ :

    sub foo($x) {
         say (@).push($x);
     }

     foo($_) for ^3;

Produces:

    [0]
     [0 1]
     [0 1 2]

The @ here is parenthesized in order to disambiguate the expression from a class member variable named @.push. Indexed access doesn't require this disambiguation but you will need to copy the value in order to do anything useful with it:

    sub foo($x) {
         my $v = @;
         $v[$x] = $x;
         say $v;
     }

     foo($_) for ^3;

Produces:

    [0]
     [0 1]
     [0 1 2]

As with $ each mention of @ in a scope introduces a new anonymous array.

### 42.3.5.3 The % Variable

Finally there is also an Associative anonymous state variable %:

    sub foo($x) {
         say (%).push($x => $x);
     }

     foo($_) for ^3;

Which produces:

    0 => 0
     0 => 0, 1 => 1
     0 => 0, 1 => 1, 2 => 2

The same caveat about disambiguation applies. As you may expect, indexed access is also possible (with copying to make it useful):

    sub foo($x) {
         my $v = %;
         $v{$x} = $x;
         say $v;
     }

     foo($_) for ^3;

Which produces:

    0 => 0
     0 => 0, 1 => 1
     0 => 0, 1 => 1, 2 => 2

As with the other anonymous state variables each mention of % within a given scope will effectively introduce a separate variable.

## 42.3.6 The augment Declarator

With augment, you can add attributes and methods to existing classes and grammars, provided you activated the MONKEY-TYPING pragma first.

Since classes are usually our scoped, and thus global, this means modifying global state, which is strongly discouraged. For almost all situations, there are better solutions.

    # don't do this
    use MONKEY-TYPING;
    augment class Int {
        method is-answer { self == 42 }
    }
    say 42.is-answer;       # True

(In this case, the better solution would be to use a function).

## 42.3.7 The temp Prefix

Like my, temp restores the old value of a variable at the end of its scope. However, temp does not create a new variable.

    my $in = 0; # temp will "entangle" the global variable with the call stack
                # that keeps the calls at the bottom in order.
    sub f(*@c) {
        (temp $in)++;
         "&lt;f>\n"
         ~ @c>>.indent($in).join("\n")
         ~ (+@c ?? "\n" !! "")
         ~ '&lt;/f>'
    };
    sub g(*@c) {
        (temp $in)++;
        "&lt;g>\n"
        ~ @c>>.indent($in).join("\n")
        ~ (+@c ?? "\n" !! "")
        ~ "&lt;/g>"
    };
    print g(g(f(g()), g(), f()));

output:

    &lt;g>
     &lt;g>
      &lt;f>
       &lt;g>
       &lt;/g>
      &lt;/f>
      &lt;g>
      &lt;/g>
      &lt;f>
      &lt;/f>
     &lt;/g>
    &lt;/g>

## 42.3.8 The let Prefix

Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.

    my $answer = 42;

    {
        let $answer = 84;
        die if not Bool.pick;
        CATCH {
            default { say "it's been reset :(" }
        }
        say "we made it 84 sticks!";
    }

    say $answer;

In the above case, if the Bool.pick returns true, the answer will stay as 84 because the block returns a defined value (say returns true). Otherwise the die statement will cause the block to exit unsuccessfully, resetting the answer to 42.

this is duplicated in operators.pod

# 42.4 Type Constraints and Initialization

Variables can have a type constraint, which goes between the declarator and the variable name:

        my Int $x = 42;
         $x = 'a string';    # throws an  <a href="#_type_X::TypeCheck::Assignment.pod6">X::TypeCheck::Assignment</a>  error

If a scalar variable has a type constraint but no initial value, it is initialized with the type object of the constraint type.

    my Int $x;
    say $x.^name;       # Int
    say $x.defined;     # False

Scalar variables without an explicit type constraint are typed as Mu but default to the Any type object.

Variables with the @ sigil are initialized with an empty Array; variables with the % sigil are initialized with an empty Hash.

The default value of a variable can be set with the is default trait, and re-applied by assigning Nil to it:

    my Real $product is default(1);
    say $product;                       # 1
    $produce *= 5;
    say $product;                       # 5
    $product = Nil;
    say $product;                       # 1

## 42.4.1 Default Defined Variables Pragma

To force all variables to have a definedness contraint use the prama use variables :D. The pragma is lexically scoped and can be switched of with use variables :_.

    use variables :D;
    my Int $i;
    # OUTPUT«===SORRY!=== Error while compiling &lt;tmp>␤Variable definition of type Int:D (implicit :D by pragma) requires an initializer ...
    my Int $i = 1; # that works
    { use variables :_; my Int $i; } # switch it of in this block

# 42.5 Special Variables

Perl 5 is infamous for its many obscure special variables. Perl 6 also has special variables but only has three that are extra short due to how often they're used. Other special variables have longer, more descriptive names.

## 42.5.1 Pre-defined lexical variables

There are three special variables that are available in every block:

Variable | Meaning
--- | ---
$_ | topic variable
$/ | regex match
$! | exceptions

### 42.5.1.1 The $_ Variable

$_ is the topic variable. It is the default parameter for blocks that do not have an explicit signature, so constructs like for @array { ... } and given $var { ... } bind to $_ simply by invoking the block.

    for &lt;a b c> { say $_ }  # sets $_ to 'a', 'b' and 'c' in turn
    say $_ for &lt;a b c>;     # same, even though it's not a block
    given 'a'   { say $_ }  # sets $_ to 'a'
    say $_ given 'a';       # same, even though it's not a block

CATCH blocks set $_ to the exception that was caught. The ~~ smart-match operator sets $_ on the right-hand side expression to the value of the left-hand side.

Calling a method on $_ can be shortened by leaving off the variable name:

    .say;                   # same as $_.say

m/regex/ and /regex/ regex matches and s/regex/subst/ substitutions work on $_:

    say "Looking for strings with non-alphabetic characters...";
    for &lt;ab:c d$e fgh ij*> {
        .say if m/&lt;!alpha>/;
    }

This outputs:

    Looking for strings with non-alphabetic characters...
    ab:c
    d$e
    ij*

### 42.5.1.2 The $/ Variable

$/ is the match variable. It stores the result of the last Regex match and so usually contains objects of type Match.

    'abc 12' ~~ /\w+/;  # sets $/ to a Match object
    say $/.Str;         # abc

The Grammar.parse method also sets the caller's $/ to the resulting Match object. For the following code:

    use XML::Grammar; # panda install XML
    XML.Grammar.parse("&lt;p>some text&lt;/p>");
    say $/;

the output is:

｢<p>some text</p>｣ root => ｢<p>some text</p>｣ name => ｢p｣ child => ｢some text｣ text => ｢some text｣ textnode => ｢some text｣ element => ｢<p>some text</p>｣ name => ｢p｣ child => ｢some text｣ text => ｢some text｣ textnode => ｢some text｣

#### 42.5.1.2.1 Positional Attributes

$/ can have positional attributes if the Regex had capture-groups in it, which are just formed with parentheses.

    'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;
    say $/[0]; # ｢bbbbb｣
    say $/[1]; # ｢dddddeff｣

These can also be accessed by the shortcuts $0, $1, $2, etc.

    say $0; # ｢bbbbb｣
    say $1; # ｢dddddeff｣

To get all of the positional attributes, any of $/.list, @$/, or @() can be used.

    say @().join; # bbbbbdddddeff

#### 42.5.1.2.2 Named Attributes

$/ can have named attributes if the Regex had named capture-groups in it, or if the Regex called out to another Regex.

    'I.... see?' ~~ / \w+ $&lt;punctuation>=[ &lt;-[\w\s]>+ ] \s* $&lt;final-word> = [ \w+ . ] /;
    say $/&lt;punctuation>; # ｢....｣
    say $/&lt;final-word>;  # ｢see?｣

These can also be accessed by the shortcut $<named>.

    say $&lt;punctuation>; # ｢....｣
    say $&lt;final-word>;  # ｢see?｣

To get all of the named attributes, any of $/.hash, %$/, or %() can be used.

    say %().join;       # "punctuation     ....final-word  see?"

### 42.5.1.3 The $! Variable

$! is the error variable. If a try block or statement prefix catches an exception, that exception is stored in $!. If no exception was caught, $! is set to the Any type object.

Note that CATCH blocks do not set $!. Rather they set $_ inside the block to the caught exception.

## 42.5.2 Compile-time variables

$?FILE | Which file am I in?
$?LINE | Which line am I at?
::?CLASS | Which class am I in?
&?ROUTINE | Which routine am I in?
&?BLOCK | Which block am I in?
%?LANG | What is the current set of interwoven languages?
%?RESOURCES | The files associated with the "Distribution" of the current compilation unit.

    for '.' {
        .Str.say when !.IO.d;
        .IO.dir()>>.&amp;?BLOCK when .IO.d # lets recurse a little!
    }

Other compile-time variables:

$?SCOPE | Which lexical scope am I in?
$?PACKAGE | Which package am I in?
$?MODULE | Which module am I in?
$?CLASS | Which class am I in? (as variable)
$?ROLE | Which role am I in? (as variable)
$?GRAMMAR | Which grammar am I in?
$?TABSTOP | How many spaces is a tab in a heredoc or virtual margin?
$?USAGE | The usage message generated from the signatures of MAIN subs.
$?ENC | Default encoding of Str.encode/Buf.decode/various IO methods.

## 42.5.3 Dynamic variables

There should be a better way get this table to be formatted properly, but if there is, Rakudo doesn't support it at the moment.

$*ARGFILES | Magic command-line input handle.
@*ARGS | Arguments from the command line.
$*IN | Standard input filehandle, AKA stdin
$*OUT | Standard output filehandle, AKA stdout
$*ERR | Standard error filehandle, AKA stderr
%*ENV | Environment variables
$*REPO | A variable holding information about modules installed/loaded
$*TZ | The system's local timezone.
$*CWD | The Current Working Directory.
$*KERNEL | Which kernel am I running under?
$*DISTRO | Which OS distribution am I running under?
$*VM | Which virtual machine am I running under?
$*PERL | Which Perl am I running under?
$*PID | Process ID of the current process.
$*PROGRAM-NAME | Path to the current executable as it was entered on the | command line, or C<-e> if perl was invoked with the -e flag.
$*PROGRAM | Location (in the form of an C<IO::Path> object) of the | Perl program being executed.
$*EXECUTABLE | Absolute path of the perl executable that is currently running.
$*EXECUTABLE-NAME | The name of the perl executable that is currently running. | (e.g. perl6-p, perl6-m, Niecza.exe) | Favor $*EXECUTABLE because it is not guaranteed that the perl | executable is in PATH.
$*USER | The user that is running the program. It is an object | that evaluates to "username (uid)". It will evaluate | to the username only if treated as a string and the | numeric user id if treated as a number.
$*GROUP | The primary group of the user who is running the program. | It is an object that evaluates to "groupname (gid)". | It will evaluate to the groupname only if treated as a | string and the numeric group id if treated as a number.
$*HOME | An L<IO::Path> object representing the "home directory" | of the user that is running the program. If the | "home directory" cannot be determined it will be L<Nil>
$*SPEC | The appropriate L<IO::Spec> sub-class for the platform that | the program is running on. For OS-specific code, simply use smartmatch: | C<say "We are on Windows!" if $*SPEC ~~ IO::Spec::Win32>
$*TMPDIR | An L<IO::Path> object representing the "system temporary directory"
$*THREAD | A L<Thread> object representing the currently executing thread.
$*SCHEDULER | A L<ThreadPoolScheduler> object representing the current default | scheduler. | | Note on usage: For the current Rakudo, by default this imposes a | maximum of 16 threads on the methods C<.hyper> and C<.race>. To change | the maximum number of threads, either set the environment variable | RAKUDO_MAX_THREADS before running perl6 or create a scoped copy | with the default changed before using C<.hyper> or C<.race>: | | my $*SCHEDULER = ThreadPoolScheduler.new( max_threads => 64 ); | | This behavior is not tested in the spec tests and is subject to change.

# 43 Perl 6

perl6 - the Rakudo Perl 6 Compiler

# 43.1 SYNOPSIS

    perl6 [switches] [--] [programfile] [arguments]

# 43.2 DESCRIPTION

With no arguments, enters a REPL. With a [programfile] or the -e option, compiles the given program and by default also executes the compiled code.

      Option               Purpose
       ======               ==============================================
       -c                   check syntax only (runs BEGIN and CHECK blocks)
       --doc                extract documentation and print it as text
       -e program           one line of program, strict is enabled by default
       -h, --help           display this help text
       -n                   run program once for each line of input
       -p                   same as -n, but also print $_ at the end of lines
       -I path              adds the path to the module search path
       -M module            loads the module prior to running the program
       --target=[stage]     specify compilation stage to emit
       --optimize=[level]   use the given level of optimization (0..3)
       --encoding=[mode]    specify string encoding mode
       -o, --output=[name]  specify name of output file
       -v, --version        display version information
       --stagestats         display time spent in the compilation stages
       --ll-exception       display a low level backtrace on errors
       --profile            write profile information as HTML file (MoarVM)
       --profile-filename   provide a different filename (also allows .json)
       --doc=[module]       Use Pod::To::[module] to render inline documentation.

     Note that only boolean single-letter options may be bundled.

The supported values for --target are:

Target | Backend | Description
--- | --- | ---
parse | all | a representation of the parse tree
ast | all | an abstract syntax tree (before optimizations)
optimize | all | an abstract syntax tree (after optimizations)
mbc | MoarVM | MoarVM byte code
jar | JVM | JVM archive

For --profile-filename, specifying a name ending in .json will write a raw JSON profile dump. The default if this is omitted is profile-I<[timestamp]>.html.

# 43.3 ENVIRONMENT VARIABLES

Rakudo's behavior can be tweaked by a (growing) number of environment variables; this section attempts to document all those currently in use.

## 43.3.1 Module Loading

- RAKUDOLIB, PERL6LIB (Str; src/core/Inc.pm)

    Appends a comma-delimited list of paths to C&lt;@INC>. C&lt;RAKUDOLIB> is evaluated first.

RAKUDO_MODULE_DEBUG (Bool; src/Perl6/ModuleLoader.pm) Causes the module loader to print debugging information to standard error.

## 43.3.2 Error Message Verbosity and Strictness

RAKUDO_NO_DEPRECATIONS (Bool; src/core/Deprecations.pm) If true, suppresses deprecation warnings triggered by the is DEPRECATED trait.

RAKUDO_DEPRECATIONS_FATAL (Bool; src/core/Deprecations.pm) If true, deprecation warnings become thrown exceptions.

RAKUDO_VERBOSE_STACKFRAME (UInt; src/core/Backtrace.pm) Displays source code in stack frames surrounded by the specified number of lines of context.

RAKUDO_BACKTRACE_SETTING (Bool; src/core/Backtrace.pm) Controls whether .setting files are included in backtraces.

## 43.3.3 Affecting Precompilation

RAKUDO_PREFIX (Str; src/core/CompUnit/RepositoryRegistry.pm) When this is set, Rakudo will look for the standard repositories (perl, vendor, site) in the specified directory. This is intended as an escape hatch for build-time bootstrapping issues, where Rakudo may be built as an unprivileged user without write access to the runtime paths in NQP's config.

RAKUDO_PRECOMP_DIST (src/core/CompUnit/PrecompilationRepository.pm)

RAKUDO_PRECOMP_LOADING (src/core/CompUnit/PrecompilationRepository.pm)

RAKUDO_PRECOMP_WITH (src/core/CompUnit/PrecompilationRepository.pm) These are internal variables for passing serialized state to precompilation jobs in child processes. Please do not set them manually.

## 43.3.4 Other

RAKUDO_ERROR_COLOR (Bool; src/core/Exception.pm) Controls whether to emit ANSI codes for error highlighting. Defaults to true if unset, except on Win32.

RAKUDO_MAX_THREADS (UInt; src/core/ThreadPoolScheduler.pm) Override the default maximum number of threads used by a thread pool.

RAKUDO_JDB_PORT (Str; src/core/CompUnit/PrecompilationRepository.pm) In perl6-jdb-server for setting the jdb port

RAKUDO_PRECOMP_NESTED_JDB and RAKUDO_JDB_PORT (Str; src/core/CompUnit/PrecompilationRepository.pm) RAKUDO_PRECOMP_NESTED_JDB uses perl6-jdb-server with increasing ports for precompilation and RAKUDO_JDB_PORT in perl6-jdb-server is for setting the jdb port.

TMPDIR, TEMP, TMP (Str; src/core/IO/Spec/) The IO::Spec::Unix.tmpdir method will return $TMPDIR if it points to a directory with full access permissions for the current user, with a fallback default of '/tmp'.

IO::Spec::Cygwin and IO::Spec::Win32 use more Win32-appropriate lists which also include the %TEMP% and %TMP% environment variables.

PATH, Path (Str; src/core/IO/Spec/) The IO::Spec::Unix.path method splits $PATH as a shell would; i.e. as a colon-separated list. IO::Spec::Cygwin inherits this from IO::Spec::Unix.

IO::Spec::Win32.path will read the first defined of either %PATH% or %Path% as a semicolon-delimited list.

# 44 Debugging

Debug Perl 6 programs

There are at least two useful debuggers available for Rakudo:

- Debugger::UI::CommandLine

    A command-line debugger frontend for Rakudo.

- Grammar::Debugger (and Grammar::Tracer in the same distribution)

    Simple tracing and debugging support for Perl 6 grammars

Please see the documentation for these programs for further information.

Historically others have existed and others are likely to be written in future, check the Perl 6 Modules website.

# 45 class AST

Abstract representation of a piece of source code

    class AST { }

An AST or Abstract Syntax Tree is a partially processed representation of a program. ASTs are return values of the quasi quoting construct, and are typically used within macros to generate code that is inserted in the calling location of the macro.

There is no API defined for ASTs yet. Hopefully that will emerge as part of the work on macros.

# 46 class Any

Thing/object

    class Any is Mu { ... }

While Mu is the root of the Perl 6 class hierarchy, Any is the class that serves as a default base class for new classes, and as the base class for most built-in classes.

Since Perl 6 intentionally confuses items and single-element lists, most methods in Any are also present on class List, and coerce to List or a list-like type.

# 46.1 Methods

## 46.1.1 method ACCEPTS

Defined as:

    multi method ACCEPTS(Any:D: Mu $other)

Usage:

    EXPR.ACCEPTS(EXPR);

Returns True if $other === self (i.e. it checks object identity).

Many built-in types override this for more specific comparisons

## 46.1.2 method any

Defined as:

    method any() returns Junction:D

Usage:

    LIST.any

Interprets the invocant as a list and creates an any-Junction from it.

    say so 2 == &lt;1 2 3>.any;        # True
    say so 5 == &lt;1 2 3>.any;        # False

## 46.1.3 method all

Defined as:

    method all() returns Junction:D

Usage:

    LIST.all

Interprets the invocant as a list and creates an all-Junction from it.

    say so 1 &lt; &lt;2 3 4>.all;         # True
    say so 3 &lt; &lt;2 3 4>.all;         # False

## 46.1.4 method one

Defined as:

    method one() returns Junction:D

Usage:

    LIST.one

Interprets the invocant as a list and creates a one-Junction from it.

    say so 1 == (1, 2, 3).one;      # True
    say so 1 == (1, 2, 1).one;      # False

## 46.1.5 method none

Defined as:

    method none() returns Junction:D

Usage:

    LIST.none

Interprets the invocant as a list and creates a none-Junction from it.

    say so 1 == (1, 2, 3).none;     # False
    say so 4 == (1, 2, 3).none;     # True

## 46.1.6 method list

Interprets the invocant as a list, and returns that List.

    say 42.list.^name;           # List
    say 42.list.elems;           # 1

## 46.1.7 method push

The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

    my %h;
    dd %h&lt;a>; # Any (and therefor undefined)
    %h&lt;a>.push(1); # .push on Any
    dd %h; # «Hash %h = {:a($[1])}␤» # please note the Array

## 46.1.8 routine reverse

Defined as:

    multi sub    reverse(*@list ) returns List:D
    multi method reverse(List:D:) returns List:D

Usage:

    reverse(LIST)
    LIST.reverse

Returns a list with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

    say &lt;hello world!>.reverse      #  world! hello
    say reverse ^10                 # 9 8 7 6 5 4 3 2 1 0

## 46.1.9 method sort

Sorts iterables with infix:<cmp> or given code object and returns a new List.

Examples:

    say &lt;b c a>.sort;                           # a b c
    say 'bca'.comb.sort.join;                   # abc
    say 'bca'.comb.sort({$^b cmp $^a}).join;    # cba
    say '231'.comb.sort(&amp;infix:«&lt;=>»).join;     # 123

## 46.1.10 method map

Defined as:

    proto method map(|) is nodal { * }
    multi method map(\SELF: &amp;block;; :$label, :$item)
    multi method map(HyperIterable:D: &amp;block;; :$label)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

## 46.1.11 method deepmap

Defined as:

    method deepmap(&amp;block -->List) is nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

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

## 46.1.12 method duckmap

Defined as:

    method duckmap(&amp;block) is rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

    my @a = [1,[2,3],4];
    dd @a.duckmap({ $_ ~~ Int ?? $_++ !! Any });
    # OUTPUT«(1, (2, 3), 4)␤»

## 46.1.13 method flat

Interprets the invocant as a list, flattens it, and returns that list. Please note that .flat will not solve the halting problem for you. If you flat an infinite list .flat may return that infinite list, eating all your RAM in the process.

    say ((1, 2), (3)).elems;        # 2
    say ((1, 2), (3)).flat.elems;   # 3

## 46.1.14 method eager

Interprets the invocant as a list, evaluates it eagerly, and returns that list.

    say (1..10).eager;              # 1 2 3 4 5 6 7 8 9 10

## 46.1.15 method elems

Interprets the invocant as a list, and returns the number of elements in the list.

    say 42.elems;                   # 1
    say &lt;a b c>.elems;              # 3

## 46.1.16 method end

Interprets the invocant as a list, and returns the last index of that list.

    say 6.end;                      # 0
    say &lt;a b c>.end;                # 2

## 46.1.17 method pairup

    method pairup() returns List

Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed is passed through, and the next list item, if any, is considered to be a key again).

    say (a => 1, 'b', 'c').pairup.perl;     # ("a" => 1, "b" => "c").list

## 46.1.18 sub exit

    sub exit(Int() $status = 0)

Exits the current process with return code $status.

TODO maybe find a better place to document &exit

# 47 class Array

Sequence of itemized values

    class Array is List { ... }

An Array is a List which forces all its elements to be scalar containers, which means you can assign to array elements.

# 47.1 Methods

## 47.1.1 routine pop

Defined as:

    multi sub    pop(Array:D )
    multi method pop(Array:D:)

Usage:

    pop ARRAY
    ARRAY.pop

Removes and returns the last item from the array. Fails for an empty array.

Example:

    > my @foo = &lt;a b>;
    a b
    > @foo.pop;
    b
    > pop @foo
    a
    > pop @foo
    Element popped from empty list

## 47.1.2 routine push

Defined as:

    multi sub    push(Array:D, **@values) returns Array:D
    multi method push(Array:D: **@values) returns Array:D

Usage:

    push ARRAY, VALUES
    ARRAY.push(VALUES)
    ARRAY.push: VALUES

Adds the @values to the end of the array, and returns the modified list. Fails for infinite arrays.

Example:

    my @foo = &lt;a b c>;
    @foo.push: 'd';
    say @foo;                   # a b c d

Note that push does not attempt to flatten its argument list. If you pass an array or list as the thing to push, it becomes one additional element:

    my @a = &lt;a b c>;
    my @b = &lt;d e f>;
    @a.push: @b;
    say @a.elems;               # 4
    say @a[3].join;             # def

Only if you supply multiple values as separate arguments to push are multiple values added to the array:

    my @a = '1';
    my @b = &lt;a b>;
    my @c = &lt;E F>;
    @a.push: @b, @c;
    say @a.elems;                # 3

See method append for when you want to append multiple values that are stored in a single array.

## 47.1.3 method append

Defined as

    sub append(\array, elems)
    multi method append(Array:D: \values)
    multi method append(Array:D: **@values is raw)

Usage:

    ARRAY.append(LIST)
    append ARRAY, LIST

Appends the argument list to the array passed as the first argument. This modifies the array in-place. Returns the modified array.

The difference from method push is that with an array or list argument, append appends several elements (one for each array or list element), whereas push appends just one element.

Example:

    my @a = &lt;a b c>;
    my @b = &lt;d e f>;
    @a.append: @b;
    say @a.elems;               # 6
    say @a;                     # a b c d e f

## 47.1.4 routine shift

Defined as:

    multi sub    shift(Array:D )
    multi method shift(Array:D:)

Usage:

    shift ARRAY
    ARRAY.shift

Removes and returns the first item from the array. Fails for an empty arrays.

Example:

    my @foo = &lt;a b>;
    say @foo.shift;             # a
    say @foo.shift;             # b
    say @foo.shift;             # Element shifted from empty list

## 47.1.5 routine unshift

Defined as:

    multi sub    unshift(Array:D, **@values) returns Array:D
    multi method unshift(Array:D: **@values) returns Array:D

Usage:

    unshift ARRAY, VALUES
    ARRAY.unshift(VALUES)
    ARRAY.unshift: VALUES

Adds the @values to the start of the array, and returns the modified array. Fails if @values is infinite.

Example:

    my @foo = &lt;a b c>;
    @foo.unshift: 1, 3 ... 11;
    say @foo;                   # (1 3 5 7 9 11) a b c

The notes in the documentation for method push apply, regarding how many elements are added to the array.

#method prepend is the equivalent for adding multiple elements from one list or array.

## 47.1.6 method prepend

Defined as

    sub prepend(\array, elems)
    multi method prepend(Array:D: \values)
    multi method prepend(Array:D: **@values is raw)

Usage:

    ARRAY.prepend(LIST)
    prepend ARRAY, LIST

Adds the elements from LIST to the front of the array, modifying it in-place.

Example:

    my @foo = &lt;a b c>;
    @foo.prepend: 1, 3 ... 11;
    say @foo;                   # 1 3 5 7 9 11 a b c

## 47.1.7 routine splice

Defined as:

    multi sub    splice(@list,  $start, $elems?, *@replacement) returns Array
    multi method splice(Array:D $start, $elems?, *@replacement) returns Array

Usage:

    splice(ARRAY, START, ELEMS?, REPLACEMENT?)
    ARRAY.splice(START, ELEMS?, REPLACEMENT?)

Deletes $elems elements starting from index $start from the Array, returns them and replaces them by @replacement. If $elems is omitted, all the elements starting from index $start are deleted.

Example:

    my @foo = &lt;a b c d e f g>;
    say @foo.splice(2, 3, &lt;M N O P>);        # c d e
    say @foo;                                # a b M N O P f g

## 47.1.8 method shape

Defined as:

    method shape() { (*,) }

Usage:

    ARRAY.shape

Returns the shape of the array as a list.

Example:

    my @foo[2;3] = ( &lt; 1 2 3 >, &lt; 4 5 6 > ); # Array with fixed dimensions
    say @foo.shape;                          # (2 3)
    my @bar = ( &lt; 1 2 3 >, &lt; 4 5 6 > );      # Normal array (of arrays)
    say @bar.shape;                          # (*)

## 47.1.9 method default

Defined as:

    method default

Usage:

    Array.default

Returns the default value of the invocant, i.e. the value which is returned when trying to access an element in the Array which has not been previously initialized or when accessing an element which has explicitly been set to Nil. Unless the Array is declared as having a default value by using the is default trait the method returns the type object (Any).

    my @a1 = 1, "two", 2.718;
    say @a1.default;                                       # (Any)
    say @a1[4];                                            # (Any)

    my @a2 is default(17) = 1, "two", 3;
    say @a2.default;                                       # 17
    say @a2[4];                                            # 17
    @a2[1] = Nil;                                          # (resets element to its default)
    say @a2[1];                                            # 17

## 47.1.10 method of

Defined as:

    method of

Usage:

    Array.of

Returns the type constraint for the values of the invocant. By default, i.e. if no type constraint is given during declaration, the method returns (Mu).

    my @a1 = 1, 'two', 3.14159;              # (no type constraint specified)
    say @a1.of;                              # (Mu)

    my Int @a2 = 1, 2, 3;                    # (values must be of type Int)
    say @a2.of;                              # (Int)
    @a2.push: 'd';                           # throws X::TypeCheck::Assignment

# 48 role Associative

Object that supports looking up values by key

    role Associative { }

A common role for types that support name-based lookup through postcircumfix:<{ }> , for example Hash and Map.

The % sigil restricts variables to objects that do Associative.

Associative does not provide any methods.

# 49 class Attribute

Member variable

    class Attribute { }

In Perl 6 lingo, an attribute refers to a per-instance/object storage slot. An Attribute is used to talk about classes' and roles' attributes on the meta level.

Normal usage of attributes does not require the user to use class Attribute explicitly.

The usual way to obtain an object of type Attribute is by introspection:

    class Useless {
        has @!things;
    }
    my $a = Useless.^attributes(:local)[0];
    say $a.name;            # @!things
    say $a.package;         # Useless()
    say $a.has_accessor;    # False

    # modifying an attribute from the outside
    # this is usually not possible, but since Attribute
    # is at the level of the meta class, all is fair game
    my $instance = Useless.new;
    $a.set_value($instance, [1, 2, 3]);
    say $a.get_value($instance);        # 1 2 3

# 49.1 Methods

## 49.1.1 method name

Defined as:

    method name(Attribute:D:) returns Str:D

Usage:

    ATTRIBUTE.name

Returns the name of the attribute. Note that this is always the private name, so if an attribute is declared as has $.a, the name returned is $!a.

## 49.1.2 method package

Defined as:

    method package(Attribute:D:) returns Mu:U

Usage:

    ATTRIBUTE.package

Returns the package (class/grammar/role) to which this attribute belongs.

## 49.1.3 method has_accessor

Defined as:

    method has_accessor(Attribute:D:) returns Bool:D

Usage:

    ATTRIBUTE.has_accessor

Returns True if the attribute has a public accessor method.

## 49.1.4 method readonly

Defined as:

    method readonly(Attribute:D:) returns Bool:D

Usage:

    ATTRIBUTE.readonly

Returns True for readonly attributes, which is the default. Returns False for attributes marked as is rw.

## 49.1.5 method type

Defined as:

    method type(Attribute:D:) returns Mu

Usage:

    ATTRIBUTE.type

Returns the type constraint of the attribute.

## 49.1.6 method get_value

Defined as:

    method get_value(Attribute:D: Mu $instance)

Usage:

    my $val = ATTRIBUTE.get_value(OBJECT)

Returns the value stored in this attribute of object $instance.

Note that this method violates encapsulation of the object, and should be used with care. Here be dragons.

## 49.1.7 method set_value

Defined as:

    method set_value(Attribute:D: Mu $instance, Mu \new_val)

Usage:

    ATTRIBUTE.set_value(OBJECT, NEW_VALUE)

Binds the value new_val to this attribute of object $instance.

Note that this method violates encapsulation of the object, and should be used with care. Here be dragons.

## 49.1.8 trait is required

    multi sub trait_mod:&lt;is> (Attribute $attr, :$required!)

Marks an attribute as being required. If a value is not provided during object construction, an exception is thrown.

    class Foo {
       has $.bar is required;
       has $.baz;
    }

    Foo.new(bar => 42) # works
    Foo.new(baz => 42) # fails - bar is required

is required doesn't just affect the default constructor, it checks for the attribute at a lower level, so it will work for custom constructors written using bless.

## 49.1.9 trait is rw

    multi sub trait_mod:&lt;is> (Attribute:D $attr, :$rw!)

Marks an attribute as read/write as opposed to the default readonly. The default accessor for the attribute will return a writable value.

    class Foo {
       has $.bar is rw;
       has $.baz;
    }

    my $foo = Foo.new;
    $foo.bar = 42; # works
    $foo.baz = 42; # fails

# 50 class Backtrace

Snapshot of the dynamic call stack

    class Backtrace is List { ... }

A backtrace shows the dynamic call stack, usually leading up to a point where an exception was thrown.

It is a List of Backtrace::Frame objects. Its default stringification excludes backtrace frames that are deemed unnecessary or confusing, for example routines like &die are hidden by default.

# 50.1 Methods

## 50.1.1 method new

Defined as:

    proto method new(*@, *%) {*}
    multi method new()

Usage:

    $backtrace = Backtrace.new

Creates a new backtrace, using its calling location as the origin of the backtrace.

## 50.1.2 method Str

Defined as:

    multi method Str(Backtrace:D:) returns Str:D:

Usage:

    BACKTRACE.Str

Returns a concise string representation of the backtrace, omitting routines marked as is hidden-from-backtrace, and at the discretion of the implementor, also some routines from the setting.

## 50.1.3 method full

Defined as:

    multi method full(Backtrace:D:) returns Str:D:

Usage:

    BACKTRACE.full

Returns a full string representation of the backtrace, including hidden frames, compiler-specific frames and those from the setting.

# 51 class Backtrace::Frame

Single frame of a

    class Backtrace::Frame { }

A single backtrace frame. It identifies a location in the source code.

# 51.1 Methods

## 51.1.1 method file

Defined as:

    method file(Backtrace::Frame:D) returns Str

Usage:

    FRAME.file

Returns the file name.

## 51.1.2 method line

Defined as:

    method line(Backtrace::Frame:D) returns Int

Usage:

    FRAME.line

Returns the line number (line numbers start to count from 1).

## 51.1.3 method code

Defined as:

    method code(Backtrace::Frame:D)

Usage:

    FRAME.code

Returns the code object into which .file and .line point, if available.

## 51.1.4 method subname

Defined as:

    method subname(Backtrace::Frame:D) returns Str

Usage:

    FRAME.subname

Returns the name of the enclosing subroutine.

## 51.1.5 method is-hidden

Defined as:

    method is-hidden(Backtrace::Frame:D) return Bool:D

Usage:

    FRAME.is-hidden

Returns True if the frame is marked as hidden with the is hidden-from-backtrace trait.

## 51.1.6 method is-routine

Defined as:

    method is-routine(Backtrace::Frame:D) return Bool:D

Usage:

    FRAME.is-routine

Return True if the frame point into a routine (and not into a mere Block).

## 51.1.7 method is-setting

Defined as:

    method is-setting(Backtrace::Frame:D) return Bool:D

Usage:

    FRAME.is-setting

Returns True if the frame is part of a setting.

# 52 class Bag

Immutable collection of distinct objects with integer weights

    class Bag does Baggy { }

A Bag is an immutable bag/multiset, meaning a collection of distinct elements in no particular order that each have an integer weight assigned to them signifying how many copies of that element are considered "in the bag". (For mutable bags, see BagHash instead.)

Bags are often used for performing weighted random selections - see .pick and .roll.

Objects/values of any type are allowed as bag elements. Within a Bag, items that would compare positively with the === operator are considered the same element, with the number of how many there are as its weight. But of course you can also easily get back the expanded list of items (without the order):

    my $breakfast = bag &lt;spam eggs spam spam bacon spam>;

     say $breakfast.elems;      # 3
     say $breakfast.keys.sort;  # bacon eggs spam

     say $breakfast.total;      # 6
     say $breakfast.kxxv.sort;  # bacon eggs spam spam spam spam

Bags can be treated as object hashes using the { } postcircumfix operator, or the < > operator for literal string keys, which returns the corresponding integer weight for keys that are elements of the bag, and 0 for keys that aren't:

    say $breakfast&lt;bacon>;    # 1
    say $breakfast&lt;spam>;     # 4
    say $breakfast&lt;sausage>;  # 0

# 52.1 Creating Bag objects

Bags can be composed using the bag subroutine (or Bag.new, for which it is a shorthand). Any positional parameters, regardless of their type, become elements of the bag:

    my $n = bag "a" => 0, "b" => 1, "c" => 2, "c" => 2;
    say $n.keys.perl;        # ("a" => 0, "b" => 1, "c" => 2, "c" => 2).list
    say $n.keys.map(&amp;WHAT);  # (Pair) (Pair) (Pair) (Pair)
    say $n.values.perl;      # (1, 1, 1, 1).list

Alternatively, the .Bag coercer (or its functional form, Bag()) can be called on an existing object to coerce it to a Bag. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a bag with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the bag, and the (cumulative) values become the associated integer weights:

    my $n = ("a" => 0, "b" => 1, "c" => 2, "c" => 2).Bag;
    say $n.keys.perl;        # ("b", "c").list
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)
    say $n.values.perl;      # (1, 4).list

Furthermore, you can get a Bag by using bag operators (see next section) on objects of other types such as List, which will internally call .Bag on them before performing the operation. Be aware of the tight precedence of those operators though, which may require you to use parens around arguments:

    say (1..5) (+) 4;  # bag(1, 2, 3, 4(2), 5)

# 52.2 Operators

Perl 6 provides common set and bag operators, which can take Bags (or any other collections) as input, and return result as Bool, Set or Bag values. For example:

    my ($a, $b) = bag(2, 2, 4), bag(2, 3, 3, 4);

     say $a (&lt;) $b;   # True
     say $a (&lt;+) $b;  # False
     say $a (^) $b;   # set(3)
     say $a (+) $b;   # bag(2(3), 4(2), 3(2))

     # Unicode versions:
     say $a ⊂ $b;  # True
     say $a ≼ $b;  # False
     say $a ⊖ $b;  # set(3)
     say $a ⊎ $b;  # bag(2(3), 4(2), 3(2))

See Set/Bag Operators for a complete list of set and bag operators with detailed explanations.

# 52.3 Subroutines

## 52.3.1 sub bag

    sub bag(*@args --> Bag)

Creates a new Bag from @args.

# 52.4 See Also

Sets, Bags, and Mixes

# 53 class BagHash

Mutable collection of distinct objects with integer weights

    class BagHash does Baggy { }

A BagHash is a mutable bag/multiset, meaning a collection of distinct elements in no particular order that each have an integer weight assigned to them signifying how many copies of that element are considered "in the bag". (For immutable bags, see Bag instead.)

Objects/values of any type are allowed as bag elements. Within a BagHash, items that would compare positively with the === operator are considered the same element, with the number of how many there were as its weight. But of course you can also easily get back the expanded list of items (without the order):

    my $breakfast = &lt;spam eggs spam spam bacon spam>.BagHash;

     say $breakfast.elems;      # 3
     say $breakfast.keys.sort;  # bacon eggs spam

     say $breakfast.total;      # 6
     say $breakfast.kxxv.sort;  # bacon eggs spam spam spam spam

BagHashes can be treated as object hashes using the { } postcircumfix operator, which returns the corresponding integer weight for keys that are elements of the bag, and 0 for keys that aren't. It can also be used to modify weights; setting a weight to 0 automatically removes that element from the bag, and setting a weight to a positive number adds that element if it didn't already exist:

    say $breakfast&lt;bacon>;     # 1
     say $breakfast&lt;spam>;      # 4
     say $breakfast&lt;sausage>;   # 0

     $breakfast&lt;sausage> = 2;
     $breakfast&lt;bacon>--;
     say $breakfast.kxxv.sort;  # eggs sausage sausage spam spam spam spam

# 53.1 Creating BagHash objects

BagHashes can be composed using BagHash.new. Any positional parameters, regardless of their type, become elements of the bag:

    my $n = BagHash.new: "a" => 0, "b" => 1, "c" => 2, "c" => 2;
    say $n.keys.perl;        # ("a" => 0, "b" => 1, "c" => 2, "c" => 2).list
    say $n.keys.map(&amp;WHAT);  # (Pair) (Pair) (Pair) (Pair)
    say $n.values.perl;      # (1, 1, 1, 1).list

Alternatively, the .BagHash coercer (or its functional form, BagHash()) can be called on an existing object to coerce it to a BagHash. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a bag with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the bag, and the (cumulative) values become the associated integer weights:

    my $n = ("a" => 0, "b" => 1, "c" => 2, "c" => 2).BagHash;
    say $n.keys.perl;        # ("b", "c").list
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)
    say $n.values.perl;      # (1, 4).list

# 53.2 Operators

Perl 6 provides common set and bag operators, which can take BagHashes (or any other collections) as input, and return result as Bool, Set or Bag values. For example:

    my ($a, $b) = BagHash.new(2, 2, 4), BagHash.new(2, 3, 3, 4);

     say $a (&lt;) $b;   # True
     say $a (&lt;+) $b;  # False
     say $a (^) $b;   # set(3)
     say $a (+) $b;   # bag(2(3), 4(2), 3(2))

     # Unicode versions:
     say $a ⊂ $b;  # True
     say $a ≼ $b;  # False
     say $a ⊖ $b;  # set(3)
     say $a ⊎ $b;  # bag(2(3), 4(2), 3(2))

See Set/Bag Operators for a complete list of set and bag operators with detailed explanations.

# 53.3 See Also

Sets, Bags, and Mixes

# 54 role Baggy

Collection of distinct weighted objects

    role Baggy does QuantHash { }

A role for collections of weighted objects. See Bag, BagHash, and Mixy.

# 54.1 Methods

## 54.1.1 method grab

Defined as:

    multi method grab(Baggy:D:) returns Any
    multi method grab(Baggy:D: $count) returns Array:D

Like pick, a grab returns a random selection of elements, weighted by the values corresponding to each key. Unlike pick, it works only on mutable structures, e.g. BagHash. Use of grab on an immutable structure results in an X::Immutable exception. If * is passed as $count, or $count is greater than or equal to the total of the invocant, then total elements from the invocant are returned in a random sequence.

Grabbing decrements the grabbed key's weight by one (deleting the key when it reaches 0). By definition, the total of the invocant also decreases by one, so the probabilities stay consistent through subsequent grab operations.

    my $cars = ('Ford' => 2, 'Rover' => 3).BagHash;
    say $cars.grab;                                   # Ford
    say $cars.grab(2);                                # [Rover Rover]
    say $cars.grab(*);                                # [Rover Ford]

    my $breakfast = ('eggs' => 2, 'bacon' => 3).Bag;
    say $breakfast.grab;                              # throws X::Immutable exception

## 54.1.2 method grabpairs

Defined as:

    multi method grabpairs(Baggy:D:) returns Any
    multi method grabpairs(Baggy:D: $count) returns List:D

Returns a Pair or a List of Pairs depending on the version of the method being invoked. Each Pair returned has an element of the invocant as its key and the elements weight as its value. Unlike pickpairs, it works only on mutable structures, e.g. BagHash. Use of grabpairs on 'an immutable structure results in an X::Immutable exception. If * is passed as $count, or $count is greater than or equal to the number of elements of the invocant, then all element/weight Pairs from the invocant are returned in a random sequence.

What makes grabpairs different from pickpairs is that the 'grabbed' elements are in fact removed from the invocant.

    my $breakfast = (eggs => 2, bacon => 3).BagHash;
    say $breakfast.grabpairs;                         # bacon => 3
    say $breakfast;                                   # BagHash.new(eggs(2))
    say $breakfast.grabpairs(1);                      # (eggs => 2)
    say $breakfast.grabpairs(*);                      # []

    my $diet = ('eggs' => 2, 'bacon' => 3).Bag;
    say $diet.grabpairs;                              # throws X::Immutable exception

## 54.1.3 method pick

Defined as:

    multi method pick(Baggy:D:) returns Any
    multi method pick(Baggy:D: $count) returns Seq:D

Like an ordinary list pick, but returns keys of the invocant weighted by their values, as if the keys were replicated the number of times indicated by the corresponding value and then list pick used. The underlying metaphor for picking is that you're pulling colored marbles out a bag. (For "picking with replacement" see roll instead). If * is passed as $count, or $count is greater than or equal to the total of the invocant, then total elements from the invocant are returned in a random sequence.

Note that each pick invocation maintains its own private state and has no effect on subsequent pick invocations.

    my $breakfast = bag &lt;eggs bacon bacon bacon>;
    say $breakfast.pick;                              # eggs
    say $breakfast.pick(2);                           # (eggs bacon)

    say $breakfast.total;                             # 4
    say $breakfast.pick(*);                           # (bacon bacon bacon eggs)

## 54.1.4 method pickpairs

Defined as:

    multi method pickpairs(Baggy:D:) returns Pair:D
    multi method pickpairs(Baggy:D: $count) returns List:D

Returns a Pair or a List of Pairs depending on the version of the method being invoked. Each Pair returned has an element of the invocant as its key and the elements weight as its value. The elements are 'picked' without replacement. If * is passed as $count, or $count is greater than or equal to the number of elements of the invocant, then all element/weight Pairs from the invocant are returned in a random sequence.

Note that each pickpairs invocation maintains its own private state and has no effect on subsequent pickpairs invocations.

    my $breakfast = bag &lt;eggs bacon bacon bacon>;
    say $breakfast.pickpairs;                         # eggs => 1
    say $breakfast.pickpairs(1);                      # (bacon => 3)
    say $breakfast.pickpairs(*);                      # (eggs => 1 bacon => 3)

## 54.1.5 method roll

Defined as:

    multi method roll(Baggy:D:) returns Any:D
    multi method roll(Baggy:D: $count) returns Seq:D

Like an ordinary list roll, but returns keys of the invocant weighted by their values, as if the keys were replicated the number of times indicated by the corresponding value and then list roll used. The underlying metaphor for rolling is that you're throwing $count dice that are independent of each other, which (in bag terms) is equivalent to picking a colored marble out your bag and then putting it back, and doing this $count times. In dice terms, the number of marbles corresponds to the number of sides, and the number of marbles of the same color corresponds to the number of sides with the same color. (For "picking without replacement" see pick instead).

If * is passed to $count, returns a lazy, infinite sequence of randomly chosen elements from the invocant.

    my $breakfast = bag &lt;eggs bacon bacon bacon>;
    say $breakfast.roll;                                  # bacon
    say $breakfast.roll(3);                               # (bacon eggs bacon)

    my $random_dishes := $breakfast.roll(*);
    say $random_dishes[^5];                               # (bacon eggs bacon bacon bacon)

## 54.1.6 method pairs

Defined as:

    method pairs(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs where the key is the element itself and the value is the weight of that element.

    my $breakfast = bag &lt;bacon eggs bacon>;
    my $seq = $breakfast.pairs;
    say $seq.sort;                                    # (bacon => 2 eggs => 1)

## 54.1.7 method antipairs

Defined as:

    method antipairs(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs, where the element itself is the value and the weight of that element is the key, i.e. the opposite of method pairs.

    my $breakfast = bag &lt;bacon eggs bacon>;
    my $seq = $breakfast.antipairs;
    say $seq.sort;                                    # (1 => eggs 2 => bacon)

## 54.1.8 method invert

Defined as:

    method invert(Baggy:D:) returns Seq:D

Returns all elements and their respective weights as a Seq of Pairs, where the element itself is the value and the weight of that element is the key, i.e. the opposite of method pairs. Except for some esoteric cases invert on a Baggy type returns the same result as antipairs.

    my $breakfast = bag &lt;bacon eggs bacon>;
    my $seq = $breakfast.invert;
    say $seq.sort;                                    # (1 => eggs 2 => bacon)

## 54.1.9 method classify-list

Defined as:

    multi method classify-list(&amp;test, *@list) returns Baggy:D

Transforms a list of values into a classification of those values according to &test and stores the results in the invocant which is then returned. Each key represents the classification for one or more of the incoming list values, and the corresponding value contains the number of list values classified by &test into the category of the associated key.

As an example, suppose that we have a list of Ints which we would like to classify into two categories, namely even and odd numbers. Here's one way to solve this problem:

    my $b = BagHash.new();
    dd $b.classify-list( { $_ %% 2 ?? 'even' !! 'odd' }, (1, 7, 6, 3, 2) );
    # returns: ("even"=>2,"odd"=>3).BagHash

The printed result shows us that of the numbers in the list two were classified as even and three as odd. Note that the result doesn't show us which numbers were classified as being even or odd. If that's what you want, use the classify routine in List instead.

## 54.1.10 method categorize-list

TODO

## 54.1.11 method keys

Defined as:

    method keys(Baggy:D:) returns List:D

Returns a list of all keys in the Baggy object without taking their individual weights into account as opposed to kxxv.

    my $breakfast = bag &lt;eggs spam spam spam>;
    say $breakfast.keys.sort;                        # (eggs spam)

    my $n = ("a" => 5, "b" => 2).BagHash;
    say $n.keys.sort;                                # (a b)

## 54.1.12 method values

Defined as:

    method values(Baggy:D:) returns List:D

Returns a list of all values, i.e. weights, in the Baggy object.

    my $breakfast = bag &lt;eggs spam spam spam>;
    say $breakfast.values.sort;                      # (1 3)

    my $n = ("a" => 5, "b" => 2, "a" => 1).BagHash;
    say $n.values.sort;                              # (2 6)

## 54.1.13 method kv

Defined as:

    method kv(Baggy:D:) returns List:D

Returns a list of keys and values interleaved.

    my $breakfast = bag &lt;eggs spam spam spam>;
    say $breakfast.kv;                                # (spam 3 eggs 1)

    my $n = ("a" => 5, "b" => 2, "a" => 1).BagHash;
    say $n.kv;                                        # (a 6 b 2)

## 54.1.14 method kxxv

Defined as:

    method kxxv(Baggy:D:) returns List:D

Returns a list of the keys of the invocant, with each key multiplied by its weight. Note that kxxv only works for Baggy types which have integer weights, i.e. Bag and BagHash.

    my $breakfast = bag &lt;spam eggs spam spam bacon>;
    say $breakfast.kxxv.sort;                         # (bacon eggs spam spam spam)

    my $n = ("a" => 0, "b" => 1, "b" => 2).BagHash;
    say $n.kxxv;                                      # (b b b)

## 54.1.15 method elems

Defined as:

    method elems(Baggy:D:) returns Int:D

Returns the number of elements in the Baggy object without taking the individual elements weight into account.

    my $breakfast = bag &lt;eggs spam spam spam>;
    say $breakfast.elems;                             # 2

    my $n = ("b" => 9.4, "b" => 2).MixHash;
    say $n.elems;                                     # 1

## 54.1.16 method total

Defined as:

    method total(Baggy:D:)

Returns the sum of weights for all elements in the Baggy object.

    my $breakfast = bag &lt;eggs spam spam bacon>;
    say $breakfast.total;                             # 4

    my $n = ("a" => 5, "b" => 1, "b" => 2).BagHash;
    say $n.total;                                     # 8

## 54.1.17 method default

Defined as:

    method default(Baggy:D:) returns Int:D

Returns zero.

    my $breakfast = bag &lt;eggs bacon>;
    say $breakfast.default;                           # 0

## 54.1.18 method hash

Defined as:

    method hash(Baggy:D:) returns Hash:D

Returns a Hash where the elements of the invocant are the keys and their respective weights the values;

    my $breakfast = bag &lt;eggs bacon bacon>;
    my $h = $breakfast.hash;
    say $h.WHAT;                                      # (Hash)
    say $h;                                           # {bacon => 2, eggs => 1}

## 54.1.19 method Bool

Defined as:

    method Bool(Baggy:D:) returns Bool:D

Returns True if the invocant contains at least one element.

    my $breakfast = ('eggs' => 1).BagHash;
    say $breakfast.Bool;                              # True   (since we have one element)
    $breakfast&lt;eggs> = 0;                             # weight == 0 will lead to element removal
    say $breakfast.Bool;                              # False

## 54.1.20 method Set

Defined as:

    method Set() returns Set:D

Returns a Set whose elements are the keys of the invocant.

    my $breakfast = (eggs => 2, bacon => 3).BagHash;
    say $breakfast.Set;                               # set(bacon, eggs)

## 54.1.21 method SetHash

Defined as:

    method SetHash() returns SetHash:D

Returns a SetHash whose elements are the keys of the invocant.

    my $breakfast = (eggs => 2, bacon => 3).BagHash;
    my $sh = $breakfast.SetHash;
    say $sh.WHAT;                                     # (SetHash)
    say $sh.elems;                                    # 2

## 54.1.22 method ACCEPTS

Defined as:

    method ACCEPTS($other) returns Bool:D

Used in smart-matching if the right-hand side is a Baggy.

If the right hand side is the type object, i.e. Baggy, the method returns True if $other does Baggy otherwise False is returned.

If the right hand side is a Baggy object, True is returned only if $other has the same elements, with the same weights, as the invocant.

    my $breakfast = bag &lt;eggs bacon>;
    say $breakfast ~~ Baggy;                            # True
    say $breakfast.does(Baggy);                         # True

    my $second-breakfast = (eggs => 1, bacon => 1).Mix;
    say $breakfast ~~ $second-breakfast;                # True

    my $third-breakfast = (eggs => 1, bacon => 2).Bag;
    say $second-breakfast ~~ $third-breakfast;          # False

# 54.2 See Also

Sets, Bags, and Mixes

# 55 role Blob

Immutable buffer for binary data ('Binary Large OBject')

    role Blob[::T = uint8] does Positional[T] does Stringy { }

The Blob role is an immutable interface to binary types, and offers a list-like interface to lists of integers, typically unsigned integers.

# 55.1 Methods

## 55.1.1 method new

Defined as:

    method new(*@codes)

Usage:

    $blob = Blob.new(LIST)

Creates a Blob from a list of integers.

## 55.1.2 method Bool

Defined as:

    multi method Bool(Blob:D:)

Usage:

    BLOB.Bool

Returns False if and only if the buffer is empty.

## 55.1.3 method elems

Defined as:

    multi method elems(Blob:D:) returns Int:D

Usage:

    BLOB.elems

Returns the number of elements of the buffer.

## 55.1.4 method decode

Defined as:

    multi method decode(Blob:D: Str:D $encoding = 'UTF-8') returns Str:D

Usage:

    BLOB.decode(ENCODING?)

Applies an encoding to turn the blob into a Str.

## 55.1.5 method subbuf

Defined as:

    method subbuf(Int $from, Int $len = self.elems) returns Blob:D
    method subbuf(Range $range) returns Blob:D

Usage:

    BLOB.subbuf(FROM, LENGTH?)
    BLOB.subbuf(RANGE)

Extracts a part of the invocant buffer, starting from the index with elements $from, and taking $len elements (or less if the buffer is shorter), and creates a new buffer as the result.

    say Blob.new(1..10).subbuf(2, 4);    # Blob:0x&lt;03 04 05 06>
    say Blob.new(1..10).subbuf(*-2);     # Blob:0x&lt;09 0a>
    say Blob.new(1..10).subbuf(*-5,2);   # Blob:0x&lt;06 07>

For convenience, also allows a Range to be specified to indicate which part of the invocant buffer you would like:

    say Blob.new(1..10).subbuf(2..5);    # Blob:0x&lt;03 04 05 06>

## 55.1.6 method unpack

This method is considered experimental, in order to use it you will need to do:

    use experimental :pack;

Defined as:

    method unpack(Blob:D: $template) returns List:D

Usage:

    BLOB.unpack(TEMPLATE)

Extracts features from the blob according to the template string, and returns them as a list.

The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. The quantifier can be * (which typically stands for "use up the rest of the Blob here"), or a positive integer (without a +).

Whitespace between template units is ignored.

Examples of valid templates include "A4 C n*" and "A*".

The following letters are recognized:

Letter | Meaning
--- | ---
A | Extract a string, where each element of the Blob maps to a codepoint
a | Same as A
C | Extract an element from the blob as an integer
H | Extracts a hex string
L | Extracts four elements and returns them as a single unsigned integer
n | Extracts two elements and combines them in "network" (big-endian) byte order into a single integer
N | Extracts four elements and combines them in "network" (big-endian) byte order into a single integer
S | Extracts two elements and returns them as a single unsigned integer
v | Same as S
V | Same as L
x | Drop an element from the blob (that is, ignore it)
Z | Same as A

## 55.1.7 sub pack

This subroutine is considered experimental, in order to use it you will need to do:

    use experimental :pack;

    sub pack(Str $template, *@items) returns Buf

Packs the given items according to the template and returns a buffer containing the packed bytes.

The template string consists of zero or more units that begin with an ASCII letter, and are optionally followed by a quantifier. For details, see unpack.

# 56 class Block

Code object with its own lexical scope

    class Block is Code { }

A Block is a code object meant for small-scale code reuse. A block is created syntactically by a list of statements enclosed in curly braces.

Without an explicit signature or placeholder arguments, a block has $_ as a positional argument

    my $block = { uc $_; };
    say $block.WHAT;            # Block
    say $block('hello');        # HELLO

A block can have a signature between -> or <-> and the block:

    my $add = -> $a, $b { $a + $b };
    say $add(38, 4);            # 42

If the signature is introduced with <-> , then the parameters are marked as rw by default:

    my $swap = &lt;-> $a, $b { ($a, $b) = ($b, $a) };

    my ($a, $b) = (2, 4);
    $swap($a, $b);
    say $a;                     # 4

Blocks that aren't of type Routine (which is a subclass of Block) are transparent to return.

    sub f() {
        say &lt;a b c>.map: { return 42 };
                       #   ^^^^^^   exits &amp;f, not just the block
    }

The last statement is the implicit return value of the block.

    say {1}.(); # OUTPUT«1␤»

Bare blocks in sink context are automatically executed:

    say 1;
    {
        say 2;                  # executed directly, not a Block object
    }
    say 3;

# 57 enum Bool

Logical boolean

    enum Bool &lt;False True>

An enum for boolean true/false decisions.

# 57.1 Methods

## 57.1.1 routine succ

    method succ() returns Bool:D

Returns True.

    say True.succ;                                    # True
    say False.succ;                                   # True

## 57.1.2 routine pred

    method pred() returns Bool:D

Returns False.

    say True.pred;                                    # False
    say False.pred;                                   # False

## 57.1.3 routine enums

    method enums() returns Hash:D

Returns a Hash of enum-pairs. Works on both the Bool type and any key.

    say Bool.enums;                                   # {False => 0, True => 1}
    say False.enums;                                  # {False => 0, True => 1}

# 57.2 Operators

## 57.2.1 prefix ?

    multi sub prefix:&lt;?>(Mu) returns Bool:D

Coerces its argument to Bool.

## 57.2.2 prefix so

    multi sub prefix:&lt;so>(Mu) returns Bool:D

Coerces its argument to Bool, has looser precedence than prefix:<?> .

# 58 role Buf

Mutable buffer for binary data

    role Buf[::T] does Blob[T] { ... }

A Buf is a mutable sequence of (usually unsigned) integers.

    my $b = Buf.new(1, 2, 3);
    $b[1] = 42;

# 59 role Callable

Invocable code object

    role Callable { ... }

Role for objects which support calling them. It's used in Block, Routine, Sub, Method, Submethod and Macro types.

Callables can be stored in &-sigiled containers, the default type constraint of such a container is Callable. A signature object can be used to force a check against the signature of the Callable to be stored into the container.

    my &amp;a = {};
    my &amp;b = -> {};
    my &amp;c = sub () {};
    sub foo() {};
    my &amp;d = &amp;foo;
    my &amp;f:(Int) = sub bar(Int) {};
    my &amp;f:(Str) = -> Str {};

# 59.1 Methods

## 59.1.1 method assuming

    method assuming(Callable:D $self: |primers)

Returns a Callable that implements the same behaviour as the original, but has the values passed to .assuming already bound to the corresponding parameters.

    sub add(Int $x, Int $y) { $x + $y };
    my &amp;add_to_5 = &amp;add.assuming(5);
    say add_to_5(4); #-> 9

according to design docs it's Callable but in rakudo it's assuming is in Block

# 59.2 Operators

## 59.2.1 infix:<∘>

The function combinator infix:<∘> or infix:<o> combines two functions of arity one, so that the left function is called with the return value of the right function.

    sub f($p){ say 'f'; $p / 2 }
    sub g($p){ say 'g'; $p * 2 }
    my &amp;f-g = &amp;f ∘ &amp;g;
    say f-g(2); # OUTPUT«g␤f␤2␤»

# 60 class Cancellation

Removal of a task from a Scheduler before normal completion

    my class Cancellation { ... }

A low level part of the Perl 6 concurrency system. Some Scheduler objects return a Cancellation with the .cue method which can be used to cancel the scheduled execution before normal completion. Cancellation.cancelled is a boolean that is true after #cancel is called.

# 60.1 Methods

## 60.1.1 method cancel

Defined as:

    method cancel()

Usage:

    CANCELLATION.cancel

Cancels the scheduled execution of a task before normal completion.

# 61 class Capture

Argument list suitable for passing to a

    class Capture does Positional does Associative { }

A Capture is a container for passing arguments to a code object. Captures are the flip-side of Signatures -- Captures at the caller define arguments, while Signatures at the callee define parameters.

When you call print $a, $b, the $a, $b part is a Capture.

Captures contain a list-like part for positional arguments and a hash-like part for named arguments. For the named arguments, Captures use a slightly different syntax than a normal List. There are two easy ways to make a named argument: 1) use an unquoted key naming a parameter, followed by =>, followed by the argument and 2) use a colon-pair literal named after the parameter:

    say unique 1, -2, 2, 3, as => { abs $_ }; # 1, -2, 3
    # ... is the same thing as:
    say unique 1, -2, 2, 3, :as({ abs $_ });  # 1, -2, 3
    # Be careful not to quote the name of a named parameter:
    say unique 1, -2, 2, 3, 'as' => { abs $_ }; # 1, -2, 2, 3, "as" => { ... }

A stand-alone Capture can also be made, stored, and used later. A literal Capture can be created by prefixing a term with a backslash \. Commonly, this term will be a List of terms, from which any Pair literal will be placed in the named part, and all other terms will be placed in the positional part.

    my $c = \(42);          # Capture with one positional part
    $c = \(1, 2, a => 'b'); # Capture with two positional and one named parts

To use such a Capture, you may use '|' before it in a function call, and it will be as if the values in the Capture were passed directly to the function as arguments -- named arguments will be passed as named arguments and positional arguments will be passed as positional arguments. You may re-use the Capture as many times as you want, even with different functions.

    my $c = \(4, 2, 3);
    reverse(|$c).say; # 3 2 4
    sort(5,|$c).say;  # 2 3 4 5

Inside a Signature, a Capture may be created by prefixing a sigilless parameter with a vertical bar |. This packs the remainder of the argument list into that parameter.

    f(1, 2, 3, a => 4, b => 5);
    sub f($a, |c) {
        # c  is  \(2, 3, a => 4, b => 5)
    }

Note that Captures are still Lists in that they may contain containers, not just values:

    my $b = 1;
    my $c = \(4, 2, $b, 3);
    sort(|$c).say;        # 1 2 3 4
    $b = 6;
    sort(|$c).say;        # 2 3 4 6

# 61.1 Methods

## 61.1.1 method list

Defined as:

    method list(Capture:D:) returns Positional

Usage:

    CAPTURE.list

Returns the positional part of the Capture.

    my Capture $c = \(2, 3, 5, apples => (red => 2));
    say $c.list;                                      # (2 3 5)

## 61.1.2 method hash

Defined as:

    method hash(Capture:D:) returns Associative

Usage:

    CAPTURE.hash

Returns the named/hash part of the Capture.

## 61.1.3 method elems

Defined as:

    method elems(Capture:D:) returns Int:D

Usage:

    CAPTURE.elems

Returns the number of positional elements in the Capture.

    my Capture $c = \(2, 3, 5, apples => (red => 2));
    say $c.elems;                                     # 3

## 61.1.4 method keys

Defined as:

    multi method keys(Capture:D:) returns Seq:D

Usage:

    $capture.keys

Returns a Seq containing all positional keys followed by all named keys. For positional arguments the keys are the respective arguments ordinal position starting from zero.

    my $capture = \(2, 3, 5, apples => (red => 2));
    say $capture.keys;                                # (0 1 2 apples)

## 61.1.5 method values

Defined as:

    multi method values(Capture:D:) returns Seq:D

Usage:

    $capture.values

Returns a Seq containing all positional values followed by all named argument values.

    my $capture = \(2, 3, 5, apples => (red => 2));
    say $capture.values;                              # (2 3 5 red => 2)

## 61.1.6 method kv

Defined as:

    multi method kv(Capture:D:) returns Seq:D

Usage:

    $capture.kv

Returns a Seq of alternating keys and values. The positional keys and values, if any, comes first followed by the named keys and values.

    my $capture = \(2, 3, apples => (red => 2));
    say $capture.kv;                                  # (0 2 1 3 apples red => 2)

## 61.1.7 method pairs

Defined as:

    multi method pairs(Capture:D:) returns Seq:D

Usage:

    $capture.pairs

Returns all arguments, the positional followed by the named, as a Seq of Pairs. Positional arguments have their respective ordinal value, starting at zero, as key while the named arguments have their names as key.

    my Capture $c = \(2, 3, apples => (red => 2));
    say $c.pairs;                                     # (0 => 2 1 => 3 apples => red => 2)

## 61.1.8 method antipairs

Defined as:

    multi method antipairs(Capture:D:) returns Seq:D

Usage:

    $capture.antipairs

Returns all arguments, the positional followed by the named, as a Seq of pairs where the keys and values have been swapped, i.e. the value becomes the key and the key becomes the value. This behavior is the opposite of the pairs method.

    my $capture = \(2, 3, apples => (red => 2));
    say $capture.antipairs;                           # (2 => 0 3 => 1 (red => 2) => apples)

## 61.1.9 method Bool

Defined as:

    method Bool(Capture:D:) returns Bool:D

Usage:

    CAPTURE.Bool

Returns True if the Capture contains at least one named or one positional argument.

    say \(1,2,3, apples => 2).Bool;                   # True
    say \().Bool;                                     # False

## 61.1.10 method Capture

Defined as:

    method Capture(Capture:D:) returns Capture:D

Usage:

    CAPTURE.Capture

Returns itself, i.e. the invocant.

## 61.1.11 method Numeric

Defined as:

    method Numeric(Capture:D:) returns Int:D

Usage:

    CAPTURE.Numeric

Returns the number of positional elements in the Capture.

    say \(1,2,3, apples => 2).Numeric;                # 3

# 62 class Channel

Thread-safe queue for sending values from producers to consumers

    class Channel { ... }

A Channel is a thread-safe queue that helps you to send a series of objects from one or more producers to one or more consumers. Each object will arrive at only one such consumer, selected by the scheduler. If there is only one consumer and one producer, order of objects is guaranteed to be preserved. Sending on a Channel is non-blocking.

    my $c = Channel.new;
    await (^10).map: {
        start {
            my $r = rand;
            sleep $r;
            $c.send($r);
        }
    }
    $c.close;
    say $c.list;

Further examples can be found in the concurrency page

# 62.1 Methods

## 62.1.1 method send

Defined as:

    method send(Channel:D: \item)

Usage:

    CHANNEL.send(ITEM)

Enqueues an item into the Channel. Throws an exception of type X::Channel::SendOnClosed if the channel has been closed already. This call will not block waiting for a consumer to take the object. There is no set limit on the number of items that may be queued, so care should be taken to prevent runaway queueing.

## 62.1.2 method receive

Defined as:

    method receive(Channel:D:)

Usage:

    CHANNEL.receive

Receives and removes an item from the channel. It blocks if no item is present, waiting for a send from another thread.

Throws an exception of type X::Channel::ReceiveOnClosed if the channel has been closed, and the last item has been removed already, or if close is called while receive is waiting for an item to arrive.

If the channel has been marked as erratic with method fail, and the last item has been removed, throws the argument that was given to fail as an exception.

See method poll for a non-blocking version that won't throw exceptions.

## 62.1.3 method poll

Defined as:

    method poll(Channel:D:)

Usage:

    CHANNEL.poll

Receives and removes an item from the channel. If no item is present, returns Nil instead of waiting.

See method receive for a blocking version that properly responds to channel closing and failure.

## 62.1.4 method close

Defined as:

    method close(Channel:D:)

Usage:

    CHANNEL.close

Close the Channel, normally. This makes subsequent send calls die with X::Channel::SendOnClosed. Subsequent calls of .receive may still drain any remaining items that were previously sent, but if the queue is empty, will throw an X::Channel::ReceiveOnClosed exception. A Seq produced by an @() or by the .list method will not terminate until this has been done.

## 62.1.5 method list

Defined as:

    method list(Channel:D:) returns List:D

Usage:

    CHANNEL.list

Returns a Seq which will iterate items in the queue and removes each item from the queue as it iterates. This can only terminate once the close method has been called.

## 62.1.6 method closed

Defined as:

    method closed(Channel:D:) returns Promise:D

Usage:

    CHANNEL.closed

Returns a promise that will be kept once the channel is closed by a call to method close.

## 62.1.7 method fail

Defined as:

    method fail(Channel:D: $error)

Usage:

    CHANNEL.fail

Closes the Channel (that is, makes subsequent send calls die), and enqueues the error to be thrown as the final element in the channel. Method receive will throw that error as an exception. Does nothing if the channel has already been closed or .fail has already been called on it.

## 62.1.8 method Supply

Defined as:

    method Supply(Channel:D:)

Usage:

    CHANNEL.Supply

This returns an on-demand Supply that emits a value for every value received on the Channel. done will be called on the Supply when the Channel is closed.

Multiple calls to this method produce multiple instances of Supply, which compete over the values from the Channel.

## 62.1.9 sub await

Defined as:

    multi sub await(Channel:D)
    multi sub await(*@)

Usage:

    await(CHANNEL)
    await(CHANNELS)

Waits until all of one or more channels has a value available, and returns those values (it calls .receive on the channel). Also works with promises.

# 63 class Code

Code object

    class Code is Any does Callable { ... }

Code is the ultimate base class of all code objects in Perl 6. It exposes functionality that all code objects have. While thunks are directly of type Code, most code objects (such as those resulting from blocks, subroutines or methods) will be of some subclass of Code.

# 63.1 Methods

## 63.1.1 method ACCEPTS

    multi method ACCEPTS(Code:D: Mu $topic)

Usually calls the code object and passes $topic as an argument. However, when called on a code object that takes no arguments, the code object is invoked with no arguments and $topic is dropped. The result of the call is returned.

## 63.1.2 method arity

Defined as:

    method arity(Code:D:) returns Int:D

Usage:

    CODE.arity

Returns the minimum number of positional arguments that must be passed in order to call the code object. Any optional or slurpy parameters in the code object's Signature do not contribute, nor do named parameters.

    sub argless() { }
    sub args($a, $b?) { }
    sub slurpy($a, $b, *@c) { }
    say &amp;argless.arity;             # 0
    say &amp;args.arity;                # 1
    say &amp;slurpy.arity;              # 2

## 63.1.3 method count

Defined as:

    method count(Code:D:) returns Real:D

Usage:

    CODE.count

Returns the maximum number of positional arguments that may be passed when calling the code object. For code objects that can accept any number of positional arguments (that is, they have a slurpy parameter), count will return Inf. Named parameters do not contribute.

    sub argless() { }
    sub args($a, $b?) { }
    sub slurpy($a, $b, *@c) { }
    say &amp;argless.count;             # 0
    say &amp;args.count;                # 2
    say &amp;slurpy.count;              # Inf

## 63.1.4 method signature

Defined as:

    multi method signature(Code:D:) returns Signature:D

Usage:

    CODE.signature

Returns the Signature object for this code object, which describes its parameters.

## 63.1.5 method Str

Defined as:

    multi method Str(Code:D:) returns Str:D

Usage:

    CODE.Str

Will produce a warning. Use .perl or .gist instead.

    sub marine() { }
    say ~&amp;marine;   # marine

## 63.1.6 method file

Defined as:

    method file(Code:D:) returns Str:D

Usage:

    CODE.file

Returns the name of the file in which the code object was declared.

    say &amp;infix:&lt;+>.file;

## 63.1.7 method line

Defined as

    method line(Code:D:) returns Int:D

Usage:

    CODE.line

Returns the line number in which the code object was declared.

    say &amp;infix:&lt;+>.line;

# 64 class Complex

Complex number

    class Complex is Cool does Numeric { ... }

Represents a number in the complex plane.

Complex objects are immutable.

# 64.1 Operators

## 64.1.1 postfix i

Adding a trailing i to a number literal makes it a Complex, for example:

    2i;     # same as Complex.new(0, 2);
    1-2e3i; # same as Complex.new(1, -2e3);

# 64.2 Methods

## 64.2.1 method new

Defined as:

    proto method new(*@, *%) {*} returns Complex:D
    multi method new(Real $re, Real $im) returns Complex:D

Usage:

    $complex = Complex.new(REAL, IMAGINARY)

Creates a new Complex object from real and imaginary parts.

## 64.2.2 method re

Defined as:

    method re(Complex:D:) returns Real:D

Usage:

    COMPLEX.re

Returns the real part of the complex number.

    say (3+5i).re;    # 3

## 64.2.3 method im

Defined as:

    method im(Complex:D:) returns Real:D

Usage:

    COMPLEX.im

Returns the imaginary part of the complex number.

    say (3+5i).im;    # 5

## 64.2.4 method reals

Defined as:

    method reals(Complex:D:) returns Positional:D

Usage:

    COMPLEX.reals

Returns a two-element list containing the real and imaginary parts for this value.

    say (3+5i).reals;    # (3 5)

## 64.2.5 method isNaN

Defined as:

    method isNaN(Complex:D:) returns Bool:D

Usage:

    COMPLEX.isNaN

Returns true if the real or imaginary part is NaN (not a number).

## 64.2.6 method polar

Defined as:

    method polar(Complex:D:) returns Positional:D

Usage:

    COMPLEX.polar

Returns a two-element list of the polar coordinates for this value, i.e. magnitude and angle in radians.

## 64.2.7 method floor

Defined as:

    method floor(Complex:D:) returns Complex:D

Usage:

    COMPLEX.floor

Returns self.re.floor + self.im.floor. That is, each of the real and imaginary parts is rounded to the highest integer not greater than the value of that part.

    say (1.2-3.8i).floor;           # 1-4i

## 64.2.8 method ceiling

Defined as:

    method ceiling(Complex:D:) returns Complex:D

Usage:

    COMPLEX.ceiling

Returns self.re.ceiling + self.im.ceiling. That is, each of the real and imaginary parts is rounded to the lowest integer not less than the value of that part.

    say (1.2-3.8i).ceiling;         # 2-3i

## 64.2.9 method round

Defined as:

    multi method round(Complex:D:) returns Complex:D
    multi method round(Complex:D: Real() $scale) returns Complex:D

Usage:

    COMPLEX.round
    COMPLEX.round($scale)

With no arguments, rounds both the real and imaginary parts to the nearest integer and returns a new Complex number. If $scale is given, rounds both parts of the invocant to the nearest multiple of $scale. Uses the same algorithm as Real.round on each part of the number.

    say (1.2-3.8i).round;           # 1-4i
    say (1.256-3.875i).round(0.1);  # 1.3-3.9i

## 64.2.10 method truncate

Defined as:

    method truncate(Complex:D:) returns Complex:D

Usage:

    COMPLEX.truncate

Removes the fractional part of both the real and imaginary parts of the number, using Real.truncate, and returns the result as a new Complex.

    say (1.2-3.8i).truncate;        # 1-3i

## 64.2.11 method abs

Defined as:

    method abs(Complex:D:) returns Num:D
    multi sub abs(Complex:D $z) returns Num:D

Usage:

    COMPLEX.abs
    abs COMPLEX

Returns the absolute value of the invocant (or the argument in sub form). For a given complex number $z the absolute value |$z| is defined as sqrt($z.re * $z.re + $z.im * $z.im).

    say (3+4i).abs;                 # sqrt(3*3 + 4*4) == 5

## 64.2.12 method conj

Defined as:

    method conj(Complex:D:) returns Complex:D

Usage:

    COMPLEX.conj

Returns the complex conjugate of the invocant (that is, the number with the sign of the imaginary part negated).

    say (1-4i).conj;                # 1+4i

## 64.2.13 method gist

Defined as:

    method gist(Complex:D:) returns Str:D

Usage:

    COMPLEX.gist

Returns a string representation of the form "1+2i", without internal spaces. (Str coercion also returns this.)

    say (1-4i).gist;                # 1-4i

## 64.2.14 method perl

Defined as:

    method perl(Complex:D:) returns Str:D

Usage:

    COMPLEX.perl

Returns a string representation corresponding to the unambiguous val()-based representation of complex literals, of the form "<1+2i>", without internal spaces, and including the angles that keep the + from being treated as a normal addition operator.

    say (1-3i).perl;                # &lt;1-3i>

# 65 class ComplexStr

Dual Value Complex number and String

    class ComplexStr is Complex is Str

The dual value types (often referred to as allomorphs) allow for the representation of a value as both a string and a numeric type, typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some quoting constructs:

    my $f = &lt;42+0i>; say $f.WHAT; # (ComplexStr)

A ComplexStr can be used interchangeably where one might use a Str or a Complex :

    my $f = &lt;42+0i>;
    my $i = $f + 0.1;
    my $s = $f ~ " and a bit more";

# 65.1 Methods

## 65.1.1 method new

    method new(Complex $i, Str $s)

The constructor requires both the Complex and the Str value, when constructing one directly the values can be whatever is required:

    my $f = ComplexStr.new(42+0i, "forty two (but complicated)");
    say +$f; # -> 42+0i
    say ~$f; # -> "forty two (but complicated)"

## 65.1.2 method Numeric

    method Numeric

The numeric coercion is applied when the ComplexStr is used in a numeric context, such as a numeric comparison or smart match against a numeric value. It will return the Complex value.

## 65.1.3 method Complex

    method Complex

Returns the Complex value of the ComplexStr.

## 65.1.4 method Str

Returns the string value of the ComplexStr.

# 65.2 Operators

## 65.2.1 infix cmp

    multi sub infix:&lt;cmp>(ComplexStr:D $a, ComplexStr:D $b)

Compare two ComplexStr objects. The comparison is done on the Complex value first and then on the Str value. If you want to compare in a different order then you would coerce to the Complex or Str values first:

    my $f = ComplexStr.new(42+0i, "smaller");
    my $g = ComplexStr.new(43+0i, "larger");
    say $f cmp $g;          # Less
    say $f.Str cmp $g.Str;  # More

# 66 class Cool

Value that can be treated as a string or number interchangeably

    class Cool is Any { }

Cool, also known as the Convenient OO Loop, is a base class for strings, numbers and other built-in classes that you are supposed to use mostly interchangeably.

Methods in Cool coerce the invocant to a more specific type, and then call the same method on that type. For example both Int and Str inherit from Cool, and calling method substr on an Int converts the integer to Str first.

    123.substr(1, 1);   # '2', same as 123.Str.substr(1, 1)

The following built-in types inherit from Cool: Array Bool Complex Cool Duration Map FatRat Hash Instant Int List Match Nil Num Range Seq Stash Str

The following table summarizes the methods that Cool provides, and what type they coerce to:

method | coercion type
--- | ---
abs | Numeric
conj | Numeric
sqrt | Numeric
sign | Real
rand | Numeric
sin | Numeric
asin | Numeric
cos | Numeric
acos | Numeric
tan | Numeric
tanh | Numeric
atan | Numeric
atan2 | Numeric
atanh | Numeric
sec | Numeric
asec | Numeric
cosec | Numeric
acosec | Numeric
cotan | Numeric
cotanh | Numeric
acotan | Numeric
sinh | Numeric
asinh | Numeric
cosh | Numeric
acosh | Numeric
sech | Numeric
asech | Numeric
cosech | Numeric
acosech | Numeric
acotanh | Numeric
cis | Numeric
log | Numeric
exp | Numeric
roots | Numeric
log10 | Numeric
unpolar | Numeric
round | Numeric
floor | Numeric
ceiling | Numeric
truncate | Numeric
chr | Int
ord | Str
chars | Str
fmt | Str
uniname | Str
uninames | Seq
unival | Str
univals | Str
uniprop | Str
uniprop-int | Str
uniprop-str | Str
uniprop-bool | Str
unimatch | Str
uc | Str
lc | Str
fc | Str
flip | Str
trans | Str
index | Str
rindex | Str
ords | Str
split | Str
match | Str
comb | Str
subst | Str
sprintf | Str
printf | Str
samecase | Str
trim | Str
trim-leading | Str
trim-trailing | Str
EVAL | Str
chomp | Str
chop | Str
codes | Str

# 66.1 Methods

## 66.1.1 routine abs

Defined as:

    sub abs(Numeric() $x)
    method abs()

Usage:

    abs NUMERIC
    NUMERIC.abs

Coerces the invocant (or in the sub form, the argument) to Numeric and returns the absolute value (that is, a non-negative number).

    say (-2).abs;       # 2
    say abs "6+8i";     # 10

## 66.1.2 method conj

Defined as:

    method conj()

Usage:

    NUMERIC.conj

Coerces the invocant to Numeric and returns the complex conjugate (that is, the number with the sign of the imaginary part negated).

    say (1+2i).conj;        # 1-2i

## 66.1.3 routine sqrt

Defined as:

    sub sqrt(Numeric(Cool) $x)
    method sqrt()

Usage:

    sqrt NUMERIC
    NUMERIC.sqrt

Coerces the invocant to Numeric (or in the sub form, the argument) and returns the square root, that is, a non-negative number that, when multiplied with itself, produces the original number.

    say 4.sqrt;             # 2
    say sqrt(2);            # 1.4142135623731

## 66.1.4 method sign

Defined as:

    method sign()

Usage:

    NUMERIC.sign

Coerces the invocant to Numeric and returns its sign, that is, 0 if the number is 0, 1 for positive and -1 for negative values.

    say 6.sign;             # 1
    say (-6).sign;          # -1
    say "0".sign;           # 0

## 66.1.5 method rand

Defined as:

    method rand()

Usage: NUMERIC.rand

Coerces the invocant to Num and returns a pseudo-random value between zero and the number.

    say 1e5.rand;           # 33128.495184283

## 66.1.6 routine sin

Defined as:

    sub sin(Numeric(Cool))
    method sin()

Usage:

    sin NUMERIC
    NUMERIC.sin

Coerces the invocant (or in the sub form, the argument) to Numeric, interprets it as radians, returns its sine.

    say sin(0);             # 0
    say sin(pi/4);          # 0.707106781186547
    say sin(pi/2);          # 1

Note that Perl 6 is no computer algebra system, so sin(pi) typically does not produce an exact 0, but rather a very small floating-point number.

## 66.1.7 routine asin

Defined as:

    sub asin(Numeric(Cool))
    method asin()

Usage:

    asin NUMERIC
    NUMERIC.asin

Coerces the invocant (or in the sub form, the argument) to Numeric, and returns its arc-sine in radians.

    say 0.1.asin;               # 0.10016742116156

## 66.1.8 routine cos

Defined as:

    sub cos(Numeric(Cool))
    method cos()

Usage:

    cos NUMERIC
    NUMERIC.cos

Coerces the invocant (or in sub form, the argument) to Numeric, interprets it as radians, returns its cosine.

    say 0.cos;                  # 1
    say pi.cos;                 # -1
    say cos(pi/2);              # 6.12323399573677e-17

## 66.1.9 routine acos

Defined as:

    sub acos(Numeric(Cool))
    method acos()

Usage:

    acos NUMERIC
    NUMERIC.acos

Coerces the invocant (or in sub form, the argument) to Numeric, and returns its arc-cosine in radians.

## 66.1.10 routine tan

Defined as:

    sub tan(Numeric(Cool))
    method tan()

Usage:

    tan NUMERIC
    NUMERIC.tan

Coerces the invocant (or in sub form, the argument) to Numeric, interprets it as radians, returns its tangent.

## 66.1.11 routine atan

Defined as:

    sub atan(Numeric(Cool))
    method atan()

Usage:

    atan NUMERIC
    NUMERIC.atan

Coerces the invocant (or in sub form, the argument) to Numeric, and returns its arc-tangent in radians.

## 66.1.12 routine atan2

Defined as:

    sub atan2(Numeric() $x, Numeric() $y = 1e0)
    method atan2($y = 1e0)

Usage:

    atan2 NUMERIC, NUMERIC?
    NUMERIC.atan2(NUMERIC?)

Coerces the arguments (including the invocant in the method form) to Numeric, and returns their two-argument arc-tangent in radians.

## 66.1.13 method sec

Defined as:

    sub sec(Numeric(Cool))
    method sec()

Usage:

    sec NUMERIC
    NUMERIC.sec

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its secant, that is, the reciprocal of its cosine.

## 66.1.14 routine asec

Defined as:

    sub asec(Numeric(Cool))
    method asec()

Usage:

    asec NUMERIC
    NUMERIC.asec

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-secant in radians.

## 66.1.15 routine cosec

Defined as:

    sub cosec(Numeric(Cool))
    method cosec()

Usage:

    cosec NUMERIC
    NUMERIC.cosec

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its cosecant, that is, the reciprocal of its sine.

## 66.1.16 routine acosec

Defined as:

    sub acosec(Numeric(Cool))
    method acosec()

Usage:

    acosec NUMERIC
    NUMERIC.acosec

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-cosecant in radians.

## 66.1.17 routine cotan

Defined as:

    sub cotan(Numeric(Cool))
    method cotan()

Usage:

    cotan NUMERIC
    NUMERIC.cotan

Coerces the invocant (or in sub form, its argument) to Numeric, interprets it as radians, returns its cotangent, that is, the reciprocal of its tangent.

## 66.1.18 routine acotan

Defined as:

    sub acotan(Numeric(Cool))
    method acotan()

Usage:

    acotan NUMERIC
    NUMERIC.acotan

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its arc-cotangent in radians.

## 66.1.19 routine sinh

Defined as:

    sub sinh(Numeric(Cool))
    method sinh()

Usage:

    sinh NUMERIC
    NUMERIC.sinh

Coerces the invocant (or in method form, its argument) to Numeric, and returns its Sine hyperbolicus.

## 66.1.20 routine asinh

Defined as:

    sub asinh(Numeric(Cool))
    method asinh()

Usage:

    asinh NUMERIC
    NUMERIC.asinh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse Sine hyperbolicus.

## 66.1.21 routine cosh

Defined as:

    sub cosh(Numeric(Cool))
    method cosh()

Usage:

    cosh NUMERIC
    NUMERIC.cosh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Cosine hyperbolicus.

## 66.1.22 routine acosh

Defined as:

    sub acosh(Numeric(Cool))
    method acosh()

Usage:

    acosh NUMERIC
    NUMERIC.acosh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse Cosine hyperbolicus.

## 66.1.23 routine tanh

Defined as:

    sub tanh(Numeric(Cool))
    method tanh()

Usage:

    tanh NUMERIC
    NUMERIC.tanh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Tangent hyperbolicus.

## 66.1.24 routine atanh

Defined as:

    sub atanh(Numeric(Cool))
    method atanh()

Usage:

    atanh NUMERIC
    NUMERIC.atanh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse tangent hyperbolicus.

## 66.1.25 routine sech

Defined as:

    sub sech(Numeric(Cool))
    method sech()

Usage:

    sech NUMERIC
    NUMERIC.sech

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Secant hyperbolicus.

    say 0.sech;                  # 1

## 66.1.26 routine asech

Defined as:

    sub asech(Numeric(Cool))
    method asech()

Usage:

    asech NUMERIC
    NUMERIC.asech

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic secant.

    say 0.8.asech;                  # 0.693147180559945

## 66.1.27 routine cosech

Defined as:

    sub cosech(Numeric(Cool))
    method cosech()

Usage:

    cosech NUMERIC
    NUMERIC.cosech

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Hyperbolic cosecant.

    say cosech(pi/2);                # 0.434537208094696

## 66.1.28 routine acosech

Defined as:

    sub acosech(Numeric(Cool))
    method acosech()

Usage:

    acosech NUMERIC
    NUMERIC.acosech

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic cosecant.

    say acosech(4.5);                  # 0.220432720979802

## 66.1.29 routine cotanh

Defined as:

    sub cotanh(Numeric(Cool))
    method cotanh()

Usage:

    cotanh NUMERIC
    NUMERIC.cotanh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Hyperbolic cotangent.

    say cotanh(pi);                   # 1.00374187319732

## 66.1.30 routine acotanh

Defined as:

    sub acotanh(Numeric(Cool))
    method acotanh()

Usage:

    acotanh NUMERIC
    NUMERIC.acotanh

Coerces the invocant (or in sub form, its argument) to Numeric, and returns its Inverse hyperbolic cotangent.

    say acotanh(2.5);                  # 0.423648930193602

## 66.1.31 routine cis

Defined as:

    sub cis(Numeric(Cool))
    method cis()

Usage:

    cis NUMERIC
    NUMERIC.cis

Coerces the invocant (or in sub form, its argument) to Numeric, and returns cos(argument) + i*sin(argument).

    say cis(pi/4);                  # 0.707106781186548+0.707106781186547i

## 66.1.32 routine log

Defined as:

    multi sub log(Numeric(Cool) $number, Numeric(Cool) $base?)
    multi method log(Cool:D: Cool:D $base?)

Usage:

    log NUMERIC, NUMERIC?
    NUMERIC.log(NUMERIC?)

Coerces the arguments (including the invocant in the method form) to Numeric, and returns its Logarithm to base $base, or to base e (Euler's Number) if no base was supplied (Natural logarithm.

    say (e*e).log;                      # 2

## 66.1.33 routine log10

Defined as:

    multi sub log10(Cool(Numeric))
    multi method log10()

Usage:

    log10 NUMERIC
    NUMERIC.log10

Coerces the invocant (or in the sub form, the invocant) to Numeric, and returns its Logarithm to base 10, that is, a number that approximately produces the original number when raised to the power of 10.

    say log10(1001);                    # 3.00043407747932

## 66.1.34 method exp

Defined as:

    multi sub exp(Cool:D $pow, Cool:D $base?)
    multi method exp(Cool:D: Cool:D $base?)

Usage:

    exp NUMERIC, NUMERIC?
    NUMERIC.exp(NUMERIC?)

Coerces the arguments (including the invocant in the method from) to Numeric, and returns $base raised to the power of the first number. If no $base is supplied, e (Euler's Number) is used.

    say 0.exp;      # 1
    say 1.exp;      # 2.71828182845905
    say 10.exp;     # 22026.4657948067

## 66.1.35 method unpolar

Defined as:

    method unpolar(Numeric(Cool))

Usage:

    unpolar NUMERIC, NUMERIC
    NUMERIC.unpolar(NUMERIC)

Coerces the arguments (including the invocant in the method form) to Numeric, and returns a complex number from the given polar coordinates. The invocant (or the first argument in sub form) is the magnitude while the argument (i.e. the second argument in sub form) is the angle. The angle is assumed to be in radians.

    say sqrt(2).unpolar(pi/4);      # 1+1i

## 66.1.36 routine round

Defined as:

    multi sub round(Numeric(Cool))
    multi method round(Cool:D: $unit = 1)

Usage:

    round NUMERIC, NUMERIC?
    NUMERIC.round(NUMERIC?)

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it to the unit of $unit. If $unit is 1, rounds to the nearest integer.

    say 1.7.round;          # 2
    say 1.07.round(0.1);    # 1.1
    say 21.round(10);       # 20

## 66.1.37 routine floor

Defined as:

    multi sub floor(Numeric(Cool))
    multi method floor

Usage:

    floor NUMERIC
    NUMERIC.floor

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it downwards to the nearest integer.

    say "1.99".floor;       # 1
    say "-1.9".floor;       # -2
    say 0.floor;            # 0

## 66.1.38 routine ceiling

Defined as:

    multi sub ceiling(Numeric(Cool))
    multi method ceiling

Usage:

    ceiling NUMERIC
    NUMERIC.ceiling

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it upwards to the nearest integer.

    say "1".ceiling;        # 1
    say "-0.9".ceiling;     # 0
    say "42.1".ceiling;     # 43

## 66.1.39 routine truncate

Defined as:

    multi sub truncate(Numeric(Cool))
    multi method truncate()

Usage:

    truncate NUMERIC
    NUMERIC.truncate

Coerces the invocant (or in sub form, its argument) to Numeric, and rounds it towards zero.

    say 1.2.truncate        # 1
    say truncate -1.2;      # -1

## 66.1.40 routine ord

Defined as:

    sub ord(Str(Cool))
    method ord()

Usage:

    ord STRING
    STRING.ord

Coerces the invocant (or in sub form, its argument) to Str, and returns the Unicode code point number of the first code point.

    say 'a'.ord;            # 97

The inverse operation is chr.

Mnemonic: returns an ordinal number

## 66.1.41 routine chr

Defined as:

    sub chr(Int(Cool))
    method chr()

Usage:

    chr INTEGER
    INTEGER.chr

Coerces the invocant (or in sub form, its argument) to Int, interprets it as a Unicode code points, and returns a string made of that code point.

    say '65'.chr;       # A

The inverse operation is ord.

Mnemonic: turns an integer into a character.

## 66.1.42 routine chars

Defined as:

    sub chars(Str(Cool))
    method chars()

Usage:

    chars STRING
    STRING.chars

Coerces the invocant (or in sub form, its argument) to Str, and returns the number of characters in the string. Please note that on the JVM, you currently get codepoints instead of graphemes.

    say 'møp'.chars;    # 3

## 66.1.43 routine codes

Defined as:

    sub codes(Str(Cool))
    method codes()

Usage:

    codes STRING
    STRING.codes

Coerces the invocant (or in sub form, its argument) to Str, and returns the number of Unicode code points.

    say 'møp'.codes;    # 3

## 66.1.44 routine flip

Defined as:

    sub flip(Str(Cool))
    method flip()

Usage:

    flip STRING
    STRING.flip

Coerces the invocant (or in sub form, its argument) to Str, and returns a reversed version.

    say 421.flip;       # 124

## 66.1.45 routine trim

Defined as:

    sub trim(Str(Cool))
    method trim()

Usage:

    trim STRING
    STRING.trim

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with both leading and trailing whitespace stripped.

    my $stripped = '  abc '.trim;
    say "&lt;$stripped>";          # &lt;abc>

## 66.1.46 routine trim-leading

Defined as:

    sub trim-leading(Str(Cool))
    method trim-leading()

Usage:

    trim-leading STRING
    STRING.trim-leading

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with leading whitespace stripped.

    my $stripped = '  abc '.trim-leading;
    say "&lt;$stripped>";          # &lt;abc >

## 66.1.47 routine trim-trailing

Defined as:

    sub trim-trailing(Str(Cool))
    method trim-trailing()

Usage:

    trim-trailing STRING
    STRING.trim-trailing

Coerces the invocant (or in sub form, its argument) to Str, and returns the string with trailing whitespace stripped.

    my $stripped = '  abc '.trim-trailing;
    say "&lt;$stripped>";          # &lt;  abc>

## 66.1.48 routine lc

Defined as:

    sub lc(Str(Cool))
    method lc()

Usage:

    lc STRING
    STRING.lc

Coerces the invocant (or in sub form, its argument) to Str, and returns it case-folded to lower case.

    say "ABC".lc;       # abc

## 66.1.49 routine uc

Defined as:

    sub uc(Str(Cool))
    method uc()

Usage:

    uc STRING
    STRING.uc

Coerces the invocant (or in sub form, its argument) to Str, and returns it case-folded to upper case (capital letters).

    say "Abc".uc;       # ABC

## 66.1.50 routine tc

Defined as:

    sub tc(Str(Cool))
    method tc()

Usage:

    tc STRING
    STRING.tc

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the first letter case-folded to title case (or where not available, upper case).

    say "abC".tc;       # AbC

## 66.1.51 routine tclc

Defined as:

    sub tclc(Str(Cool))
    method tclc()

Usage:

    tclc STRING
    STRING.tclc

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the first letter case-folded to title case (or where not available, upper case), and the rest of the string case-folded to lower case..

    say 'abC'.tclc;     # Abc

## 66.1.52 routine wordcase

Defined as:

    sub wordcase(Str(Cool) $input, :&amp;filter = &amp;tclc, Mu :$where = True)
    method wordcase(:&amp;filter = &amp;tclc, Mu :$where = True)

Usage:

    wordcase STRING, FILTER?, WHERE?
    STRING.wordcase(FILTER?, WHERE?)

Coerces the invocant (or in sub form, the first argument) to Str, and filters each word that smart-matches against $where through the &filter. With the default filter (first character to upper case, rest to lower) and matcher (which accepts everything), this title-cases each word:

    say "perl 6 programming".wordcase;      # Perl 6 Programming

With a matcher:

    say "have fun working on perl".wordcase(:where({ .chars > 3 }));
                                            # Have fun Working on Perl

With a customer filter too:

    say "have fun working on perl".wordcase(:filter(&amp;uc), :where({ .chars > 3 }));
                                            # HAVE fun WORKING on PERL

## 66.1.53 routine samecase

Defined as:

    sub samecase(Cool $string, Cool $pattern)
    method samecase(Cool:D: Cool $pattern)

Usage:

    samecase STRING, PATTERN
    STRING.samecase(PATTERN)

Coerces the invocant (or in sub form, the first argument) to Str, and returns a copy of $string with case information for each individual character changed according to $pattern. (The pattern string can contain three types of characters, i.e. uppercase, lowercase and caseless. For a given character in $pattern its case information determines the case of the corresponding character in the result.) If $string is longer than $pattern, the case information from the last character of $pattern is applied to the remaining characters of $string.

    say "perL 6".samecase("A__a__"); # Perl 6
    say "pERL 6".samecase("Ab");     # Perl 6

## 66.1.54 routine uniname

Defined as:

    sub uniname(Str(Cool) returns Str
    method uniname() returns Str

Usage:

    # Camelia in Unicode
    say ‘»ö«’.comb».uniname;
    # «("RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK",
        "LATIN SMALL LETTER O WITH DIAERESIS", "LEFT-POINTING DOUBLE ANGLE QUOTATION MARK")␤»

    # Find the char with the longest Unicode name.
    say (0..0x1FFFF).sort(*.uniname.chars)[*-1].chr.uniname;
    # «ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH HAMZA ABOVE WITH ALEF MAKSURA INITIAL FORM␤»

Interprets the invocant / first argument as a Str, and returns the Unicode codepoint name of the first character. To convert a whole string use uninames.

## 66.1.55 routine uninames

Defined as:

    sub uninames(Str:D)
    method uninames()

Usage:

    dd ‘»ö«’.comb».uniname;
    # «("RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK",
        "LATIN SMALL LETTER O WITH DIAERESIS",
        "LEFT-POINTING DOUBLE ANGLE QUOTATION MARK").Seq␤»

Returns of a Seq of unicode names for the Str provided.

## 66.1.56 routine chop

Defined as:

    sub chop(Str(Cool))
    method chop()

Usage:

    chop STRING
    STRING.chop

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the last character removed.

    say 'perl'.chop;                        # per

## 66.1.57 routine chomp

Defined as:

    sub chomp(Str(Cool))
    method chomp()

Usage:

    chomp STRING
    STRING.chomp

Coerces the invocant (or in sub form, its argument) to Str, and returns it with the last character removed, if it is a logical newline.

    say 'ab'.chomp.chars;                   # 2
    say "a\n".chomp.chars;                  # 1

## 66.1.58 routine substr

Defined as:

    sub substr(Str(Cool) $str, $from, $chars?)
    method substr($from, $chars?)

Usage:

    substr(STRING, FROM, CHARS?)
    STRING.substr(FROM, CHARS?)

Coerces the invocant (or in the sub form, the first argument) to Str, and returns the string starting from offset $from. If $chars is supplied, at most $chars characters are returned.

    say 'zenith'.substr(2);         # nith
    say 'zenith'.substr(0, 3);      # zen

    # works on non-strings too:
    say 20151224.substr(6);         # 24

    # sub form:
    say substr "zenith", 0, 3;      # zen

If the $from parameter is a Callable, it is called with the number of chars in the string as argument. This allows easy indexing relative to the end:

    say 20151224.substr(*-2);       # 24

## 66.1.59 routine ords

Defined as:

    sub ords(Str(Cool) $str)
    method ords()

Usage:

    ords(STRING)
    STRING.ords

Coerces the invocant (or in the sub form, the first argument) to Str, and returns a list of Unicode codepoints for each character.

    say "Perl 6".ords;              # 80 101 114 108 32 54
    say ords 10;                    # 49 48

This is the list-returning version of ord. The inverse operation in chrs.

## 66.1.60 routine chrs

Defined as:

    sub chrs(*@codepoints) return Str:D
    method chrs()

Usage:

    chrs LIST
    LIST.chrs

Coerces the invocant (or in the sub form, the argument list) to a list of integers, and returns the string created by interpreting each integer as a Unicode codepoint, and joining the characters.

    say &lt;80 101 114 108 32 54>.chrs;    # Perl 6

This is the list-input version of chr. The inverse operation is ords.

## 66.1.61 routine split

Defined as:

    multi sub    split(  Str:D $delimiter, Str(Cool) $input, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)
    multi sub    split(Regex:D $delimiter, Str(Cool) $input, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)
    multi method split(  Str:D $delimiter, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)
    multi method split(Regex:D $delimiter, $limit = Inf, :$k, :$v, :$kv, :$p, :$skip-empty)

Usage:

    split DELIMITER, STRING, LIMIT?, [:k | :v | :kv | :p]?, :skip-empty?
    split /PATTERN/, STRING, LIMIT?, [:k | :v | :kv | :p]?, :skip-empty?
    STRING.split(DELIMITER, LIMIT?,  [:k | :v | :kv | :p]?, :skip-empty?)
    STRING.split(/PATTERN/, LIMIT?,  [:k | :v | :kv | :p]?, :skip-empty?)

Coerces the invocant (or in the sub form, the second argument) to Str, and splits it into pieces based on delimiters found in the string.

If $delimiter is a string, it is searched for literally and not treated as a regex.

    say split(';', "a;b;c").perl;          # ("a", "b", "c").list
    say split(';', "a;b;c", 2).perl;       # ("a", "b;c").list

    say split(';', "a;b;c,d").perl;        # ("a", "b", "c,d").list
    say split(/\;/, "a;b;c,d").perl;       # ("a", "b", "c,d").list
    say split(/&lt;[;,]>/, "a;b;c,d").perl;   # ("a", "b", "c", "d").list

By default, split omits the matches, and returns a list of only those parts of the string that did not match. Specifying one of the :k, :v, :kv, :p adverbs changes that. Think of the matches as a list that is interleaved with the non-matching parts. :v interleaves the values of that list: s say 'abc'.split(/b/, :v); # (a ｢b｣ c)

:k interleaves the keys, that is, the indexes:

    say 'abc'.split(/b/, :k);               # (a 0 c)

:kv adds both indexes and matches:

    say 'abc'.split(/b/, :kv);               # (a 0 ｢b｣ c)

You can only use one of the :k, :v, :kv, :p adverbs in a single call to split.

and :p adds them as Pairs:

    say 'abc'.split(/b/, :p)                # (a 0 => ｢b｣ c)

Note that unlike in Perl 5, empty chunks are not removed from the result list. For that behavior, use the `:skip-empty` named argument:

    say ("f,,b,c,d".split: /","/             ).perl  # ("f", "", "b", "c", "d")
    say ("f,,b,c,d".split: /","/, :skip-empty).perl  # ("f", "b", "c", "d")

See also: comb.

## 66.1.62 routine lines

Defined as:

    sub lines(Str(Cool))
    method lines()

Usage:

    lines STRING
    STRING.lines

Coerces the invocant (and in sub form, the argument) to Str, decomposes it into lines (with the newline characters stripped), and returns the list of lines.

    say lines("a\nb\n").join('|');          # a|b
    say "some\nmore\nlines".lines.elems;    # 3

This method can be used as part of an IO::Path to process a file line-by-line, since IO::Path objects inherit from Cool, e.g.:

    for 'huge-csv'.IO.lines -> $line {
             # Do something with $line
     }

     # or if you'll be processing later
     my @lines = 'huge-csv'.IO.lines;

Without any arguments, sub lines operates on $*ARGFILES, which defaults to $*IN in the absence of any filenames.

To modify values in place use is copy to force a writeable container.

    for $*IN.lines -> $_ is copy { s/(\w+)/{$0 ~ $0}/; .say }

## 66.1.63 method words

Defined as:

    method words(Int() $limit)

Usage:

    INTEGER.words(LIMIT?)

Coerces the invocant to Str, and returns a list of words that make up the string (and if $limit is supplied, only the first $limit words).

    say 'The quick brown fox'.words.join('|');      # The|quick|brown|fox
    say 'The quick brown fox'.words(2).join('|');   # The|quick

Only whitespace counts as word boundaries

    say "isn't, can't".words.join('|');             # isn't,|can't

## 66.1.64 routine comb

Defined as:

    multi sub comb(Regex $matcher, Str(Cool) $input, $limit = *) returns List:D
    multi method comb(Regex $matcher, $limit = *) returns List:D

Usage:

    comb /PATTERN/, STRING, LIMIT?
    STRING.comb(/PATTERN/, LIMIT?)

Returns all (or if supplied, at most $limit) matches of the invocant (method form) or the second argument (sub form) against the Regex as a list of strings.

    say "6 or 12".comb(/\d+/).join(", ");           # 6, 12

## 66.1.65 method contains

    multi method contains(Cool:D: Str(Cool) $needle, Cool $start?) returns True:D

Returns True if the invocant contains the $needle at any position within the string. If $start is provided skip as many characters.

    say "Hello, World".contains('hello');      # False
    say "Hello, World".contains(',');          # True

## 66.1.66 routine index

Defined as:

    multi sub    index(Str(Cool) $s, Str:D $needle, Int(Cool) $startpos = 0) returns Int
    multi method index(Str(Cool) $needle, Int(Cool) $startpos = 0) returns Int

Usage:

    index STRING, NEEDLE, STARTPOS?
    STRING.comb(NEEDLE, STARTPOS?)

Coerces the first two arguments (in method form, also counting the invocant) to Str, and searches for $needle in the string starting from $startpos. It returns the offset into the string where $needle was found, and an undefined value if it was not found.

See the documentation in type Str for examples.

## 66.1.67 routine rindex

Defined as:

    multi sub    rindex(Str(Cool) $haystack, Str(Cool) $needle, Int(Cool) $startpos = $haystack.chars)
    multi method rindex(Str(Cool) $haystack: Str(Cool) $needle, Int(Cool) $startpos = $haystack.chars)

Usage:

    rindex STRING, NEEDLE, STARTPOS?
    STRING.rindex(NEEDLE, STARTPOS?)

Coerces the first two arguments (including the invocant in method form) to Str and $startpos to Int, and returns the last position of $needle in $haystack not after $startpos. Returns an undefined value if $needle wasn't found.

See the documentation in type Str for examples.

## 66.1.68 method fmt

Defined as:

    method fmt($format = '%s') returns Str:D

Uses $format to return a formatted representation of the invocant.

For more information about formats strings, see sprintf.

    say 11.fmt('This Int equals %03d');               # This Int equals 011
    say '16'.fmt('Hexadecimal %x');                   # Hexadecimal 10

## 66.1.69 routine roots

Defined as:

    multi sub roots(Numeric(Cool) $x, Int(Cool) $n)
    multi method roots(Int(Cool) $n)

Usage:

    roots NUMERIC, INTEGER
    NUMERIC.roots(INTEGER)

Coerces the first argument (and in method form, the invocant) to Numeric and the second ($n) to Int, and produces a list of $n Complex $n-roots, which means numbers that, raised to the $nth power, approximately produce the original number.

For example

    my $original = 16;
     my @roots = $original.roots(4);
     say @roots;

     for @roots -> $r {
         say abs($r ** 4 - $original);
     }

produces this output:

    2+0i 1.22464679914735e-16+2i -2+2.44929359829471e-16i -3.67394039744206e-16-2i
     1.77635683940025e-15
     4.30267170434156e-15
     8.03651692704705e-15
     1.04441561648202e-14

## 66.1.70 method IO

Defined as:

    method IO() returns IO::Path:D

Usage:

    EXPR.IO

Coerces the invocant to IO::Path.

    .say for '.'.IO.dir;        # gives a directory listing

## 66.1.71 routine EVAL

Defined as:

    sub EVAL(Cool $code, :$lang = { ... })

Usage:

    EVAL "say 'hello'";

Coerces the invocant to Str.

This works as-is with a literal string parameter. If you have a more complex input, such as a variable or string with embedded code, you must enable the MONKEY-SEE-NO-EVAL pragma:

    use MONKEY-SEE-NO-EVAL;
    EVAL "say { 5 + 5 }";

Symbols in the current lexical scope are visible to code in an EVAL.

    my $answer = 42;
    EVAL 'say $answer;';    # says 42

However, since the set of symbols in a lexical scope is immutable after compile time, an EVAL can never introduce symbols into the surrounding scope.

    EVAL 'my $lives = 9'; say $lives;   # error, $lives not declared

Furthermore, the EVAL is evaluated in the current package:

    module M {
        EVAL 'our $answer = 42'
    }
    say $M::answer;         # says 42

And also the current language, meaning any added syntax is available:

    sub infix:&lt;mean>(*@a) is assoc&lt;list> {
        @a.sum / @a.elems
    }
    EVAL 'say 2 mean 6 mean 4';     # says 4

An EVAL statement evaluates to the result of the last statement:

    say EVAL 'say 1; 2 mean 6 mean 4';         # says 1, then says 4

EVAL is also a gateway for executing code in other languages:

    EVAL "use v5.20; say 'Hello from perl5!'", :lang&lt;Perl5>;

## 66.1.72 routine EVALFILE

Defined as:

    sub EVALFILE(Cool $filename, :$lang = { ... })

Usage:

    EVALFILE "foo.p6";

Slurps the specified file and evaluates it. Behaves the same way as EVAL with regard to both scoping and the $lang parameter. Evaluates to the value produced by the final statement in the file.

TODO: unpolar, fmt, substr-rw, trans, match, subst, sprintf, printf, samecase

# 67 class CurrentThreadScheduler

Scheduler that blockingly executes code on the current thread

    class CurrentThreadScheduler does Scheduler { ... }

CurrentThreadScheduler executes tasks on the current threads. This means that method cue blocks until the code has finished executing.

# 68 class Cursor

Internal state of the regex engine during parsing

    class Cursor { }

A Cursor object is used internally by the regex engine in regex matches to keep track of the current position, backtracking waypoints and information about capturing groups.

A user-space program usually doesn't need to deal with Cursor objects, just with their relatives, Match objects.

# 69 class Date

Calendar date

    class Date { }

A Date is an immutable object identifying a day in the Gregorian calendar.

Date objects support addition and subtraction of integers, where an integer is interpreted as the number of days. You can compare Date objects with the numeric comparison operators ==, <, <=, >, >=, != . Their stringification in YYYY-MM-DD format means that comparing them with the string operators eq, lt, le etc. also gives the right result.

Date.today creates an object the current day according to the system clock.

    my $d = Date.new(2015, 12, 24); # Christmas Eve!
    say $d;                         # 2015-12-24
    say $d.year;                    # 2015
    say $d.month;                   # 12
    say $d.day;                     # 24
    say $d.day-of-week;             # 1  (that's Monday)
    say $d.later(days => 20);       # 2016-01-13
    my $n = Date.new('2015-12-31'); # New Year's Eve
    say $n - $d;                    # 7 days between New Years/Christmas Eve
    say $n + 1;                     # 2016-01-01

# 69.1 Methods

## 69.1.1 method new

Defined as:

    proto method new() {*}
    multi method new($year, $month, $day, :&amp;formatter) returns Date:D
    multi method new(:$year!, :$month = 1, :$day = 1)  returns Date:D
    multi method new(Str $date)                        returns Date:D
    multi method new(Instant:D $dt)                    returns Date:D
    multi method new(DateTime:D $dt)                   returns Date:D

Usage:

    $date = Date.new(YEAR, MONTH, DAY, FORMATTER?)
    $date = Date.new(year => YEAR, month => MONTH?, day => DAY?, FORMATTER?)
    $date = Date.new(YYYY-MM-DD, FORMATTER?)
    $date = Date.new(now, FORMATTER?)
    $date = Date.new(DateTime.now, FORMATTER?)

Creates a new Date object, either from a triple of (year, month, day) that can be coerced to integers, or from a string of the form YYYY-MM-DD (ISO 8601), or from an Instant or DateTime object. Optionally accepts a formatter as a named parameter.

## 69.1.2 method new-from-daycount

Defined as:

    method new-from-daycount($daycount,:&amp;formatter) returns Date:D

Usage:

    $date = Date.new-from-daycount(DAYCOUNT, FORMATTER?)

Creates a new Date object given $daycount which is the number of days from epoch Nov. 17, 1858, i.e. the Modified Julian Day. Optionally accepts a formatter as a named parameter.

    say Date.new-from-daycount(49987);          # 1995-09-27

## 69.1.3 method clone

Defined as:

    method clone(:$year, :$month, :$day)

Usage:

    DATE.clone(YEAR, MONTH, DAY)

Creates a new Date object based on the invocant, but with the given arguments overriding the values from the invocant.

    say Date.new('2015-11-24').clone(month => 12);    # 2015-12-24

## 69.1.4 method today

Defined as:

    method today(:&amp;formatter) returns Date:D

Usage:

    Date.today

Returns a Date object for the current day. Optionally accepts a formatter named parameter.

## 69.1.5 method later

Defined as:

    method later(Date:D: *%unit)

Usage:

    DATE.later(DELTA)

Returns a Date object based on the current one, but with a date delta applied. The date delta can be passed as a named argument where the argument name is the unit.

Allowed units are day, days, week, weeks, month, months, year, years. Please note that the plural forms can only be used with the later method.

Please note that the special ":2nd" named parameter syntax can be a compact and self-documenting way of specifying the delta

    say Date.new('2015-12-24').later(:2years);  # 2017-12-24

Since addition of several different time units is not commutative, only one unit may be passed.

    my $d = Date.new('2015-02-27');
    say $d.later(month => 1).later(:2days);  # 2015-03-29
    say $d.later(days => 2).later(:1month);  # 2015-04-01
    say $d.later(days => 2).later(:month);   # same, as +True === 1

Negative offsets are allowed, though #method earlier is more idiomatic for that.

## 69.1.6 method earlier

Defined as:

    method earlier(Date:D: *%unit)

Usage:

    DATE.earlier(DELTA)

Returns a Date object based on the current one, but with a date delta towards the past applied. See #method later for usage.

## 69.1.7 method truncated-to

Defined as:

    method truncated-to(Date:D: Cool $unit)

Usage:

    DATE.truncated-to(UNIT)

Returns a Date truncated to the first day of its year, month or week. For example

    my $c = Date.new('2012-12-24');
    say $c.truncated-to('year');     # 2012-01-01
    say $c.truncated-to('month');    # 2012-12-01
    say $c.truncated-to('week');     # 2012-12-24  (because it's Monday already)

## 69.1.8 method succ

Defined as:

    method succ(Date:D:) returns Date:D

Usage:

    DATE.succ

Returns a Date of the following day.

    say Date.new("2016-02-28").succ;   # 2016-02-29

## 69.1.9 method pred

Defined as:

    method pred(Date:D:) returns Date:D

Usage:

    DATE.pred

Returns a Date of the previous day.

    say Date.new("2016-01-01").pred;   # 2015-12-31

## 69.1.10 method Str

Defined as:

    multi method Str(Date:D:) returns Str:D

Usage:

    DATE.Str

Returns a string representation of the invocant, as specified by the the formatter. If no formatter was specified, an (ISO 8601) date will be returned.

    say Date.new('2015-12-24').Str;                     # 2015-12-24

    my $fmt = { sprintf "%02d/%02d/%04d", .month, .day, .year };
    say Date.new('2015-12-24', formatter => $fmt).Str;  # 12/24/2015

## 69.1.11 method gist

Defined as:

    multi method gist(Date:D:) returns Str:D

Usage:

    DATE.gist

Returns the date in YYYY-MM-DD format (ISO 8601)

# 69.2 Functions

## 69.2.1 sub sleep

    sub sleep($seconds = Inf --> Nil)

Attempt to sleep for the given number of $seconds. Returns Nil on completion. Accepts Int, Num, Rat, or Duration types as an argument since all of these also do Real.

    sleep 5                # Int
    sleep 5.2              # Num
    sleep (5/2)            # Rat
    sleep (now - now + 5)  # Duration

It is thus possible to sleep for a non-integer amount of time. For instance, the following code shows that sleep (5/2) sleeps for 2.5 seconds and sleep 5.2 sleeps for 5.2 seconds:

    my $before = now
    sleep (5/2)
    my $after = now
    say $after-$before  #=> 2.502411561

    my $before = now
    sleep 5.2
    my $after = now
    say $after-$before  #=> 5.20156987

## 69.2.2 sub sleep-timer

    sub sleep-timer(Real $seconds = Inf --> Duration)

This function is just like sleep, but returns the amount of time remaining to sleep as a Duration (which will be 0 if the call was not interrupted).

    say sleep-timer 3.14  #=> 0

## 69.2.3 sub sleep-until

    sub sleep-until(Instant $until --> Bool)

Works just like sleep but checks the current time and goes back to sleep if accidentally woken up early, to guarantee waiting until the specified time. Returns True if the function actually waited, or if the specified time happens to be the present moment. Returns False if you asked to sleep until a time in the past.

To sleep until 10 seconds into the future, one could write something like this:

    say sleep-until now+10     #=> True

Trying to sleep until a time in the past doesn't work:

    my $instant = now - 5;
    say sleep-until $instant   # => False

However if we put the instant sufficiently far in the future, the sleep should run:

    my $instant = now + 30
    # assuming the two commands are run within 30 seconds of one another...
    say sleep-until $instant   # => True

To specify an exact instant in the future, first create a DateTime at the appropriate point in time, and cast to an Instant.

    my $instant = DateTime.new(
        year => 2020,
        month => 9,
        day => 1,
        hour => 22,
        minute => 5);
    say sleep-until $instant.Instant  # => True (eventually...)

This could be be used as a primitive kind of alarm clock. For instance, say you need to get up at 7am on the 4th of September 2015, but for some reason your usual alarm clock is broken and you only have your laptop. You can specify the time to get up (being careful about timezones, since DateTime.new uses UTC by default) as an Instant and pass this to sleep-until, after which you can play an mp3 file to wake you up instead of your normal alarm clock. This scenario looks roughly like this:

    # DateTime.new uses UTC by default, so get timezone from current time
    my $timezone = DateTime.now.timezone;
    my $instant = DateTime.new(
        year => 2015,
        month => 9,
        day => 4,
        hour => 7,
        minute => 0,
        timezone => $timezone
    ).Instant;
    sleep-until $instant;
    qqx{mplayer wake-me-up.mp3};

# 70 class DateTime

Calendar date with time

    class DateTime does Dateish { ... }

For handling points in civil time, a DateTime object stores year, month, day, hour, minute (all Int), second (potentially fractional) and a time zone.

It provides methods for calculating with date and time.

DateTime methods are immutable; if you are tempted to modify one, create a modified copy instead.

Time zones are handled as Integers in seconds offset from UTC, not by time zone name.

    use v6;
     my $dt = DateTime.new(
         year    => 2015,
         month   => 11,
         day     => 21,
         hour    => 16,
         minute  => 1,
     );

     say $dt;                            # 2015-11-21T16:01:00Z
     say $dt.later(days => 20);          # 2015-12-11T16:01:00Z
     say $dt.truncated-to('hour');       # 2015-11-21T16:00:00Z
     say $dt.in-timezone(-8 * 3600);     # 2015-11-21T08:01:00-0800

     my $now = DateTime.now(formatter => { sprintf "%02d:%02d",.hour,.minute });
     say $now;                           # 12:45 (or something like that)

# 70.1 Methods

## 70.1.1 method new

Defined as:

    multi method new(Int :$year!, Int :$month = 1, Int :$day = 1,
                     Int :$hour = 0, Int :$minute = 0, :$second = 0,
                     Int :$timezone = 0, :&amp;formatter)
    multi method new(Date :$date!,
                     Int :$hour = 0, Int :$minute = 0, :$second = 0,
                     Int :$timezone = 0, :&amp;formatter)
    multi method new(Int() $year, Int() $month, Int() $day,
                     Int() $hour, Int $minute, $second,
                     Int() :$timezone = 0, :&amp;formatter)       # since 6.d
    multi method new(Instant:D $i,  :$timezone=0, :&amp;formatter)
    multi method new(Int:D $posix,  :$timezone=0, :&amp;formatter)
    multi method new(Str:D $format, :$timezone=0, :&amp;formatter)

Usage:

    $datetime = DateTime.new(YEAR, MONTH?, DAY?, HOUR?, MINUTE?, SECOND?,
      TIMEZONE?, FORMATTER?)
    $datetime = DateTime.new(DATE, HOUR?, MINUTE?, SECOND?, TIMEZONE?,
      FORMATTER?)
    $datetime = DateTime.new(YEAR, MONTH, DAY, HOUR, MINUTE, SECOND,
      TIMEZONE?, FORMATTER?)                                  # since 6.d
    $datetime = DateTime.new(INSTANT, TIMEZONE?, FORMATTER?)
    $datetime = DateTime.new(TIMESTAMP, TIMEZONE?, FORMATTER?)
    $datetime = DateTime.new(FORMAT, TIMEZONE?, FORMATTER?)

Creates a new DateTime object. One option for creating a new DateTime object is from the components (year, month, day, hour, ...) separately. Another is to pass a Date object for the date component, and specify the time component-wise. Yet another is to obtain the time from an Instant, and only supply the time zone and formatter. Or instead of an Instant you can supply an Int as a UNIX timestamp.

You can also supply a Str formatted in ISO 8601 timestamp notation or as a full RFC 3339 date and time. Strings should be formatted as yyyy-mm-ddThh:mm::ssZ or yyyy-mm-ddThh:mm:ss+0100. We are somewhat less restrictive than the ISO 8601 standard, as we allow Unicode digits and mixing of condensed and extended time formats.

An invalid input string throws an exception of type X::Temporal::InvalidFormat. If you supply a string that includes a time zone and supply the timezone named argument, an exception of type X::DateTime::TimezoneClash is thrown.

## 70.1.2 method now

Defined as:

    method now(:$timezone=$*TZ, &amp;formatter) returns DateTime:D

Usage:

    DateTime.now(TIMEZONE?, FORMATTER?)

Creates a new DateTime object from the current system time, optionally with a different timezone than the default attached.

## 70.1.3 method clone

Defined as:

    method clone(:$year, :$month, :$day, :$hour, :$minute, :$second,
                 :$timezone, :&amp;formatter)

Usage:

    DATETIME.clone(YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, TIMEZONE,
    FORMATTER)

Creates a new DateTime object based on the invocant, but with the given arguments overriding the values from the invocant.

    say DateTime.new('2015-12-24T12:23:00Z').clone(hour => 0);
        # 2015-12-24T00:23:00Z

Note that this can lead to invalid dates in some circumstances:

    say DateTime.new("2012-02-29T12:34:56Z").clone(year => 2015);
        # day of 2015/2 out of range. Is: 29, should be in 1..28

## 70.1.4 method hour

Defined as:

    method hour(DateTime:D:) returns Int:D

Usage:

    DATETIME.hour

Returns the hour component.

    say DateTime.new('2012-02-29T12:34:56Z').hour;      # 12

## 70.1.5 method minute

Defined as:

    method minute(DateTime:D:) returns Int:D

Usage:

    DATETIME.minute

Returns the minute component.

    say DateTime.new('2012-02-29T12:34:56Z').minute;     # 34

## 70.1.6 method second

Defined as:

    method second(DateTime:D:)

Usage:

    DATETIME.second

Returns the second component, including potentially fractional seconds.

    say DateTime.new('2012-02-29T12:34:56Z').second;     # 56
    say DateTime.new('2012-02-29T12:34:56.789Z').second; # 56.789
    say DateTime.new('2012-02-29T12:34:56,789Z').second; # comma also ok

## 70.1.7 method whole-second

Defined as:

    method whole-second(DateTime:D:)

Usage:

    DATETIME.whole-second

Returns the second component, rounded down to an Int.

    say DateTime.new('2012-02-29T12:34:56.789Z').whole-second;      # 56

## 70.1.8 method timezone

Defined as:

    method timezone(DateTime:D:) returns Int:D

Usage:

    DATETIME.timezone

Returns the time zone in seconds as an offset from UTC.

    say DateTime.new('2015-12-24T12:23:00+0200').timezone;      # 7200

## 70.1.9 method offset

Defined as:

    method offset(DateTime:D:) returns Int:D

Usage:

    DATETIME.offset

Returns the time zone in seconds as an offset from UTC. This is an alias for #method timezone.

    say DateTime.new('2015-12-24T12:23:00+0200').offset;            # 7200

## 70.1.10 method offset-in-minutes

Defined as:

    method offset-in-minutes(DateTime:D:) returns Real:D

Usage:

    DATETIME.offset-in-minutes

Returns the time zone in minutes as an offset from UTC.

    say DateTime.new('2015-12-24T12:23:00+0200').offset-in-minutes; # 120

## 70.1.11 method offset-in-hours

Defined as:

    method offset-in-hours(DateTime:D:) returns Real:D

Usage:

    DATETIME.offset-in-hours

Returns the time zone in hours as an offset from UTC.

    say DateTime.new('2015-12-24T12:23:00+0200').offset-in-hours;   # 2

## 70.1.12 method Str

Defined as:

    method Str(DateTime:D:) returns Str:D

Usage:

    DATETIME.Str

Returns a string representation of the invocant, as done by the formatter. If no formatter was specified, an ISO 8601 timestamp will be returned.

## 70.1.13 method Instant

Defined as:

    method Instant(DateTime:D:) returns Instant:D

Usage:

    DATETIME.Instant

Returns an Instant object based on the invocant.

## 70.1.14 method posix

Defined as:

    method posix(DateTime:D: $ignore-timezone = False) returns Int:D

Usage:

    DATETIME.posix

Returns the date and time as a POSIX/UNIX timestamp (seconds since the Epoch, 1st January 1970 UTC).

    say DateTime.new('2015-12-24T12:23:00Z').posix;     # 1450959780

## 70.1.15 method later

Defined as:

    method later(DateTime:D: *%unit)

Usage:

    DATETIME.later(DELTA)

Returns a DateTime object based on the current one, but with a time delta applied. The time delta can be passed as a named argument where the argument name is the unit.

Allowed units are second, seconds, minute, minutes, hour, hours, day, days, week, weeks, month, months, year, years. Please note that the plural forms can only be used with the later method.

Please note that the special ":2nd" named parameter syntax can be a compact and self-documenting way of specifying the delta

    say DateTime.new('2015-12-24T12:23:00Z').later(:2years);
        # 2017-12-24T12:23:00Z

Since addition of several different time units is not commutative, only one unit may be passed.

    my $d = DateTime.new(date => Date.new('2015-02-27'));
    say $d.later(month => 1).later(:2days);  # 2015-03-29T00:00:00Z
    say $d.later(days => 2).later(:1month);  # 2015-04-01T00:00:00Z
    say $d.later(days => 2).later(:month);   # same, as +True === 1

Negative offsets are allowed, though #method earlier is more idiomatic for that.

## 70.1.16 method earlier

Defined as:

    method earlier(DateTime:D: *%unit)

Usage:

    DATETIME.earlier(DELTA)

Returns a DateTime object based on the current one, but with a time delta towards the past applied. See #method later for usage.

## 70.1.17 method truncated-to

Defined as:

    method truncated-to(DateTime:D: Cool $unit)

Usage:

    DATETIME.truncated-to(UNIT)

Returns a copy of the invocant, with everything smaller than the specified unit truncated to the smallest possible value.

    my $d = DateTime.new("2012-02-29T12:34:56.946314Z");
    say $d.truncated-to('second');      # 2012-02-29T12:34:56Z
    say $d.truncated-to('minute');      # 2012-02-29T12:34:00Z
    say $d.truncated-to('hour');        # 2012-02-29T12:00:00Z
    say $d.truncated-to('day');         # 2012-02-29T00:00:00Z
    say $d.truncated-to('month');       # 2012-02-01T00:00:00Z
    say $d.truncated-to('year');        # 2012-01-01T00:00:00Z

DateTimes with fractional seconds can be truncated to whole seconds with .truncated-to('second').

## 70.1.18 method Date

Defined as:

    method Date(DateTime:D:) returns Date:D

Usage:

    DATETIME.Date

Returns a Date object for this DateTime object. Which obviously lacks the time component.

## 70.1.19 method utc

Defined as:

    method utc(DateTime:D:) returns DateTime:D

Usage:

    DATETIME.utc

Returns a DateTime object for the same time, but in time zone UTC.

    say DateTime.new('2015-12-24T12:23:00+0200').utc";  # 2015-12-24T10:23:00Z

## 70.1.20 method in-timezone

Defined as:

    method in-timezone(DateTime:D: $timezone = 0) returns DateTime:D

Usage:

    DATETIME.in-timezone

Returns a DateTime object for the same time, but in the specified time zone.

    say DateTime.new('2015-12-24T12:23:00Z').in-timezone(3600 + 1800);
        # 2015-12-24T13:53:00+0130

## 70.1.21 method local

Defined as:

    method local(DateTime:D:) returns DateTime:D

Usage:

    DATETIME.local

Returns a DateTime object for the same time, but in the local time zone ($*TZ).

    my $*TZ = -3600;
    say DateTime.new('2015-12-24T12:23:00+0200').local;
            # 2015-12-24T09:23:00-0100

# 71 role Dateish

Object that can be treated as a date

    role Dateish { ... }

Both Date and DateTime support accessing a year, month and day-of-month, as well as related functionality such as calculating the day of the week.

# 71.1 Methods

## 71.1.1 method year

Defined as:

    method year(Date:D:) returns Int:D

Usage:

    Dateish.year

Returns the year of the date

## 71.1.2 method month

Defined as:

    method month(Date:D:) returns Int:D

Usage:

    Dateish.month

Returns the month of the date (1..12)

## 71.1.3 method day

Defined as:

    method day(Date:D:) returns Int:D

Usage:

    Dateish.day

Returns the day of the month of the date (1..31)

## 71.1.4 method formatter

Defined as:

    method formatter(Dateish:D:)

Usage:

    Dateish.formatter

Returns the formatting function which is used for conversion to Str. If none was provided at object construction, a default formatter is used. In that case the method will return a Callable type object.

The formatting function is called by DateTime method Str with the invocant as its only argument.

    my $dt = Date.new('2015-12-31');  # (no formatter specified)
    say $dt.formatter.WHAT;           # (Callable)
    my $us-format = sub ($self) { sprintf "%02d/%02d/%04d", .month, .day, .year given $self; };
    $dt = Date.new('2015-12-31', formatter => $us-format);
    say $dt.formatter.WHAT;           # (Sub)
    say $dt;                          # 12/31/2015

## 71.1.5 method is-leap-year

Defined as:

    method is-leap-year($year = self.year) returns Bool:D

Usage:

    Dateish.is-leap-year(YEAR?)

Returns True if $year is a leap year. Can be called as a class method if the year is provided.

    say Dateish.is-leap-year(2016);           # True
    say Date.new("1900-01-01").is-leap-year;  # False

## 71.1.6 method day-of-month

Defined as:

    method day-of-month(Date:D:) returns Int:D

Usage:

    Dateish.day-of-month

Returns the day of the month of the date (1..31). Synonymous to the day method.

## 71.1.7 method day-of-week

Defined as:

    method day-of-week(Date:D:) returns Int:D

Usage:

    Dateish.day-of-week

Returns the day of the week, where 1 is Monday, 2 is Tuesday and Sunday is 7.

## 71.1.8 method day-of-year

Defined as:

    method day-of-year(Date:D:) returns Int:D

Usage:

    Dateish.day-of-year

Returns the day of the year (1..366).

## 71.1.9 method days-in-month

Defined as:

    method days-in-month(year = self.year, month = self.month) returns Int:D

Usage:

    Dateish.days-in-month(YEAR?, MONTH?)

Returns the number of days in a month, where year and month default to that of the invocant. If both year and month are provided, it can be called as a class method.

    say Date.new("2016-01-02").days-in-month;  # 31
    say Dateish.days-in-month(2016, 1);        # 31

## 71.1.10 method week

Defined as:

    method week()

Usage:

    Dateish.week

Returns a list of two integers: the year, and the week number. This is because at the start or end of a year, the week may actually belong to the other year.

    my ($year, $week) = Date.new("2014-12-31").week;
    say $year;      # 2015
    say $week;      # 1
    say Date.new('2015-01-31').week;        # 2015 5

## 71.1.11 method week-number

Defined as:

    method week-number(Date:D:) returns Int:D

Usage:

    Dateish.week-number

Returns the week number (1..53) of the date specified by the invocant. The first week of the year is defined by ISO as the one which contains the fourth day of January. Thus, dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year.

    say Date.new("2014-12-31").week-number;   # 1  (first week of 2015)
    say Date.new("2016-01-02").week-number;   # 53 (last week of 2015)

## 71.1.12 method week-year

Defined as:

    method week-year(Date:D:) returns Int:D

Usage:

    Dateish.week-year

Returns the week year of the date specified by the invocant. Normally week-year is equal to Date.year. Note however that dates early in January often end up in the last week of the prior year, and similarly, the final few days of December may be placed in the first week of the next year.

    say Date.new("2015-11-15").week-year;   # 2015
    say Date.new("2014-12-31").week-year;   # 2015 (date belongs to the first week of 2015)
    say Date.new("2016-01-02").week-year;   # 2015 (date belongs to the last week of 2015)

## 71.1.13 method weekday-of-month

Defined as:

    method weekday-of-month(Date:D:) returns Int:D

Usage:

    Dateish.weekday-of-month

Returns a number (1..5) indicating the number of times a particular day-of-week has occurred so far during that month, the day itself included.

    say Date.new("2003-06-09").weekday-of-month;  # 2  (second Monday of the month)

## 71.1.14 method yyyy-mm-dd

Defined as:

    method yyyy-mm-dd(Date:D:) returns Str:D

Usage:

    Dateish.yyyy-mm-dd

Returns the date in YYYY-MM-DD format (ISO 8601)

## 71.1.15 method daycount

Defined as:

    method daycount(Dateish:D:) returns Int:D

Usage:

    Dateish.daycount

Returns the number of days from the epoch Nov. 17, 1858 to the day of the invocant. The daycount returned by this method is the MJD, i.e. the Modified Julian Day, which is used routinely by e.g. astronomers, geodesists, scientists and others. The MJD convention is designed to facilitate simplified chronological calculations.

    say Date.new('1995-09-27').daycount;    # 49987

# 72 class Duration

Length of time

    class Duration is Cool does Real { }

A Duration represents a length of time in atomic seconds, with fractions. Like an Instant, it is epoch-agnostic. In numeric contexts (situations where a Duration is used as a number), a Duration will return either a Rat or a FatRat representing the number of seconds it holds.

Durations can be subtracted from or added to Instants to yield another, new Instant. Subtracting one Instant from another yields a Duration. A Duration can also result from mathematical operations between two Durations when it makes sense (namely, the addition, subtraction, or modulus of two Durations). The type of object returned for other numeric operations is currently unspecified.

# 73 class Exception

Anomalous event capable of interrupting normal control-flow

    class Exception { ... }

All exceptions that are placed into the $! variable (or into $_ in CATCH blocks) inherit from Exception. When you call die or fail with a non-Exception argument, it is wrapped into an X::AdHoc object, which also inherits from Exception.

User-defined exception classes should inherit from Exception too, and define at least a method message.

    class X::YourApp::SomeError is Exception {
        method message() {
            "A YourApp-Specific error occurred: out of coffee!";
        }
    }

# 73.1 Methods

## 73.1.1 method message

Defined as:

    method message(Exception:D:) returns Str:D

Usage:

    EXCEPTION.message

This is a stub that must be overwritten by subclasses, and should return the exception message.

Special care should be taken that this method does not produce an exception itself.

## 73.1.2 method backtrace

Defined as:

    method backtrace(Exception:D:) returns Backtrace:D

Usage:

    EXCEPTION.backtrace

Returns the backtrace associated with the exception. Only makes sense on exceptions that have been thrown at least once.

## 73.1.3 method throw

Defined as:

    method throw(Exception:D:)

Usage:

    EXCEPTION.throw

Throws the exception.

## 73.1.4 method resume

Resumes control flow where .throw left it when handled in a CATCH block.

Defined as:

    method resume(Exception:D:)

Usage:

    CATCH { default { .resume } }

## 73.1.5 method rethrow

Defined as:

    method rethrow(Exception:D:)

Usage:

    EXCEPTION.rethrow

Rethrows an exception that has already been thrown at least once. This is different from throw in that it preserves the original backtrace.

## 73.1.6 method fail

Defined as:

    sub    fail(*@text)
    sub    fail(Exception $e)
    method fail(Exception:D $e:)

Usage:

    fail(TEXT)
    fail(EXCEPTION)
    EXCEPTION.fail

Exits the calling Routine and returns a Failure object wrapping the exception $e - or, for the *@text form, an X::AdHoc exception constructed from the concatenation of @text.

    sub copy-directory-tree ($dir) {
        fail "$dir is not a directory" if !$dir.IO.d;
        ...
    }

## 73.1.7 method gist

Defined as:

    multi method gist(Exception:D:)

Usage:

    EXCEPTION.gist

Returns whatever the exception printer should produce for this exception. The default implementation returns message and backtrace separated by a newline.

## 73.1.8 sub die

Defined as:

    multi sub die(*@message)
    multi sub die(Exception:D $e:)
    method    die(Exception:D $e:)

Usage:

    die(MESSAGE)
    die(EXCEPTION)
    EXCEPTION.die

Throws a fatal Exception. The default exception handler prints each element of the list to $*ERR (STDERR).

## 73.1.9 sub warn

Defined as:

    multi sub warn(*@message)

Usage:

    warn(MESSAGE)

Throws a resumable warning exception, which is considered a control exception, and hence is invisible to most normal exception handlers. The outermost control handler will print the warning to $*ERR. After printing the warning, the exception is resumed where it was thrown. To override this behavior, catch the exception in a CONTROL block. A quietly {...} block is the opposite of a try {...} block in that it will suppress any warnings but pass fatal exceptions through.

To simply print to $*ERR, please use note instead. warn should be reserved for use in threatening situations when you don't quite want to throw an exception.

# 74 class Failure

Delayed exception

    class Failure { }

A Failure is a soft or unthrown exception, usually generated by calling &fail. It acts as a wrapper around an Exception object.

Sink (void) context causes a Failure to throw, i.e. turn into a normal exception.

Checking a Failure for truth (with the Bool method) or definedness (with the defined method) marks the failure as handled, and causes it not to throw in sink context anymore.

You can call the handled method to check if a failure has been handled.

Calling methods on unhandled failures propagates the failure. The specification says the result is another Failure, in Rakudo it causes the failure to throw.

# 74.1 Methods

## 74.1.1 method handled

Defined as:

    method handled(Failure:D:) returns Bool:D

Usage:

    FAILURE.handled

Returns True for handled failures, False otherwise.

## 74.1.2 method exception

Defined as:

    method exception(Failure:D:) returns Exception

Usage:

    FAILURE.exception

Returns the Exception object that the failure wraps.

## 74.1.3 method Bool

Defined as:

    multi method Bool(Failure:D:) returns Bool:D

Usage:

    FAILURE.Bool

Returns False, and marks the failure as handled.

## 74.1.4 method defined

Defined as:

    multi method defined(Failure:D:) returns Bool:D

Usage:

    FAILURE.defined

Returns False (failures are officially undefined), and marks the failure as handled.

# 75 class FatRat

Rational number (arbitrary-precision)

    class FatRat is Cool does Rational[Int, Int]

A FatRat is a rational number stored with arbitrary size numerator and denominator. Arithmetic operations involving a FatRat and optionally Int or Rat objects return a FatRat, avoiding loss of precision.

Since, unlike Rat, FatRat arithmetics do not fall back Num at some point, there is a risk that repeated arithmetic operations generate pathologically large numerators and denominators.

There are two common ways to generate FatRat objects: through the FatRat.new(Int, Int) constructor, which generates them from numerator and denominator, or by calling the .FatRat method on an Int or Rat object.

# 76 class Grammar

Formal grammar made up of named regexes

    class Grammar is Cursor { ... }

Every type declared with grammar (which doesn't explicitly states its superclass) becomes a subclass of Grammar.

    grammar Thingy {
        token TOP {
            &lt;a> &lt;b>
        }
        token a { a }
        token b { b }
    }
    say Thingy ~~ Grammar;      # True
    my $match = Thingy.parse('ab');
    say so $match;              # True
    say ~$match&lt;a>;             # a

More documentation on grammars is available.

# 76.1 Methods

## 76.1.1 method parse

Defined as:

    method parse($target, :$rule = 'TOP',  Capture() :$args = \(), Mu :$actions = Mu, *%opt) {

Usage:

    GRAMMAR.parse(TARGET, RULE?, ARGS?, ACTIONS?, OPTIONS?)

Parses the $target (which will be coerced to Str if it isn't one), using $rule as the starting rule. Additional $args will be given to the starting rule if provided.

If the action named argument is provided, it will be used as an action object, that is, for each successful regex match, a method of the same name (if it exists) is called on the action object, passing the match object as the sole positional argument.

Additional named arguments are used as options for matching, so you can specify things like :c(4) to start parsing from the fourth character. All matching adverbs are allowed.

Method parse only succeeds if the cursor has arrived at the end of the target string when the match is over. Use method subparse if you want to be able to stop in the middle.

Returns a Match object on success, and Nil on failure.

    grammar CSV {
        token TOP { [ &lt;line> \n? ]+ }
        token line {
            ^^            # Beginning of a line
            &lt;value>* % \, # Any number of &lt;value>s with commas in between them
            $$            # End of a line
        }
        token value {
            [
            | &lt;-[",\n]>     # Anything not a double quote, comma or newline
            | &lt;quoted-text> # Or some quoted text
            ]*              # Any number of times
        }
        token quoted-text {
            \"
            [
            | &lt;-["\\]> # Anything not a " or \
            | '\"'     # Or \", an escaped quotation mark
            ]*         # Any number of times
            \"
        }
    }.parse( q:to/EOCSV/ ).say;
        Year,Make,Model,Length
        1997,Ford,E350,2.34
        2000,Mercury,Cougar,2.38
        EOCSV

This outputs:

    ｢Year,Make,Model,Length
    1997,Ford,E350,2.34
    2000,Mercury,Cougar,2.38
    ｣
     line => ｢Year,Make,Model,Length｣
      value => ｢Year｣
      value => ｢Make｣
      value => ｢Model｣
      value => ｢Length｣
     line => ｢1997,Ford,E350,2.34｣
      value => ｢1997｣
      value => ｢Ford｣
      value => ｢E350｣
      value => ｢2.34｣
     line => ｢2000,Mercury,Cougar,2.38 ｣
      value => ｢2000｣
      value => ｢Mercury｣
      value => ｢Cougar｣
      value => ｢2.38 ｣

## 76.1.2 method subparse

Defined as:

    method subparse($target, :$rule = 'TOP', Capture() :$args = \(),  Mu :$actions = Mu, *%opt) {

Usage:

    GRAMMAR.subparse(TARGET, RULE?, ARGS?, ACTIONS?, OPTIONS?)

Does exactly the same as method parse, except that cursor doesn't have to reach the end of the string to succeed. (That is, it doesn't have to match the whole string).

    grammar A {
        token as { a+ };
    }
    my $match = A.subparse('aaab', :rule&lt;as>);
    say ~$match;        # aaa
    say $match.to;      # 3

## 76.1.3 method parsefile

Defined as:

    method parsefile(Str(Cool) $filename, :$enc, *%opts) {

Usage:

    GRAMMAR.parsefile(FILE, OPTIONS?)

Reads file $filename, and parses it. All named arguments are passed on to method parse.

# 77 class Hash

Mapping from strings to itemized values

    class Hash is Map { }

A Hash is a mutable mapping from keys to values (called dictionary, hash table or map in other programming languages). The values are all scalar containers, which means you can assign to them.

Hashes are usually stored in variables with the percent % sigil.

Hash elements are accessed by key via the { } postcircumfix operator:

    dd %*ENV{'HOME', 'PATH'};
    # OUTPUT«("/home/camelia", "/usr/bin:/sbin:/bin")␤»

The general Subscript rules apply providing shortcuts for lists of literal strings, with and without interpolation.

    my %h = oranges => 'round', bananas => 'bendy';
    dd %h&lt;oranges bananas>;
    # OUTPUT«("round", "bendy")␤»
    my $fruit = 'bananas';
    dd %h«oranges $fruit»
    OUTPUT«("round", "bendy")␤»

You can add new pairs simply by assigning to an unused key:

    my %h;
    %h{'new key'} = 'new value';

# 77.1 Hash assignment

Assigning a list of elements to a hash variable first empties the variable, and then iterates the elements of the right-hand side. If an element is a Pair, its key is taken as a new hash key, and its value as the new hash value for that key. Otherwise the value is coerced to Str and used as a hash key, while the next element of the list is taken as the corresponding value.

    my %h = 'a', 'b', c => 'd', 'e', 'f';
    # same as
    my %h = a => 'b', c => 'd', e => 'f';
    # or
    my %h = &lt;a b c d e f>;

If a Pair is encountered where a value is expected, it is used as a hash value:

    my %h = 'a', 'b' => 'c';
    say %h&lt;a>.WHAT;             # Pair();
    say %h&lt;a>.key;              # b

If the same key appears more than once, the value associated with its last occurrence is stored in the hash:

    my %h = a => 1, a => 2;
    say %h&lt;a>;                  # 2

To assign to a variable without the % sigil, you may use curly braces:

    my $h = { a => 1, b => 2 }; # *See Note*
    say $h.WHAT;                # Hash
    say $h&lt;a>;                  # 1

NOTE: If one or more values reference the topic variable, $_, the right-hand side of the assignment will be interpreted as a Block, not a Hash:

    my @people = [
        { id => "1A", firstName => "Andy", lastName => "Adams" },
        { id => "2B", firstName => "Beth", lastName => "Burke" },
        # ...
    ];

    sub lookup-user (Hash $h) { #`(Do something...) $h }

    my @names = map {
        my $query = { name => "$_&lt;firstName> $_&lt;lastName>" };
        say $query.WHAT;       # Block
        say $query&lt;name>;      # ERROR: Type Block does not support associative indexing

        lookup-user($query);   # Type check failed in binding $h; expected Hash but got Block
    }, @people;

Instead, you should either:

- 1) use the %() hash constructor:

      my  $query = %( name => "$_&lt;firstName> $_&lt;lastName>" );
      say $query.WHAT;         # Hash
      say $query&lt;name>;        # Andy Adams, Beth Burke, etc.

- 2) assign to a Hash type (%) directly:

      my  %query = name => "$_&lt;firstName> $_&lt;lastName>";   # No braces required
      say %query.WHAT;         # Hash
      say %query&lt;name>;        # Andy Adams, Beth Burke, etc.

- or 3) simply avoid the issue altogether by explicitly providing a name for the topic variable:

      my @names = map -> $person {
          my $query = { name => "$person&lt;firstName> $person&lt;lastName>" };
          say $query.WHAT;     # Hash
          say $query&lt;name>;    # Andy Adams, Beth Burke, etc.

         lookup-user($query);
      }, @people;

Even in the final case, however, specifying a Hash type (%) is still the most idiomatic and unambiguous solution:

    my @names = @people.map: -> $person {
        lookup-user( %( name => "$person&lt;firstName> $person&lt;lastName>" ) );
    };

## 77.1.1 Non-string keys

By default keys in { } are forced to strings. To compose a hash with non-string keys, use a colon prefix:

    my $when = :{ (now) => "Instant", (DateTime.now) => "DateTime" };

Note that with objects as keys, you cannot access non-string keys as strings:

    :{ -1 => 41, 0 => 42, 1 => 43 }&lt;0>  # Any
    :{ -1 => 41, 0 => 42, 1 => 43 }{0}  # 42

# 77.2 Looping over hash keys and values

A common idiom for processing the elements in a hash is to loop over the keys and values, for instance,

    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
    for %vowels.kv -> $vowel, $index {
      "$vowel: $index".say;
    }

gives output similar to this:

    a: 1
    e: 2
    o: 4
    u: 5
    i: 3

where we have used the kv method to extract the keys and their respective values from the hash, so that we can pass these values into the loop.

Note that the order of the keys and values printed cannot be relied upon; the elements of a hash are not always stored the same way in memory for different runs of the same program. Sometimes one wishes to process the elements sorted on, e.g. the keys of the hash. If one wishes to print the list of vowels in alphabetical order then one would write

    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
    for %vowels.sort(*.key)>>.kv -> ($vowel, $index) {
      "$vowel: $index".say;
    }

which prints

    a: 1
    e: 2
    i: 3
    o: 4
    u: 5

and is in alphabetical order as desired. To achieve this result, we sorted the hash of vowels by key (%vowels.sort(*.key)) which we then ask for its keys and values by applying the .kv method to each element via the unary > > hyperoperator resulting in a List of key/value lists. To extract the key/value the variables thus need to be wrapped in parentheses.

An alternative solution is to flatten the resulting list. Then the key/value pairs can be accessed in the same way as with plain .kv:

    my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
    for %vowels.sort(*.key)>>.kv.flat -> $vowel, $index {
      "$vowel: $index".say;
    }

You can also loop over a Hash using destructuring.

## 77.2.1 Object hashes and type constraints

Hash keys are stored as Str values in a normal hash. In many cases this is sufficient, but sometimes you want the hash to preserve the objects you are using as keys as the *exact* objects you are providing to the hash to use as keys. In these moments you want an object hash!

    my %intervals{Instant};
    my $first-instant = now;
    %intervals{ $first-instant } = "Our first milestone.";
    sleep 1;
    my $second-instant = now;
    %intervals{ $second-instant } = "Logging this Instant for spurious raisins.";
    for %intervals.kv.sort(* cmp *) -> (Instant $instant, $note) {
      state $last-instant //= $instant;
      say "We noted '$note' at $instant, with an interval of {$instant - $last-instant}";
      $last-instant = $instant;
    }

This example uses an object hash that only accepts keys of type Instant to implement a rudimentary, yet type-safe, logging mechanism. We utilize a named state variable for keeping track of the previous Instant so that we can provide an interval.

The whole point of object hashes is to keep keys as objects-in-themselves. Currently object hashes utilize the WHICH method of an object, which returns a unique identifier for every mutable object. This is the keystone upon which the object identity operator (===) rests. Order and containers really matter here as the order of .keys is undefined and one anonymous list is never === to another.

    > ($first-instant, $second-instant) ~~ %intervals.keys
    False
    > ($first-instant, $second-instant) ~~ %intervals.keys.sort(* cmp *)
    True
    > ($first-instant, $second-instant) === %intervals.keys.sort(* cmp *)
    False
    > $first-instant === %intervals.keys.sort(* cmp *).index(0)
    True

Since Instant defines its own comparison methods, in our example a sort according to cmp will always provide the earliest instant object as the first element in the List it returns.

If you would like to accept any object whatsoever in your hash, you can use Any!

    my %h{Any};
    %h{(now)} = "This is an Instant";
    %h{(DateTime.now)} = "This is a DateTime, which is not an Instant";
    %h{"completely different"} = "Monty Python references are neither DateTimes nor Instants";

There is a more concise syntax which uses binding.

    my %h := :{ (now) => "Instant", (DateTime.now) => "DateTime" }

The binding is necessary because an object hash is about very solid, specific objects, which is something that binding is great at keeping track of but about which assignment doesn't concern itself much.

## 77.2.2 In place editing of values

There may be times when you would like to modify the values of a hash while iterating over them.

    > my %answers = illuminatus => 23, hitchhikers => 42
    hitchhikers => 42, illuminatus => 23
    > for %answers.values -> $v { $v += 10 }
    Cannot assign to a readonly variable or a value

This is traditionally accomplished by sending both the key and the value as follows.

    for %answers.kv -> $k,$v { %answers{$k} = $v + 10 }

However, it is possible to leverage the signature of the block in order to specify that you would like read-write access to the values.

    for %answers.values -> $v is rw { $v += 10 }

It is not, however, possible to do in-place editing of hash keys, even in the case of object hashes.

# 77.3 Methods

## 77.3.1 method push

Defined as:

    multi method push(Hash:D: *@new)

Usage:

    push HASH, VALUES
    HASH.push(VALUES)
    HASH.push: (VALUES)

Adds the @new elements to the hash with the same semantics as hash assignment, but with three exceptions:

- The hash isn't emptied first, i.e. old pairs are not deleted.

- If a key already exists in the hash, and the corresponding value is an Array, the new value is pushed onto the array (instead of replacing it).

- If a key already exists in the hash, and the corresponding value is not an Array, old and new value are both placed into an array in the place of the old value.

Example:

    my %h  = a => 1;
    %h.push: (a => 1);                  # a => [1,1]
    %h.push: (a => 1) xx 3 ;            # a => [1,1,1,1,1]
    %h.push: (b => 3);                  # a => [1,1,1,1,1], b => 3
    %h.push('c' => 4);                  # a => [1,1,1,1,1], b => 3, c => 4
    push %h, 'd' => 5;                  # a => [1,1,1,1,1], b => 3, c => 4, d => 5

Be careful to quote the keys in the last two methods, as these have no effect:

    %h.push(e => 6);
    push %h, f => 7;

because they are interpreted as named arguments to push, not positional arguments.

Also note that push can be used as a replacement for assignment during hash initialization very useful ways. Take for instance the case of an inverted index:

    my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
    (my %inv).push: %wc.invert.unique;
    say %inv;                           # 322 => 'pair', 323 => ['hash','pipe']

Note that such a initialization could also be written as

    my %inv .= push: %wc.invert.unique;

## 77.3.2 method default

Defined as:

    method default

Usage:

    Hash.default

Returns the default value of the invocant, i.e. the value which is returned when a non existing key is used to access an element in the Hash. Unless the Hash is declared as having a default value by using the is default trait the method returns the type object (Any).

    my %h1 = 'apples' => 3, 'oranges' => 7;
    say %h1.default;                                       # (Any)
    say %h1{'bananas'};                                    # (Any)

    my %h2 is default(1) = 'apples' => 3, 'oranges' => 7;
    say %h2.default;                                       # 1
    say %h2{'apples'} + %h2{'bananas'};                    # 4

## 77.3.3 method keyof

Defined as:

    method keyof

Usage:

    Hash.keyof

Returns the type constraint for the keys of the invocant. For normal hashes the method returns the coercion type (Str(Any)) while for object hashes the type used in the declaration of the Hash is returned.

    my %h1 = 'apples' => 3, 'oranges' => 7;  # (no key type specified)
    say %h1.keyof;                           # (Str(Any))

    my %h2{Str} = 'oranges' => 7;            # (keys must be of type Str
    say %h2.keyof;                           # (Str)
    %h2{3} = 'apples';                       # throws exception of type X::TypeCheck::Binding

## 77.3.4 method of

Defined as:

    method of

Usage:

    Hash.of

Returns the type constraint for the values of the invocant. By default, i.e. if no type constraint is given during declaration, the method returns (Mu).

    my %h1 = 'apples' => 3, 'oranges' => 7;  # (no type constraint specified)
    say %h1.of;                              # (Mu)

    my Int %h2 = 'oranges' => 7;             # (values must be of type Int)
    say %h2.of;                              # (Int)

# 77.4 Subscript Adverbs

Some methods are implemented as adverbs on subscripts.

## 77.4.1 :exists

The adverb :exists returns Bool::True if a key exists in the Hash. If more then one key is supplied it returns a List of Bool.

    my %h = a => 1, b => 2;
    say %h&lt;a>:exists;   # True
    say %h&lt;a b>:exists; # (True True)

## 77.4.2 :delete

Use :delete to remove a Pair from the Hash.

    my %h = a => 1;
    dd %h;         # Hash %h = {:a(1)}
    %h&lt;a>:delete;
    dd %h;         # Hash %h = {}

## 77.4.3 :p

The adverb :p returns a Pair or a List of Pair instead of just the value.

    my %h = a => 1, b => 2;
    say %h&lt;a>:p;    # a => 1
    say %h&lt;a b>:p;  # (a => 1 b=> 2)

## 77.4.4 :v and :k

The adverbs :v and :k return the key or value or a list their of.

    my %h = a => 1, b => 2;
    say %h&lt;a>:k;   # a
    say %h&lt;a b>:k;  # (a b)

# 78 role IO

Input/output related object

    role IO { }

The IO role provides no functionality itself; it simply marks that a particular object relates to input/output.

# 78.1 Routines

## 78.1.1 sub print

Print the given text on $*OUT (standard output), e.g.:

    print "Hi there!\n";   # Hi there!

Note that the print function does not (in contrast to some other languages) append a newline character to the text. Thus the following code

    print "Hi there!";
    print "How are you?";
    print (0..101).list;

displays

    Hi there!How are you?0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101

To print text implicitly including the trailing newline character, use say.

## 78.1.2 sub put

Print the given text on $*OUT (standard output) with appended $*OUT.nl-out. The default for the latter is the platform dependent newline sequence.

    put 'Merry 1.0!';
    put (0..101).list;

outputs

    Merry 1.0!␤
    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101␤

## 78.1.3 sub say

Print the given text in human readable form, followed by a $*OUT.nl-out (platform dependent newline) on $*OUT (standard output). Long output may be truncated. For machine readable output use put.

With say, the example code as mentioned in the print section will be displayed as the user likely intended:

    say "Hi there!";
    say "How are you?";
    say (0..101).list;

displays

    Hi there!␤
    How are you?␤
    (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 ...)␤

say prints non-Str objects by calling their .gist method before printing. Hence the following say statements for the respective containers are equivalent:

    my @array = qw{1 2 3 4};
    say @array;       # 1 2 3 4␤
    say @array.gist;  # 1 2 3 4␤

    my %hash = "a" => 1, "b" => 2, "c" => 3;
    say %hash;        # a => 1, b => 2, c => 3␤
    say %hash.gist;   # a => 1, b => 2, c => 3␤

## 78.1.4 sub note

Print the given text, followed by a newline "\n" on $*ERR (standard error). Before printing, call the .gist method on any non-Str objects.

note is effectively say, only it writes its output to the standard error stream. For instance:

    if ("path/to/pirate/treasure".IO.e) {
        say "Found pirate treasure!";
    }
    else {
        note "Could not find pirate treasure.  Are you sure it exists?";
    }

will report (on the standard output stream) that treasure has been found if it exists or will note on the error stream that it couldn't be found if it doesn't exist.

## 78.1.5 sub dd

The Tiny Data Dumper. This function takes the input list of variables and notes them (on $*ERR) in an easy to read format, along with the name of the variable. Thus,

    my $a = 42;
    my %hash = "a" => 1, "b" => 2, "c" => 3;
    dd %hash, $a;

prints

    %hash = ("a" => 1, "c" => 3, "b" => 2).hash, $a = 42␤

to the standard error stream.

This is in spirit similar to Perl 5's Data::Dumper module.

Please note that dd will ignore named parameters. You can use a capture to force it to dump everything passed to it.

    dd \((:a(1), :b(2)), :c(3));

If you don't specify any parameters at all, it will just print the type and name of the current subroutine / method to the standard error stream:

    sub a { dd }; a    # sub a

This can be handy as a cheap trace function.

## 78.1.6 sub prompt

    sub prompt($msg)

Prints $msg to standard output and waits for the user to type something and finish with an ENTER. Returns the string typed in without the trailing newline.

    my $name = prompt("Hi, what's your name? ");

## 78.1.7 sub open

    my $fh = open(IO::Path() $path, :$r, :$w, :$a, :$rw,
                  :$bin, :$enc, :$nl, :$chomp)

Opens the $path (by default in text mode) with the given options, returning an IO::Handle object.

### 78.1.7.1 File mode options

- read-only mode, :r

Open the file as read only, e.g.:

    my $fh = open("path/to/file", :r);

This is the default mode for open.

Write-related methods on the returned IO::Handle object will fail in this mode:

    my $fh = open("test");   # the file "test" already exists
    $fh.print("new text\n");
    Failed to write bytes to filehandle: bad file descriptor

- write-only mode, :w

Open the file for writing, creating it if it doesn't exist or overwriting the file if it does exist, e.g.:

    my $fh = open("path/to/file", :w);

Read-related methods will fail in this mode:

    my $fh = open("test", :w);
    $fh.print("stuff\n");
    $fh.print("more stuff\n");
    $fh.seek(0, 0);   # return to the start of the file
    $fh.get();        # Reading from filehandle failed: bad file descriptor

- read-write mode, :rw

Open the file for reading and writing, creating the file if it doesn't exist or overwriting the file if it already exists.

    my $fh = open("path/to/file", :rw);

- append mode, :a

Open the file for appending. If the file does not exist, create it. If the file already exists, append data to it.

    my $fh = open("path/to/file", :a);

### 78.1.7.2 Encoding options

- binary mode, :bin

Open the file in binary mode (byte mode):

    my $fh = open("path/to/file", :bin);

A file opened with :bin may still be processed line-by-line, but IO will be in terms of Buf rather than Str types. Default is False, implying text semantics.

- text mode encoding, :enc

The encoding to use if opened in text mode.

    # open explicitly as utf8
    my $fh = open("path/to/file", enc => "utf8");
    my $fh = open("path/to/file", enc => "utf-8");  # this form also works
    # open with latin1 encoding
    my $fh = open("path/to/file", enc => "latin1");

Defaults to "Unicode", which implies figuring out which actual UTF is in use, either from a BOM or other heuristics. If heuristics are inconclusive, UTF-8 will be assumed. (No 8-bit encoding will ever be picked implicitly.) There exists no valid option with the name "Unicode", so the following will result in an error:

    my $fh = open("path/to/file", enc => "Unicode");

This is because one needs to specify a specific unicode encoding, e.g. "utf8".

### 78.1.7.3 Newline options

- end-of-line (EOL) marker, :nl

The marker used to indicate the end of a line of text. Only used in text mode. Defaults to "EOL", which implies accepting any combination of "\n", "\r\n" or "\r" or any other Unicode character that has the Zl (Separator, Line) property.

    # explicitly use CR-LF as EOL character
    my $fh = open("path/to/file", nl => "\r\n");

- chomp mode, :chomp

Whether or not to remove newline characters from text obtained with .lines and .get. Defaults to True.

    # don't remove newline characters from input
    my $fh = open("path/to/file", chomp => False);
    say $fh.get();     # returns line including newline char

## 78.1.8 method close

To close an open file handle, simply call its close method:

    my $fh = open("path/to/file");
    # ... do stuff with the file
    $fh.close;

It is also possible to call this as a sub, thus the example above can be written equivalently like so:

    my $fh = open("path/to/file");
    # ... do stuff with the file
    close $fh;

When a file was opened for writing, closing it is important to ensure that all contents are actually written to the file.

## 78.1.9 sub slurp

Slurps the contents of the entire file into a Str (or Buf if :bin). Accepts :bin and :enc optional named parameters, with the same meaning as open(). The routine will fail if the file does not exist, or is a directory.

    # read entire file as (Unicode) Str
    my $text_contents   = slurp "path/to/file";

    # read entire file as Latin1 Str
    my $text_contents   = slurp "path/to/file", enc => "latin1";

    # read entire file as Buf
    my $binary_contents = slurp "path/to/file", :bin;

## 78.1.10 sub spurt

    sub spurt($where, $what,
        Str  :$enc        = $*ENC,
        Bool :$bin        = False,
        Bool :$append      = False,
        Bool :$createonly = False,
        --> Bool ) is export

Writes the indicated contents (2nd positional parameter, $what) to the location indicated by the first positional parameter, $where (which can either be a string or an IO::Path object). To write to an IO::Handle, use the print method.

If a file needs to be opened for writing, it will also be closed. Returns True on success, or the appropriate Failure if something went wrong.

These named parameters are optional and only have meaning if the first positional parameter was not an IO::Handle:

### 78.1.10.1 Options

- :enc

The encoding with which the contents will be written.

- :bin

Open the file in binary mode.

- :append

Boolean indicating whether to append to a (potentially) existing file. If the file did not exist yet, it will be created. Defaults to False.

- :createonly

Boolean indicating whether to fail if the file already exists. Defaults to False.

### 78.1.10.2 Examples

    # write directly to a file
    spurt "path/to/file", "default text, directly written";

    # write directly with a non-Unicode encoding
    spurt "path/to/latin1_file", "latin1 text: äöüß", enc => "latin1";

    # append to a pre-existing file
    spurt "file_already_exists", "some text";
    spurt "file_already_exists", "new text", :append;
    slurp "file_already_exists";   # some text␤new text

    # fail when writing to a pre-existing file
    spurt "file_already_exists", "new text", :createonly;
    File 'test' already exists, and :createonly was specified

## 78.1.11 sub run

    sub run(*@args ($, *@)) returns Proc

Runs an external command without involving a shell (if possible).

See Proc for more details, for example on how to capture output.

## 78.1.12 sub shell

    sub shell($cmd) returns Proc

Runs a command through the system shell. All shell meta characters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on. See run if you don't want that.

The return value is of type Proc.

    shell 'ls -lR | gzip -9 > ls-lR.gz';

See Proc for more details, for example on how to capture output.

# 78.2 Related classes

See also the related classes IO::Handle and IO::Path.

# 79 class IO::Handle

Opened file or stream

    class IO::Handle does IO { }

# 79.1 Methods

## 79.1.1 method get

Reads a single line from the input stream (usually the Standard Input or a file).

Read one line from the standard input:

    $*IN.get;

Read one line from a file:

    my $fh = open 'filename';
    my $line = $fh.get;

## 79.1.2 method getc

Read a single character from the input stream or return Nil. The operation is blocking and the stream may be buffered.

## 79.1.3 method eof

Returns True if the read operations have exhausted the content of the file.

## 79.1.4 method lines

    method lines($limit = Inf)

Return a lazy list of the file's lines read via get, limited to $limit lines. The new line separator (i.e., $*IN.nl-in) will be excluded.

        my @data;
         my $data-file = open 'readings.csv';
         for  <b>$data-file.lines</b>  -> $line {
             @data.push($line.split(','))
         }

## 79.1.5 method words

    method words($count = Inf)

Return a lazy list of the file's words (separated on whitespace), limited to $count words.

        my %dict;
         ++%dict{$_} for $*IN.words;
         say "Most common words: ", %dict.sort(*.value).reverse.[^5];

## 79.1.6 method split

    method split(splitter = "")

Returns a lazy list of strings found between the splitter, just like split on strings.

## 79.1.7 method comb

    method comb(comber = "")

Returns a lazy list of strings combed from the handle, just like comb on strings.

## 79.1.8 method print

    method print(*@text --> Bool)

Text writing; writes the given @text to the filehandle. See write to write bytes.

    my $fh = open 'path/to/file', :w;
    $fh.print("some text\n");
    $fh.close;

## 79.1.9 method print-nl

    method print-nl(IO::Handle:D: --> True)

Writes a newline to the filehandle. The newline marker, which is stored in the attribute $.nl-out, defaults to \n unless another marker has been specified in the call to open.

    my $fh = open 'path/to/file', :w, nl-out => "\r\n";
    $fh.print("some text");
    $fh.print-nl;                                        # \r\n
    $fh.close;

## 79.1.10 method say

    method say(IO::Handle:D: |)

This method is identical to print except that it stringifies its arguments by calling .gist on them and auto-appends a newline, with a call to print-nl, after the final argument.

    my $fh = open 'path/to/file', :w;
    $fh.say(Complex.new(3, 4));        # 3+4i\n
    $fh.close;

## 79.1.11 method read

    method read(IO::Handle:D: Int(Cool:D) $bytes --> Blob)

Binary reading; reads and returns up to $bytes bytes from the filehandle.

## 79.1.12 method readchars

    method readchars(IO::Handle:D: Int(Cool:D) $chars --> Str)

Reading chars; reads and returns up to $chars chars (graphemes) from the filehandle.

## 79.1.13 method write

    method write(IO::Handle:D: Blob:D $buf)

Binary writing; writes $buf to the filehandle. See print to write characters.

## 79.1.14 method seek

    method seek(IO::Handle:D: Int:D $offset, SeekType:D $whence --> True)

Move the file pointer (that is, the position at which any subsequent read or write operations will begin,) to the byte position specified by $offset relative to the location specified by $whence which may be one of:

- SeekFromBeginning

The beginning of the file.

- SeekFromCurrent

The current position in the file.

- SeekFromEnd

The end of the file. Please note that you need to specify a negative offset if you want to position before the end of the file.

## 79.1.15 method tell

    method tell(IO::Handle:D: --> Int)

Return the current position of the file pointer in bytes.

## 79.1.16 method slurp-rest

    multi method slurp-rest(IO::Handle:D: :$bin! --> Buf)
    multi method slurp-rest(IO::Handle:D: :$enc --> Str)

Return the remaining content of the file from the current file position (which may have been set by previous reads or by seek.) If the adverb :bin is provided a Buf will be returned, otherwise the return will be a Str with the optional encoding :enc.

## 79.1.17 method Supply

    multi method Supply(IO::Handle:D: :$size = 65536, :$bin --> Supply)

Returns a Supply that will emit the contents of the handle in chunks. The size of the chunks is determined by the optional :size named parameter and defaults to 64K. The optional :bin named parameter can be specified to indicate binary reading of the contents, rather than character based reading.

## 79.1.18 method path

For a handle opened on a file this returns the IO::Path that represents the file. For the standard I/O handles $*IN, $*OUT and $*ERR it returns a IO::Special object.

    $fh.path;

## 79.1.19 method close

Will close a previously opened filehandle.

    $fh.close;

## 79.1.20 method flush

Will flush the filehandle to disk.

    $fh.flush;

## 79.1.21 method native-descriptor

    method native-descriptor()

This returns a value that the operating system would understand as a "file descriptor" and is suitable for passing to a native function that requires a file descriptor as an argument such as fcntl or ioctl.

## 79.1.22 method opened

    method opened(IO::Handle:D: --> Bool)

Returns True if the handle is open.

## 79.1.23 method t

    method t(IO::Handle:D: --> Bool)

Returns True if the handle is opened to a tty.

# 79.2 Related roles and classes

See also the related role IO and the related class IO::Path.

# 80 class IO::Notification

Asynchronous notification for file and directory changes

    enum FileChangeEvent (:FileChanged(1), :FileRenamed(2));

    class IO::Notification  {
        class Change {
            has $.path;
            has $.event;
        }
        ...
    }

IO::Notification.watch-path($path) produces a Supply of IO::Notification::Change events for a file or directory.

Here is a small example that prints the first ten FileChanged-notifications for the current directory:

    my $finish = Promise.new;
    my $count = 0;

    IO::Notification.watch-path($?FILE).act( -> $change {
        $count++ if $change.event ~~ FileChanged;
        say "($count) $change.path(): $change.event()";
        $finish.keep if $count >= 10;
    });
    await $finish;

The type of the change is very much dependent both on the platform and on specific system calls that were used initiate the change. At this point in time, relying on them seems to be a bad idea.

# 80.1 Methods

## 80.1.1 method watch-path

    method watch-path(IO::Notification: Str() $path, :$scheduler = $*SCHDEULER)

Returns a Supply that emits IO::Notification::Change objects.

If $path is a file, only modifications of that file are reported. If $path is a directory, both modifications to the directory itself (for example permission changes) and to files in the directory (including new files in the directory) are reported.

:$scheduler allows you to specify which thread scheduler is responsible for the notification stream.

# 81 class IO::Path

File or directory path

    class IO::Path is Cool does IO { }

Built-in class for file and directory paths.

Conceptually, an IO::Path object consists of a volume (think C: on windows), a directory, and a basename.

IO::Path supports both purely textual operations, and operations that access the file system.

The current working directory is available as an IO::Path object in $*CWD.

The behavior of IO::Path is dependent on the operating system it runs on; to get reproducible behavior across operating systems, you can use one of its subclasses instead: IO::Path::Unix, IO::Path::Win32, IO::Path::Cygwin, IO::Path::QNX.

The rest of this document silently assumes Unix semantics in its examples, unless when stated otherwise.

TODO: Investigate if the $SPEC = $*SPEC, :$CWD = $*CWD params that a bunch of these routines have in their signature in Rakudo, are "official" Perl 6 API, and if so, document them here in a central place so all the routine documentations can link to it without having to repeat it.

# 81.1 Methods

## 81.1.1 method new

    multi method new(Str:D $path)
    multi method new(:$basename!, :$dirname = '.', :$volume = '')

Creates a new IO::Path object from a path string (which is being parsed for volume, directory name and basename), or from volume, directory name and basename passed as named arguments.

## 81.1.2 method abspath

    method abspath(IO::Path:D: --> Str)

Returns the absolute path as a string.

## 81.1.3 method basename

    method basename(IO::Path:D:)

Returns the basename part of the path object. That is, it returns the name of the file relative to its directory.

    say IO::Path.new("/etc/passwd").basename;   # passwd

## 81.1.4 method extension

    method extension(IO::Path:D:)

Returns the extension (if any) of the path object.

    say IO::Path.new("docs/README.pod").extension;   # pod

## 81.1.5 method dirname

    method dirname(IO::Path:D:)

Returns the directory name portion of the path object. That is, it returns the path excluding the volume and the base name.

    say IO::Path.new("/etc/passwd").dirname;    # /etc

## 81.1.6 method volume

    method volume(IO::Path:D:)

Returns the volume portion of the path object. On Unix system, this is always the empty string.

    say IO::Path::Win32.new("C:\\Windows\\registry.ini").volume;    # C:

## 81.1.7 method parts

    method parts(IO::Path:D:) returns Hash

Returns a hash with the keys dirname, path and volume, and as values the return values of the methods with the same names.

    say IO::Path.new("/etc/passwd").parts.perl
    # ("dirname" => "/etc", "volume" => "", "basename" => "passwd").hash

## 81.1.8 method path

    method path(IO::Path:D: --> Str)

Returns the full path as a string.

## 81.1.9 method Str

    method Str(IO::Path:D:)

Returns the complete text that was used to create the path as a string, whether it was given as a single string or as named arguments.

    say IO::Path.new(basename => "foo", dirname => "/bar").Str  # /bar/foo
    say IO::Path.new("/bar/foo").Str                            # /bar/foo

## 81.1.10 method open

    method open(IO::Path:D: *%opts)

Opens the path as a file; the named options control the mode, and are the same as the open function accepts.

## 81.1.11 method watch

    method watch(IO::Path:D: --> Supply)

Watches the path for modifications. Only implemented in Rakudo with the MoarVM backend at the moment.

## 81.1.12 method is-absolute

    method is-absolute(IO::Path:D: --> Bool:D)

Returns True if the path is an absolute path, and False otherwise.

## 81.1.13 method is-relative

    method is-relative(IO::Path:D: --> Bool:D)

Returns True if the path is a relative path, and False otherwise.

## 81.1.14 method absolute

    method absolute(IO::Path:D: $base = ~$*CWD --> IO::Path:D)

Returns a new IO::Path object that is an absolute path, based on $base.

## 81.1.15 method relative

    method relative(IO::Path:D: $base = ~$*CWD --> IO::Path:D)

Returns a new IO::Path object relative to the $base path.

## 81.1.16 method parent

    method parent(IO::Path:D: --> IO::Path)

Removes the last portion of the path and returns the result as a new IO::Path.

    my $io = IO::Path.new( "/etc/passwd" );
    say $io.parent;                          # "/etc".IO

## 81.1.17 method child

    method child(IO::Path:D: $childname --> IO::Path)

Appends $childname to the end of the path, adding path separators where needed and returns the result as a new IO::Path.

    my $io = IO::Path.new( "/bin" );
    say $io.child('netstat');                # "/bin/netstat".IO

## 81.1.18 method resolve

    method resolve(IO::Path:D: --> IO::Path)

Returns a new IO::Path object with all symbolic links and references to the parent directory (..) resolved. This means that the filesystem is examined for each directory in the path, and any symlinks found are followed.

    # bar is a symlink pointing to "/baz"
    my $io = "foo/./bar/..".IO.resolve;      # now "/" (the parent of "/baz")

NOTE: Currently (May 2016) this method doesn't work correctly on all platforms, e.g. Windows, since it assumes POSIX semantics.

## 81.1.19 routine dir

    sub    dir(Cool $path = '.', Mu :$test = none('.', '..'))
    method dir(IO::Path:D: Mu :$test = none('.', '..'))

Returns the contents of a directory as a lazy list of IO::Path objects representing relative paths, filtered by smart-matching their names against the :test parameter.

Examples:

    # To iterate over the contents of the current directory:
    for dir() -> $file {
        say $file;
    }

    # As before, but include even '.' and '..' which are filtered out by
    # the default :test matcher:
    for dir(test => *) -> $file {
        say $file;
    }

    # To get the names of all .jpg and .jpeg files in ~/Downloads:
    my @jpegs = "%*ENV&lt;HOME>/Downloads".IO.dir(test => /:i '.' jpe?g $/)».Str;

TODO: Turn the following into a FAQ entry, and link to it from here.

An example program that lists all files and directories recursively:

    sub MAIN($dir = '.') {
        my @todo = $dir.IO;
        while @todo {
            for @todo.pop.dir -> $path {
                say $path.Str;
                @todo.push: $path if $path.d;
            }
        }
    }

A lazy way to find the first three files ending in ".p6" recursively starting from the current directory:

    my @stack = '.';
    my $perl-files := gather while ( @stack ) {
        my $current = @stack.pop;
        take $current if ($current.IO.f &amp;&amp; $current.IO.extension ~~ rx:i/p6$/);
        @stack.append(dir($current)>>.path) if $current.IO.d;
    }

    say $perl-files[1..3];

## 81.1.20 routine slurp

    multi method slurp(IO::Path:D: :$bin, :$enc);

Return the file content for this path, like slurp.

## 81.1.21 routine spurt

    multi method spurt(IO::Path:D: Blob $contents, :$bin, |c);
    multi method spurt(IO::Path:D: Cool $contents, :$bin, |c);

Write $contents to this path, like spurt.

## 81.1.22 routine chdir

    sub chdir(Str() $path, :$test = 'r' --> IO::Path);
    multi method chdir(IO::Path:U: $path, :$test = 'r' --> IO::Path);
    multi method chdir(IO::Path:D: Str() $path is copy, :$test = 'r' --> IO::Path);

Alter the processes notion of the current working directory (as found in $*CWD.)

The subroutine and class method forms both change the directory relative to $*CWD if the supplied $path is not absolute. The object method form changes the directory relative to the path of the invocant if $path is not absolute. The optional named parameter test can specify a file test that should be applied to the target path if the operation is successful. The default test is that the directory is readable.

If the directory change is successful then the IO::Path representing the target directory is returned, otherwise it will fail with X::IO::Chdir.

## 81.1.23 routine mkdir

    multi sub mkdir(Int:D $mode, *@dirnames --> @success-dirnames);
    multi sub mkdir($path, $mode = 0o777 --> Bool);
    method    mkdir(IO::Path:D: $mode 0o777 --> Bool)

Creates one or more directories with the permissions specified as an integer (thought still subject to umask).

Throws an exception of type X::IO::Mkdir if the directory cannot be created, except for the *@dirnames form which returns the names of the directories that were successfully created.

## 81.1.24 routine rmdir

    sub    rmdir($dir as IO --> Bool)
    method rmdir(IO::Path:D: --> Bool)

Remove the given directory if it is empty.

Returns True on success. Throws an exception of type X::IO::Rmdir if the directory cannot be removed (e.g. the directory is not empty, or the path is not a directory).

## 81.1.25 routine chmod

    sub    chmod($mode, *@filenames --> @success-filenames)
    method chmod(IO::Path:D: $mode --> Bool)

Changes the POSIX permissions of a file (or in the subroutine form, any number of files) to $mode.

The subroutine form returns the names of the files for which setting the new mode was successful. The method form returns True on success, and otherwise fails with X::IO::Chmod.

The mode is expected as an integer following the standard numeric notation, and is best written as an octal number:

    chmod 0o755, "myfile1", "myfile2"; # make two files executable by the owner
    "myfile".IO.chmod(0o444);          # make a file read-only
    $*CWD.chmod(0o544);                # make the working directory read-only

Make sure you don't accidentally pass the intended octal digits as a decimal number (or string containing a decimal number):

    chmod '0444', 'myfile';            # BAD!!! (interpreted as mode 0o674)

## 81.1.26 routine rename

    method rename(IO::Path:D: $to, :$createonly --> Bool);
    sub    rename($from, $to, :$createonly --> Bool);

Renames a file. Both $from (the file to be renamed) and $to (the destination) can take arbitrary paths. If :createonly is set to True, the rename fails if a file already exists in the destination. Returns True upon success, or fails with X::IO::Rename if the operation could not be completed.

Please use move if a file could not be moved by renaming (usually because the destination is on a different physical storage device).

## 81.1.27 routine copy

    method copy(IO::Path:D: $to, :$createonly)
    sub    copy($from, $to, :$createonly);

Copies a file, as indicated by $from or the invocant, to the destination specified. If :createonly is set to True, copy fails if a file already exists in the destination. Returns True upon success, or an appropriate Failure if the operation could not be completed.

## 81.1.28 routine move

    method move(IO::Path:D: $to, :$createonly)
    sub    move($from, $to, :$createonly);

Moves a file. Both $from (the file to be moved) and $to (the destination) can take arbitrary paths. If :createonly is set to True, the move fails if a file already exists in the destination. Returns True upon success, or fails with X::IO::Move if the operation could not be completed.

Please use rename if a file can be moved by renaming (which is usually possible if the destination is on the same different physical storage device).

## 81.1.29 routine symlink

    method symlink(IO::Path:D: Str $name --> Bool);
    sub    symlink(Str $target, Str $name --> Bool);

Create a new symbolic link named as $target (or the name of the invocant in the method form,) to the existing file named $name.

Both forms will return True on success or fail with X::IO::Symlink if the symbolic link could not be created.

## 81.1.30 routine link

    method link(IO::Path:D: Str $name --> Bool);
    sub    link(Str $target, Str $name --> Bool);

Create a new link named as $target (or the name of the invocant in the method form,) to the existing file named $name.

Both forms will return True on success or fail with X::IO::Link if the link operation could not be performed.

## 81.1.31 routine unlink

    method unlink(IO::Path:D: --> Bool);
    sub    unlink(*@filenames --> @success-filenames);

Delete all specified ordinary files, links, or symbolic links.

The subroutine form returns the names of the files that were successfully deleted. The method form returns True on success, or fails with X::IO::Unlink if the operation could not be completed.

## 81.1.32 method IO

    method IO(IO::Path:D: --> IO::Path)

Returns the invocant.

## 81.1.33 method SPEC

    method SPEC(IO::Path:D: --> IO::Spec)

Returns the IO::Spec object that was (implicitly) specified at object creation time.

    my $io = IO::Path.new("/bin/bash");
    say $io.SPEC;                            # (Unix)
    say $io.SPEC.dir-sep;                    # /

# 81.2 File test operators

-e -f

The -e and -f file test operators do not exist in Perl 6. Use instead :e and :f.

-M -A -C

The -M, -A and -C file test operators do not exist in Perl 6, use instead the modified, accessed and changed methods instead.

:e :d :f :l :r :w :x :s :z :rw :rwx

    :e   Exists
    :d   Directory
    :f   File
    :l   Symbolic link
    :r   Readable
    :w   Writable
    :x   Executable
    :s   Size
    :z   Zero size
    :rw  Readable and writable
    :rwx Readable, writable, and executable

Usage:

If you have a string - a path to something in the filesystem:

    if "path/to/file".IO ~~ :e {
        say 'file exists';
    }

    my $file = "path/to/file";
    if $file.IO ~~ :e {
        say 'file exists';
    }

Instead of the colonpair syntax, you can use method calls too:

    if 'path/to/file'.IO.e {
        say 'file exists';
    }

If you already have an IO object in $file, either by creating one yourself, or by getting it from another subroutine, such as dir, you can write this:

    my $file = "path/to/file".IO;
    if $file ~~ :e {
        say 'file exists';
    }

# 81.3 File timestamp retrieval

There are also 3 methods for fetching the 3 timestamps of a file (inode), on Operating Systems where these are available:

## 81.3.1 method modified

Return an Instant object representing the timestamp when the file was last modified.

    say "path/to/file".IO.modified;   #  e.g. Instant:1424089165

To obtain a human-readable form of the timestamp, call DateTime method on the returned Instant, to convert it into a DateTime object:

    say "path/to/file".IO.modified.DateTime;  # e.g. 2015-02-16T12:18:50Z

## 81.3.2 method accessed

Return an Instant object representing the timestamp when the file was last accessed.

    say "path/to/file".IO.accessed;   #  e.g. Instant:1424353577

To obtain a human-readable form of the timestamp, use a DateTime object:

    say DateTime.new("path/to/file".IO.accessed);  # e.g. 2015-02-19T13:45:42Z

or more readably:

    my $access_instant = "path/to/file".IO.accessed;
    my $access_time = DateTime.new($access_instant);
    say $access_time;         # e.g. 2015-02-19T13:45:42Z

## 81.3.3 method changed

Return an Instant object representing the timestamp when the inode was last changed.

    "path/to/file".IO.changed;        #  e.g. Instant:1424089165

To obtain a human-readable form of the timestamp, use a DateTime object:

    say DateTime.new("path/to/file".IO.changed);  # e.g. 2015-02-16T12:18:50Z

or more readably:

    my $change_instant = "path/to/file".IO.changed;
    my $change_time = DateTime.new($chnge_instant);
    say $change_time;         # e.g. 2015-02-16T12:18:50Z

# 81.4 File permissions retrieval

## 81.4.1 method mode

Return an IntStr object representing the POSIX permissions of a file. The Str part of the result is the octal representation of the file permission, like the form accepted by the chmod(1) utility.

    say ~"path/to/file".IO.mode;        # e.g. '0644'
    say +"path/to/file".IO.mode;        # e.g. 420, where sprintf('%04o', 420) eq '0644'

The result of this can be used in the other methods that take a mode as an argument.

    "path/to/file1".IO.chmod("path/to/file2".IO.mode);  # will change the
                                                        # permissions of file1
                                                        # to be the same as file2

# 81.5 Related roles and classes

See also the related role IO and the related class IO::Handle.

# 82 class IO::Pipe

Buffered inter-process string or binary stream

    class IO::Pipe is IO::Handle { ... }

An IO::Pipe object closely corresponds to a UNIX pipe. It has one end where it consumes string or binary data, and another where it reproduces the same data. It is buffered, so that a write without a read doesn't immediately block.

Pipes can be easily constructed with sub run and Proc.new.

# 82.1 Methods

## 82.1.1 method proc

    method proc(IO::Pipe:) returns Proc:D

Returns the Proc object from which the pipe originates.

# 83 role IO::Socket

Network socket

    role IO::Socket does IO { ... }

IO::Socket contains read and write methods for sockets. It is usually used through IO::Socket::INET.

# 83.1 Methods

## 83.1.1 method recv

    method recv(IO::Socket:D: Cool $elems = Inf, :$bin)

Receive a package and return it, either as a Blob if :bin was passed, or a Str if not. If $elems is supplied, only that many bytes or characters are returned.

Fails if the socket is not connected.

## 83.1.2 method read

    method read(IO::Socket:D: Int(Cool) $bytes)

Reads $bytes bytes from the socket and returns them in a Blob.

Fails if the socket is not connected.

## 83.1.3 method print

    method print(IO::Socket:D: Str(Cool) $string)

Writes the supplied string to the socket, thus sending it to other end of the connection. The binary version is #method write.

Fails if the socket is not connected.

## 83.1.4 method write

    method write(IO::Socket:D: Blob:D $buf)

Writes the supplied buffer to the socket, thus sending it to other end of the connection. The string version is #method print.

Fails if the socket is not connected.

## 83.1.5 method put

    method put(IO::Socket:D: Str(Cool) $string)

Writes the supplied string, with a \n appended to it, to the socket, thus sending it to other end of the connection.

Fails if the socket is not connected.

## 83.1.6 method close

    method close(IO::Socket:D)

Closes the socket.

Fails if the socket is not connected.

## 83.1.7 method native-descriptor

    method native-descriptor()

This returns a value that the operating system would understand as a "socket descriptor" and is suitable for passing to a native function that requires a socket descriptor as an argument such as setsockopt.

# 84 class IO::Socket::Async

Asynchronous TCP socket

    class IO::Socket::Async does IO::Socket { ... }

IO::Socket::Async provides asynchronous TCP sockets, for both the server and the client side.

Here is the equivalent example to that in IO::Socket::INET of a simple echo server that listens on port 3333:

    use v6;

     react {
         whenever IO::Socket::Async.listen('localhost', 3333) -> $conn {
             whenever $conn.Supply(:bin) -> $buf {
                 await $conn.write: $buf
             }
         }
     }

And a client that connects to it, and prints out what the server answers:

    use v6;

     await IO::Socket::Async.connect('localhost', 3333).then( -> $p {
         if $p.status {
             given $p.result {
                 .print('Hello, Perl 6');
                 react {
                     whenever .Supply() -> $v {
                         $v.say;
                         done;
                     }
                 }
                 .close;
             }
         }
     });

Alternatively IO::Socket::Async can send and receive UDP messages. An example server that outputs all the data it receives would be:

    my $socket = IO::Socket::Async.bind-udp('localhost', 3333);

     react {
         whenever $socket.Supply -> $v {
             if $v.chars > 0 {
                 say $v;
             }
         }
     }

And an associated client might be:

    my $socket = IO::Socket::Async.udp();
     await $socket.print-to('localhost', 3333, "Hello, Perl 6!");

# 84.1 Methods

The IO::Socket::Async cannot be constructed directly, either connect or listen (for TCP connections, ) or udp or bind-udp (for UDP data,) should be used to create a client or a server respectively.

## 84.1.1 method connect

    method connect(Str $host, Int $port) returns Promise

Attempts to connect to the TCP server specified by $host and $port, returning a Promise that will either be kept with a connected IO::Socket::Async or broken if the connection cannot be made.

## 84.1.2 method listen

    method listen(Str $host, Int $port) returns Supply

Creates a listening socket on the specified $host and $port, returning a Supply to which the accepted client IO::Socket::Asyncs will be emitted. This Supply should be tapped to process the client connections.

To close the underlying listening socket the Supply should be closed.

## 84.1.3 method udp

    method udp(IO::Socket::Async:U: :$broadcast ) returns IO::Socket::Async

Returns an initialised IO::Socket::Async client object that is configured to send UDP messages using print-to or write-to. The :broadcast adverb will set the SO_BROADCAST option which will allow the socket to send packets to a broadcast address.

## 84.1.4 method bind-udp

    method bind-udp(IO::Socket::Async:U: Str() $host, Int() $port, :$broadcast) returns IO::Socket::Async

This returns an initialised IO::Socket::Async server object that is configured to receive UDP messages sent to the specified $host and $port and is equivalent to listen for a TCP socket. The :broadcast adverb can be specified to allow the receipt of messages sent to the broadcast address.

## 84.1.5 method print

    method print(Str $str) returns Promise

Attempt to send $str on the IO::Socket::Async that will have been obtained indirectly via connect or listen, returning a Promise that will be kept with the number of bytes sent or broken if there was an error sending.

## 84.1.6 method print-to

    method print-to(IO::Socket::Async:D: Str() $host, Int() $port, Str() $str) returns Promise

This is the equivalent of print for UDP sockets that have been created with the udp method, it will try send a UDP message of $str to the specified $host and $port returning a Promise that will be kept when the data is successfully sent or broken if it was unable to send the data. In order to send to a broadcast address the :broadcast flag must have been specified when the socket was created.

## 84.1.7 method write

    method write(Blob $b) returns Promise

Attempt to send the bytes in $b on the IO::Socket::Async that will have been obtained indirectly via connect or listen, returning a Promise that will be kept with the number of bytes sent or broken if there was an error sending.

## 84.1.8 method write-to

    method write-to(IO::Socket::Async:D: Str() $host, Int() $port, Blob $b) returns Promise

This is the equivalent of write for UDP sockets that have been created with the udp method, it will try send a UDP message comprised of the bytes in the Blob $b to the specified $host and $port returning a Promise that will be kept when the data is successfully sent or broken if it was unable to send the data. In order to send to a broadcast address the :broadcast flag must have been specified when the socket was created.

## 84.1.9 method Supply

    method Supply(:$bin, :$buf = buf8.new) returns Supply

Returns a Supply which can be tapped to obtain the data read from the connected IO::Socket::Async as it arrives. By default the data will be emitted as characters, but if the :bin adverb is provided a Buf of bytes will be emitted instead, optionally in this case you can provide your own Buf with the :buf named parameter.

## 84.1.10 method close

    method close()

Close the connected client IO::Socket::Async which will have been obtained from the listen Supply or the connect Promise.

In order to close the underlying listening socket created by listen you can simply close the Supply.

# 85 class IO::Socket::INET

TCP Socket

    class IO::Socket::INET does IO::Socket { ... }

IO::Socket::INET provides TCP sockets, both the server and the client side.

Here is an example of a very simplistic "echo" server that listens on localhost, port 3333:

    use v6;

     my $listen = IO::Socket::INET.new(:listen, :localport(3333));
     loop {
         my $conn = $listen.accept;
         while my $buf = $conn.recv(:bin) {
             $conn.write: $buf;
         }
         $conn.close;
     }

And a client that connects to it, and prints out what the server answers:

    use v6;

     my $conn = IO::Socket::INET.new(:host&lt;localhost>, :port(3333));
     $conn.print: 'Hello, Perl 6';
     say $conn.recv;
     $conn.close;

# 85.1 Methods

## 85.1.1 method new

    multi method new(
            :$host,
            :$port,
            :$family = 2,
            :$encoding = 'utf-8',
            :$nl-in = "\r\n",
        ) returns IO::Socket::INET:D
    multi method new(
            :$localhost,
            :$localport,
            :$family = 2,
            :$listen,
            :$encoding = 'utf-8',
            :$nl-in = "\r\n",
        ) returns IO::Socket::INET:D

Creates a new socket.

If :$listen is True, creates a new socket that listen on $localhost (which can be an IP address or a domain name) on port $localport. Otherwise it opens a connection to $host on port $port.

$family defaults to 2 for IPv4, and can be set to 3 for IPv6.

For text operations (such as #method lines and #method get), $encoding specifies the encoding, and $nl-in determines the character(s) that separate lines.

# 85.2 Methods

## 85.2.1 method get

    method get()

Reads a line from the socket and returns it. Returns the Str type object on end-of-file (EOF).

## 85.2.2 method lines

    method lines()

Returns a lazy list of lines read from the socket.

## 85.2.3 method accept

    method accept()

In listen/server mode, waits for a new incoming connection, and returns it.

# 86 class IO::Spec

Platform specific operations on file and directory paths

    class IO::Spec { }

Objects of this class are not used directly but as a sub-class specific to the platform perl is running on via the $*SPEC variable which will contain an object of the appropriate type.

The sub-classes are documented separately, with the platform-specific differences documented in IO::Spec::Cygwin, IO::Spec::QNX, IO::Spec::Unix and IO::Spec::Win32.

# 86.1 Methods

## 86.1.1 method canonpath

    method canonpath(IO::Spec:D: Str $patharg, Str :$parent) returns Str

TODO

## 86.1.2 method dir-sep

    method dir-sep(IO::Spec:D:) returns Str

TODO

## 86.1.3 method curdir

    method curdir(IO::Spec:D:) returns Str

TODO

## 86.1.4 method updir

    method updir(IO::Spec:D:) returns Str

TODO

## 86.1.5 method curupdir

    method curupdir(IO::Spec:D:) returns Junction

TODO

## 86.1.6 method rootdir

    method rootdir(IO::Spec:D:) returns Str

TODO

## 86.1.7 method devnull

    method devnull(IO::Spec:D:) returns Str

TODO

## 86.1.8 method basename

    method basename(IO::Spec:D: Str $path) returns Str

TODO

## 86.1.9 method extension

    method extension(IO::Spec:D: Str $path) returns Str

TODO

## 86.1.10 method tmpdir

    method tmpdir(IO::Spec:D:) returns IO::Path

TODO

## 86.1.11 method is-absolute

    method is-absolute(IO::Spec:D: Str $file ) returns Bool

TODO

## 86.1.12 method path

    method path(IO::Spec:D:) returns Str

TODO

## 86.1.13 method splitpath

    method splitpath(IO::Spec:D: Str $path, Bool :$nofile = False )

TODO

## 86.1.14 method split

    method split(IO::Spec:D: Cool:D $path is copy )

TODO

## 86.1.15 method join

    method join(IO::Spec:D: $, $dirname, $file)

TODO

## 86.1.16 method catpath

    method catpath(IO::Spec:D:  $, $dirname, $file )

TODO

## 86.1.17 method catdir

    method catdir(IO::Spec:D: *@parts )

TODO

## 86.1.18 method splitdir

    method splitdir(IO::Spec:D: Str $path )

TODO

## 86.1.19 method catfile

    method catfile(IO::Spec:D: *@parts )

TODO

## 86.1.20 method abs2rel

    method abs2rel(IO::Spec:D: Str $path is copy, Str $base is copy = Str )

TODO

## 86.1.21 method rel2abs

    method rel2abs(IO::Spec:D Str $path, Str $base? is copy)

TODO

# 87 class IO::Spec::Cygwin

Platform specific operations on file and directory paths for Cygwin

    class IO::Spec::QNX is IO::Spec { }

This sub-class of IO::Spec will be available from the $*SPEC variable for a perl running on Cygwin .

# 87.1 Methods

## 87.1.1 method canonpath

    method canonpath(IO::Spec:D: Str $patharg, Str :$parent) returns Str

TODO

## 87.1.2 method dir-sep

    method dir-sep(IO::Spec:D:) returns Str

TODO

## 87.1.3 method curdir

    method curdir(IO::Spec:D:) returns Str

TODO

## 87.1.4 method updir

    method updir(IO::Spec:D:) returns Str

TODO

## 87.1.5 method curupdir

    method curupdir(IO::Spec:D:) returns Junction

TODO

## 87.1.6 method rootdir

    method rootdir(IO::Spec:D:) returns Str

TODO

## 87.1.7 method devnull

    method devnull(IO::Spec:D:) returns Str

TODO

## 87.1.8 method basename

    method basename(IO::Spec:D: Str $path) returns Str

TODO

## 87.1.9 method extension

    method extension(IO::Spec:D: Str $path) returns Str

TODO

## 87.1.10 method tmpdir

    method tmpdir(IO::Spec:D:) returns IO::Path

TODO

## 87.1.11 method is-absolute

    method is-absolute(IO::Spec:D: Str $file ) returns Bool

TODO

## 87.1.12 method path

    method path(IO::Spec:D:) returns Str

TODO

## 87.1.13 method splitpath

    method splitpath(IO::Spec:D: Str $path, Bool :$nofile = False )

TODO

## 87.1.14 method split

    method split(IO::Spec:D: Cool:D $path is copy )

TODO

## 87.1.15 method join

    method join(IO::Spec:D: $, $dirname, $file)

TODO

## 87.1.16 method catpath

    method catpath(IO::Spec:D:  $, $dirname, $file )

TODO

## 87.1.17 method catdir

    method catdir(IO::Spec:D: *@parts )

TODO

## 87.1.18 method splitdir

    method splitdir(IO::Spec:D: Str $path )

TODO

## 87.1.19 method catfile

    method catfile(IO::Spec:D: *@parts )

TODO

## 87.1.20 method abs2rel

    method abs2rel(IO::Spec:D: Str $path is copy, Str $base is copy = Str )

TODO

## 87.1.21 method rel2abs

    method rel2abs(IO::Spec:D Str $path, Str $base? is copy)

TODO

# 88 class IO::Spec::QNX

Platform specific operations on file and directory paths QNX

    class IO::Spec::QNX is IO::Spec { }

This sub-class of IO::Spec specific to QNX will be available via $*SPEC if the perl is running on QNX.

# 88.1 Methods

## 88.1.1 method canonpath

    method canonpath(IO::Spec:D: Str $patharg, Str :$parent) returns Str

TODO

## 88.1.2 method dir-sep

    method dir-sep(IO::Spec:D:) returns Str

TODO

## 88.1.3 method curdir

    method curdir(IO::Spec:D:) returns Str

TODO

## 88.1.4 method updir

    method updir(IO::Spec:D:) returns Str

TODO

## 88.1.5 method curupdir

    method curupdir(IO::Spec:D:) returns Junction

TODO

## 88.1.6 method rootdir

    method rootdir(IO::Spec:D:) returns Str

TODO

## 88.1.7 method devnull

    method devnull(IO::Spec:D:) returns Str

TODO

## 88.1.8 method basename

    method basename(IO::Spec:D: Str $path) returns Str

TODO

## 88.1.9 method extension

    method extension(IO::Spec:D: Str $path) returns Str

TODO

## 88.1.10 method tmpdir

    method tmpdir(IO::Spec:D:) returns IO::Path

TODO

## 88.1.11 method is-absolute

    method is-absolute(IO::Spec:D: Str $file ) returns Bool

TODO

## 88.1.12 method path

    method path(IO::Spec:D:) returns Str

TODO

## 88.1.13 method splitpath

    method splitpath(IO::Spec:D: Str $path, Bool :$nofile = False )

TODO

## 88.1.14 method split

    method split(IO::Spec:D: Cool:D $path is copy )

TODO

## 88.1.15 method join

    method join(IO::Spec:D: $, $dirname, $file)

TODO

## 88.1.16 method catpath

    method catpath(IO::Spec:D:  $, $dirname, $file )

TODO

## 88.1.17 method catdir

    method catdir(IO::Spec:D: *@parts )

TODO

## 88.1.18 method splitdir

    method splitdir(IO::Spec:D: Str $path )

TODO

## 88.1.19 method catfile

    method catfile(IO::Spec:D: *@parts )

TODO

## 88.1.20 method abs2rel

    method abs2rel(IO::Spec:D: Str $path is copy, Str $base is copy = Str )

TODO

## 88.1.21 method rel2abs

    method rel2abs(IO::Spec:D Str $path, Str $base? is copy)

TODO

# 89 class IO::Spec::Unix

Platform specific operations on file and directory paths for POSIX

    class IO::Spec::Unix is IO::Spec  { }

On object of this type is available via the variable $*SPEC if the perl is running on a Unix-like platform.

# 89.1 Methods

## 89.1.1 method canonpath

    method canonpath(IO::Spec:D: Str $patharg, Str :$parent) returns Str

TODO

## 89.1.2 method dir-sep

    method dir-sep(IO::Spec:D:) returns Str

TODO

## 89.1.3 method curdir

    method curdir(IO::Spec:D:) returns Str

TODO

## 89.1.4 method updir

    method updir(IO::Spec:D:) returns Str

TODO

## 89.1.5 method curupdir

    method curupdir(IO::Spec:D:) returns Junction

TODO

## 89.1.6 method rootdir

    method rootdir(IO::Spec:D:) returns Str

TODO

## 89.1.7 method devnull

    method devnull(IO::Spec:D:) returns Str

TODO

## 89.1.8 method basename

    method basename(IO::Spec:D: Str $path) returns Str

TODO

## 89.1.9 method extension

    method extension(IO::Spec:D: Str $path) returns Str

TODO

## 89.1.10 method tmpdir

    method tmpdir(IO::Spec:D:) returns IO::Path

TODO

## 89.1.11 method is-absolute

    method is-absolute(IO::Spec:D: Str $file ) returns Bool

TODO

## 89.1.12 method path

    method path(IO::Spec:D:) returns Str

TODO

## 89.1.13 method splitpath

    method splitpath(IO::Spec:D: Str $path, Bool :$nofile = False )

TODO

## 89.1.14 method split

    method split(IO::Spec:D: Cool:D $path is copy )

TODO

## 89.1.15 method join

    method join(IO::Spec:D: $, $dirname, $file)

TODO

## 89.1.16 method catpath

    method catpath(IO::Spec:D:  $, $dirname, $file )

TODO

## 89.1.17 method catdir

    method catdir(IO::Spec:D: *@parts )

TODO

## 89.1.18 method splitdir

    method splitdir(IO::Spec:D: Str $path )

TODO

## 89.1.19 method catfile

    method catfile(IO::Spec:D: *@parts )

TODO

## 89.1.20 method abs2rel

    method abs2rel(IO::Spec:D: Str $path is copy, Str $base is copy = Str )

TODO

## 89.1.21 method rel2abs

    method rel2abs(IO::Spec:D Str $path, Str $base? is copy)

TODO

# 90 class IO::Spec::Win32

Platform specific operations on file and directory paths for Windows

    class IO::Spec::Win32 is IO::Spec { }

Objects of this class are not used directly but as a sub-class specific to the platform perl is running on via the $*SPEC variable which will contain an object of the appropriate type.

# 90.1 Methods

## 90.1.1 method canonpath

    method canonpath(IO::Spec:D: Str $patharg, Str :$parent) returns Str

TODO

## 90.1.2 method dir-sep

    method dir-sep(IO::Spec:D:) returns Str

TODO

## 90.1.3 method curdir

    method curdir(IO::Spec:D:) returns Str

TODO

## 90.1.4 method updir

    method updir(IO::Spec:D:) returns Str

TODO

## 90.1.5 method curupdir

    method curupdir(IO::Spec:D:) returns Junction

TODO

## 90.1.6 method rootdir

    method rootdir(IO::Spec:D:) returns Str

TODO

## 90.1.7 method devnull

    method devnull(IO::Spec:D:) returns Str

TODO

## 90.1.8 method basename

    method basename(IO::Spec:D: Str $path) returns Str

TODO

## 90.1.9 method extension

    method extension(IO::Spec:D: Str $path) returns Str

TODO

## 90.1.10 method tmpdir

    method tmpdir(IO::Spec:D:) returns IO::Path

TODO

## 90.1.11 method is-absolute

    method is-absolute(IO::Spec:D: Str $file ) returns Bool

TODO

## 90.1.12 method path

    method path(IO::Spec:D:) returns Str

TODO

## 90.1.13 method splitpath

    method splitpath(IO::Spec:D: Str $path, Bool :$nofile = False )

TODO

## 90.1.14 method split

    method split(IO::Spec:D: Cool:D $path is copy )

TODO

## 90.1.15 method join

    method join(IO::Spec:D: $, $dirname, $file)

TODO

## 90.1.16 method catpath

    method catpath(IO::Spec:D:  $, $dirname, $file )

TODO

## 90.1.17 method catdir

    method catdir(IO::Spec:D: *@parts )

TODO

## 90.1.18 method splitdir

    method splitdir(IO::Spec:D: Str $path )

TODO

## 90.1.19 method catfile

    method catfile(IO::Spec:D: *@parts )

TODO

## 90.1.20 method abs2rel

    method abs2rel(IO::Spec:D: Str $path is copy, Str $base is copy = Str )

TODO

## 90.1.21 method rel2abs

    method rel2abs(IO::Spec:D Str $path, Str $base? is copy)

TODO

# 91 class IO::Special

Represent a Standard I/O device

This provides a similar interface for the special standard input and output handles $*IN, $*OUT and $*ERR to that of IO::Path for regular files. It is typically returned by the path method of those handles so that they can be used interchangeably with the handles of regular files.

# 91.1 Methods

## 91.1.1 method new

    method new(:$!what!)

The constructor has a single required named argument what that will be '<STDIN>', '<STDOUT>' or '<STDERR>' as appropriate. It is unlikely that you will ever need to construct one of these objects yourself however as it will be done for you when the special handles are initialised.

## 91.1.2 method WHICH

    method WHICH(IO::Special:D:) returns Str

This returns a string which identifies the object.

## 91.1.3 method Str

    method Str(IO::Special:D:)

This returns '<STDIN>', '<STDOUT>' or '<STDERR>' as appropriate.

## 91.1.4 method IO

    method IO(IO::Special:D:) returns IO::Special

This returns the IO::Special object, it is provided for conformance to the IO::Path interface.

## 91.1.5 method e

    method e(IO::Special:D:) returns Bool

The 'exists' file test operator, always returns True.

## 91.1.6 method d

    method d(IO::Special:D:) returns Bool

The 'directory' file test operator, always returns False.

## 91.1.7 method f

    method f(IO::Special:D:) returns Bool

The 'file' file test operator, always returns False.

## 91.1.8 method s

    method s(IO::Special:D:) returns Int

The 'size' file test operator, always returns 0.

## 91.1.9 method l

    method l(IO::Special:D:) returns Bool

The 'symbolic links' file test operator, always returns False.

## 91.1.10 method r

    method r(IO::Special:D:) returns Bool

The 'read access' file test operator, returns True if this is the standard input handle, False otherwise.

## 91.1.11 method w

    method w(IO::Special:D:) returns Bool

The 'write access' file test operator, returns True if this is the standard output or standard error handle, False if it is the standard input.

## 91.1.12 method x

    method x(IO::Special:D:) returns Bool

The 'execute access' file test operator, always returns False.

## 91.1.13 method modified

    method modified(IO::Special:D:) returns Instant

The last modified time always returns an undefined Instant.

## 91.1.14 method accessed

    method accessed(IO::Special:D:) returns Instant

The last accessed time always returns an undefined Instant

## 91.1.15 method changed

    method changed(IO::Special:D:) returns Instant

The last changed time always returns an undefined Instant

## 91.1.16 method mode

    method mode(IO::Special:D:) returns Nil

The mode always returns Nil

# 92 class Instant

Specific moment in time

    class Instant is Cool does Real { }

An Instant is a particular moment in time measured in atomic seconds, with fractions. It is not tied to or aware of any epoch.

An Instant can be used to create a DateTime object set to that Instant. The pseudo-constant now returns the current time as an Instant.

Basic math is defined for Instants (as well as Durations). Adding an Instant to a Duration returns another Instant. Subtracting two Instants will yield a Duration. Adding two Instants is explicitly disallowed. All other operations with Instants are undefined.

# 92.1 Methods

## 92.1.1 method from-posix

    method from-posix($posix, Bool $prefer-leap-second = False)

Converts the POSIX timestamp $posix to an Instant. If $prefer-leap-second is True, the return value will be the first of the two possible seconds in the case of a leap second.

    say DateTime.new(Instant.from-posix(915148800, True));  # 1998-12-31T23:59:60Z
    say DateTime.new(Instant.from-posix(915148800));        # 1999-01-01T00:00:00Z

## 92.1.2 method to-posix

    method to-posix()

Converts the invocant to a POSIX timestamp and returns a two element list containing the POSIX timestamp and a Bool. It is the inverse of #method from-posix, except that the second return value is True if *and only if* this Instant is in a leap second.

    say DateTime.new("1999-01-01T00:00:00Z").Instant.to-posix  # (915148800 False)
    say DateTime.new('1998-12-31T23:59:60Z').Instant.to-posix; # (915148800 True)

## 92.1.3 method Date

Defined as:

    method Date(Instant:D:) returns Date:D

Returns a Date object set to the date of the invocant.

    # the results given will vary from system to system
    my $i = "/etc/passwd".IO.modified;
    say $i;                                       # Instant:1451489025.878018
    say $i.Date;                                  # 2015-12-30

# 93 class Int

Integer (arbitrary-precision)

    class Int is Cool does Real { ... }

Int objects store integral numbers of arbitrary size. Ints are immutable.

There are two main syntax forms for Int literals

    123         # Int in decimal notation
    :16&lt;BEEF>   # Int in radix notations

For your convenience common radix forms come with a prefix shortcut.

    say so :2&lt;11111111> == 0b11111111 == :8&lt;377> == 0o377 == 255 == 0d255 == :16&lt;ff> == 0xff;
    # OUTPUT«True␤»

All forms allow underscores between any two digits which can serve as visual separators, but don't carry any meaning:

    5_00000       # five Lakhs
    500_000       # five hundred thousand
    0xBEEF_CAFE   # a strange place
    :2&lt;1010_1010> # 0d170

# 93.1 Methods

## 93.1.1 routine chr

Defined as:

    multi sub    chr(Int:D ) returns Str:D
    multi method chr(Int:D:) returns Str:D

Usage:

    chr INTEGER
    INTEGER.chr

Returns a one-character string, by interpreting the integer as a Unicode codepoint number and converting it to the corresponding character.

Example:

    65.chr  # returns "A"
    196.chr # returns "Ä"

## 93.1.2 routine expmod

Defined as:

    multi sub    expmod(Int:D: Int $y, Int $mod) returns Int:D
    multi method expmod(Int:D: Int $y, Int $mod) returns Int:D

Usage:

    expmod(INTEGER, POWER, MODULUS)
    INTEGER.expmod(POWER, MODULUS)

Returns the given Int raised to the $y power within modulus $mod.

    say expmod(4, 2, 5);    # 1
    say 7.expmod(2, 5);     # 4

## 93.1.3 method polymod

Defined as:

    method polymod(Int:D: +@mods)

Usage:

    INTEGER.polymod(LIST)

Returns a sequence of mod results corresponding to the divisors in @mods. The divisors are given from smallest "unit" to the largest (e.g. 60 seconds per minute, 60 minutes per hour) and the results are returned in the same way: from smallest to the largest (5 seconds, 4 minutes).

Returns one more item in the result than the number of given divisors. If the divisors are given as a lazy list, runs until the remainder is 0 or the list of divisors is exhausted. All divisors must be Ints, unless the method is called on a non-Int number.

    my $seconds = 1 * 60*60*24 # days
                + 3 * 60*60    # hours
                + 4 * 60       # minutes
                + 5;           # seconds

    say $seconds.polymod(60, 60);              # (5 4 27)
    say $seconds.polymod(60, 60, 24);          # (5 4 3 1)

    say 120.polymod:      1, 10, 10², 10³, 10⁴;  # (0 0 12 0 0 0)
    say 120.polymod: lazy 1, 10, 10², 10³, 10⁴;  # (0 0 12)
    say 120.polymod:      1, 10, 10² … ∞;        # (0 0 12)

    say ⅔.polymod(⅓);                          # (0 2)
    say 5.Rat.polymod(.3, .2);                 # (0.2 0 80)

To illustrate how the Int, non-lazy version of polymod works, consider this code that implements it:

    my $seconds = 2 * 60*60*24 # days
                + 3 * 60*60    # hours
                + 4 * 60       # minutes
                + 5;           # seconds

    my @pieces;
    for 60, 60, 24 -> $divisor {
        @pieces.push: $seconds mod $divisor;
        $seconds div= $divisor
    }
    @pieces.push: $seconds;

    say @pieces; # [5 4 3 2]

For a more detailed discussion, see this blog post

## 93.1.4 routine is-prime

Defined as:

    multi sub    is-prime (Int:D $number) returns Bool:D
    multi method is-prime (Int:D:) returns Bool:D

Usage:

    is-prime INTEGER
    INTEGER.is-prime

Returns True if this Int is known to be a prime, or is likely to be a prime based on a probabilistic Miller-Rabin test.

Returns False if this Int is known not to be a prime.

    say 2.is-prime;         # True
    say is-prime(9);        # False

## 93.1.5 routine lsb

Defined as:

    multi method lsb(Int:D:)
    multi sub    lsb(Int:D)

Usage:

    lsb INTEGER
    INTEGER.lsb

Returns Nil if the number is 0. Otherwise returns the zero-based index from the right of the first 1 in the binary representation of the number.

    say 0b01011.lsb;        # 0
    say 0b01010.lsb;        # 1
    say 0b10100.lsb;        # 2
    say 0b01000.lsb;        # 3
    say 0b10000.lsb;        # 4

## 93.1.6 routine msb

Defined as:

    multi method msb(Int:D:)
    multi sub    msb(Int:D)

Usage:

    msb INTEGER
    INTEGER.msb

Returns Nil if the number is 0. Otherwise returns the zero-based index from the left of the first 1 in the binary representation of the number.

    say 0b00001.msb;        # 0
    say 0b00011.msb;        # 1
    say 0b00101.msb;        # 2
    say 0b01010.msb;        # 3
    say 0b10011.msb;        # 4

## 93.1.7 routine unival

Defined as:

    multi sub    unival(Int:D)  returns Numeric
    multi method unival(Int:D:) returns Numeric

Usage:

    unival INTEGER
    INTEGER.unival

Returns the number represented by the Unicode codepoint with the given integer number, or NaN if it does not represent a number.

    say ord("¾").unival;    # 0.75
    say 190.unival;         # 0.75
    say unival(65);         # NaN

# 93.2 Operators

## 93.2.1 infix div

    multi sub infix:&lt;div>(Int:D, Int:D) returns Int:D

Does an integer division, rounded down.

# 94 class IntStr

Dual Value Integer and String

    class IntStr is Int is Str

The dual value types (often referred to as allomorphs) allow for the representation of a value as both a string and a numeric type, typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some quoting constructs:

    my $f = &lt;42>; say $f.WHAT; # (IntStr)

An IntStr can be used interchangeably where one might use a Str or an Int :

    my $f = &lt;42>;
    my $i = $f + 1;
    my $s = $f ~ " and a bit";

# 94.1 Methods

## 94.1.1 method new

    method new(Int $i, Str $s)

The constructor requires both the Int and the Str value, when constructing one directly the values can be whatever is required:

    my $f = IntStr.new(42, "forty two");
    say +$f; # -> 42
    say ~$f; # -> "forty two"

## 94.1.2 method Numeric

    method Numeric

The numeric coercion is applied when the IntStr is used in a numeric context, such as a numeric comparison or smart match against a numeric value. It will return the Int value.

## 94.1.3 method Int

    method Int

Returns the integer value of the IntStr.

## 94.1.4 method Str

Returns the string value of the IntStr.

# 94.2 Operators

## 94.2.1 infix cmp

    multi sub infix:&lt;cmp>(IntStr:D $a, IntStr:D $b)

Compare two IntStr objects. The comparison is done on the Int value first and then on the Str value. If you want to compare in a different order then you would coerce to a Int or Str value first:

    my $f = IntStr.new(42, "smaller");
    my $g = IntStr.new(43, "larger");
    say $f cmp $g;          # Less
    say $f.Str cmp $g.Str;  # More

# 95 role Iterable

Interface for container objects that can be iterated over

    role Iterable { }

Iterable serves as an API for objects that can be iterated with the for construct and related iteration constructs, like hyper operators.

Iterable objects nested in other Iterable objects (but not within scalar containers) flatten in certain contexts, for example when passed to a slurpy parameter (*@a), or on explicit calls to flat.

Its important aspect is a method stub for iterator.

    role DNA does Iterable {
        method iterator(){ self.comb.iterator }
    };

    my @a does DNA = 'GAATCC';
    .say for @a; # OUTPUT«G␤G␤A␤T␤C␤C␤»

# 95.1 Methods

## 95.1.1 method iterator

Defined as:

    method iterator() returns Iterator:D { ... }

Method stub that ensures all classes doing the Iterable role have a method iterator.

It is supposed to return an Iterator.

## 95.1.2 method flat

Defined as:

    method flat() return Iterable

Usage:

    ITERABLE.flat

Returns another Iterable that flattens out all iterables that the first one returns.

For example

    say (&lt;a b>, 'c').elems;         # 2
    say (&lt;a b>, 'c').flat.elems;    # 3

because <a b> is a List and thus iterable, so (<a b>, 'c').flat returns ('a', 'b', 'c'), which has three elems.

Note that the flattening is recursive, so ((("a", "b"), "c"), "d").flat returns ("a", "b", "c", "d"), but it does not flatten itemized sublists:

    say ($('a', 'b'), 'c').perl;    # ($("a", "b"), "c").Seq

## 95.1.3 method lazy

Defined as:

    method lazy() returns Iterable

Usage:

    ITERABLE.lazy

Returns a lazy iterable wrapping the invocant.

## 95.1.4 method hyper

Defined as:

    method hyper(Int(Cool) :$batch = 64, Int(Cool) :$degree = 4)
                returns Iterable

Usage:

    ITERABLE.hyper(BATCH?, DEGREE?)

Returns another Iterable that is potentially iterated in parallel, with a given batch size and degree of parallelism.

The order of elements is preserved.

## 95.1.5 method race

Defined as:

    method race(Int(Cool) :$batch = 64, Int(Cool) :$degree = 4)
                returns Iterable

Usage:

    ITERABLE.race(BATCH?, DEGREE?)

Returns another Iterable that is potentially iterated in parallel, with a given batch size and degree of parallelism (number of parallel workers).

Unlike hyper, race does not preserve the order of elements.

# 96 role Iterator

Generic API for producing a sequence of values

    constant IterationEnd
    role Iterator { }

A Iterator is an object that can generate or provide elements of a sequence. Users usually don't have to care about iterators, their usage is hidden behind iteration APIs such as for @list { }, map, grep and list indexing with .[$idx].

Iterators generally only allow one iteration over the sequence; afterwards they are exhausted.

The main API is the pull-one method, which either returns the next value, or the sentinel value IterationEnd if no more elements are available. Each class implementing Iterator must provide a pull-one method. All other Iterator API methods can be implemented in terms of pull-one, but also overridden for performance reasons.

Note: The only valid use of the sentinel value IterationEnd in a program is identity comparison (using =:=) with the result of a method in the iterator API. Any other behavior is undefined and implementation dependent.

# 96.1 Methods

## 96.1.1 method pull-one

Defined as:

    method pull-one(Iterator:D:) returns Mu { ... }

Usage:

    ITERATOR.pull-one

This method stub ensures that classes implementing the Iterator role provide a method named pull-one.

The pull-one method is supposed to return the next value if available, or the sentinel value IterationEnd if no more elements are available.

## 96.1.2 method push-exactly

Defined as:

    method push-exactly(Iterator:D: $target, int $count) returns Mu

Usage:

    ITERATOR.push-exactly(TARGET, COUNT)

Produces $count elements, and for each of them, calls $target.push($value).

If fewer than $count elements are available from the iterator, it returns the sentinel value IterationEnd. Otherwise it returns $count.

## 96.1.3 method push-at-least

Defined as:

    method push-at-least(Iterator:D: $target, int $count) returns Mu

Usage:

    ITERATOR.push-at-least(TARGET, COUNT)

Produces at least $count elements, and for each of them, calls $target.push($value).

If fewer than $count elements are available from the iterator, it returns the sentinel value IterationEnd. Otherwise it returns $count.

Iterators with side effects should produce exactly $count elements; iterators without side effects (such as Range iterators) can produce more elements to achieve better performance.

## 96.1.4 method push-all

Defined as:

    method push-all(Iterator:D: $target)

Usage:

    ITERATOR.push-all(TARGET)

Produces all elements from the iterator and pushes them to $target.

The fallback is implemented in terms of repeated push-at-least with a large $count.

## 96.1.5 method push-until-lazy

Defined as:

    method push-until-lazy(Iterator:D: $target) returns Mu

Usage:

    ITERATOR.push-until-lazy(TARGET)

Produces values until it considers itself to be lazy, and pushes them onto $target.

This matters mostly for iterators that have other iterators embedded, some of which might be lazy, while others aren't.

## 96.1.6 method is-lazy

Defined as:

    method is-lazy(Iterator:D:) returns Bool:D

Usage:

    ITERATOR.is-lazy

Returns True for iterators that consider themselves lazy, and False otherwise.

Built-in operations that know that they can produce infinitely many values return True here, for example (1..6).roll(*).

## 96.1.7 method count-only

Defined as:

    method count-only(Iterator:D:) returns int

Usage:

    ITERATOR.count-only

Produces and discards all elements until it returns the end of the iteration, and returns the number of elements produced. This is useful to reduce memory usage in scenarios such as open($file).lines.elems.

## 96.1.8 method sink-all

Defined as:

    method sink-all(Iterator:D:)

Usage:

    ITERATOR.sink-all

Exhausts the iterator (while discarding generated elements) purely for the side effects of the iteration.

# 97 class Junction

Logical superposition of values

    class Junction is Mu { }

A junction is an unordered composite value of zero or more values. Junctions autothread over many operations, which means that the operation is carried out for each junction element (also known as eigenstate), and the result is junction of the return values of all those operators.

Junctions collapse into a single value in boolean context. The semantics depend on the junction type, which can be all, any, one or none.

type | constructor | operator | True if ...
--- | --- | --- | ---
all | all | & | no value evaluates to False
any | any | | | at least one value evaluates to True
one | one | ^ | exactly one value evaluates to True
none | none |  | no value evaluates to True

Autothreading happens when a junction is bound to a parameter of a code object that doesn't accept values of type Junction. Instead of producing an error, the signature binding is repeated for each value of the junction.

Example:

    my $j = 1|2;
    if 3 == $j + 1 {
        say 'yes';
    }

First autothreads over the infix:<+> operator, producing the Junction 2|3. The next autothreading step is over infix:<==> , which produces False|True. The if conditional evaluates the junction in boolean context, which collapses it to True. So the code prints yes\n.

Note that the compiler is allowed to parallelize and short-circuit autothreading (and Junction behavior in general), so it is usually an error to autothread junctions over code with side effects.

Junctions are meant to be used as matchers in boolean context; introspection of junctions is not supported. If you feel the urge to introspect a junction, use a Set or a related type instead.

Usage examples:

    my @bool_or_int = grep Bool|Int, @list;

    sub is_prime(Int $x) returns Bool {
        # 'so' is for boolean context
        so $x %% none(2..$x.sqrt);
    }
    my @primes_ending_in_1 = grep &amp;is_prime &amp; / 1$ /, 2..100;
    say @primes_ending_in_1;        # 11 31 41 61 71

    my @exclude = &lt;~ .git>;
    for dir(".") { say .Str if .Str.ends-with(none @exclude) }

Special care should be taken when using all with arguments that may produce an empty list:

    my @a = ();
    so all(@a) # True, because there are 0 False's

To express "all, but at least one", you can use @a && all(@a)

    say so @a &amp;&amp; all(@a);   # False

Negated operators are special-cased when it comes to autothreading. $a !op $b is rewritten internally as !($a op $b). The outer negation collapses any junctions, so the return value always a plain Bool.

    my $word = 'yes';
    my @negations = &lt;no none never>;
    if $word !eq any @negations {
        say '"yes" is not a negation';
    }

Note that without this special-casing, an expression like $word ne any @words would always evaluate to True for non-trivial lists on one side.

For this purpose, infix:<ne> counts as a negation of infix:<eq> .

In general it is more readable to use a positive comparison operator and a negated junction:

    my $word = 'yes';
    my @negations = &lt;no none never>;
    if $word eq none @negations {
        say '"yes" is not a negation';
    }

# 97.1 See Also

- http://perlgeek.de/blog-en/perl-5-to-6/08-junctions.html

- http://perl6maven.com/perl6-is-a-value-in-a-given-list-of-values

- https://perl6advent.wordpress.com/2009/12/13/day-13-junctions/

# 98 class Label

Tagged location in the source code

    class Label { ... }

In Perl 6, you can give for example loops a label, and use it to control that loop (instead of the inner-most loop).

    USERS:          # the label
    for @users -> $u {
        for $u.pets -> $pet {
            # usage of a label
            next USERS if $pet.barks;
        }
        say "None of {$u}'s pets barks";
    }
    say USERS.^name;        # Label

Those label are objects of type Label.

# 98.1 Methods

## 98.1.1 method next

Defined as:

    method next(Label:)

Usage:

    next LABEL

Begin the next iteration of the loop associated with the label.

## 98.1.2 method last

Defined as:

    method last(Label:)

Usage:

    last LABEL

Terminate the execution of the loop associated with the label.

# 99 class List

Sequence of values

    my class List is Iterable does Positional { .. }

List stores items sequentially and potentially lazily.

Indexes into lists and arrays start at 0 by default.

You can assign to list elements if they are containers. Use Arrays to have every value of the list stored in a container.

# 99.1 Items, Flattening and Sigils

In Perl 6, assigning a List to a scalar variable does not lose information. The difference is that iteration generally treats a list (or any other list-like object, like a Seq or an Array) inside a scalar as a single element, as long as it's part of another .

    my @a = 1, 2, 3;
    for @a { }      # three iterations

    my $s = @a;
    for $s { }      # one iteration
    for @a.item { } # one iteration
    for $s.list { } # three iterations

Lists generally don't interpolate (flatten) into other lists, except when they are not itemized, and the single argument to an operation such as append:

    my @a = 1, 2, 3;
    my @nested = @a, @a;           # two elements
    my @flat = flat @a, @a;        # six elements, with explicit flat
    my @b = 'a', 'b';
    @b.append: @a;                 # @b now has 5 elements, because @a
                                   # is the sole argument to append
    my @c = 'a', 'b';
    @c.append: $@a;                # @b now has 3 elements, because of the
                                   # itemization with $
    say @c.elems;

.item can often be written as $( ... ), and on an array variable even as $@a.

The same flattening behavior applies all objects that do the Iterable role, notable hashes:

    my %h = a => 1, b => 2;
    my @b = %h;   say @b.elems;     # 2
    my @c = %h, ; say @c.elems;     # 1
    my @d = $%h;  say @d.elems;     # 1

Slurpy parameters (*@a) flatten non-itemized sublists:

    sub fe(*@flat) { @flat.elems }
    say fe(&lt;a b>, &lt;d e>);           # 4
    say fe(&lt;a b>, &lt;d e>.item);      # 3

# 99.2 Methods

## 99.2.1 routine elems

Defined as:

    multi sub    elems($list)  returns Int:D
    multi method elems(List:D:) returns Int:D

Usage:

    elems LIST
    LIST.elems

Returns the number of elements in the list.

## 99.2.2 routine end

Defined as:

    multi sub    end($list)  returns Int:D
    multi method end(List:D:) returns Int:D

Usage:

    end LIST
    LIST.end

Returns the index of the last element.

## 99.2.3 routine keys

Defined as:

    multi sub    keys($list)  returns Seq:D
    multi method keys(List:D:) returns Seq:D

Usage:

    keys LIST
    LIST.keys

Returns a sequence of indexes into the list (e.g., 0..(@list.elems-1)).

## 99.2.4 routine values

Defined as:

    multi sub    values($list)  returns Seq:D
    multi method values(List:D:) returns Seq:D

Usage:

    values LIST
    LIST.values

Returns a sequence of the list elements, in order.

## 99.2.5 routine kv

Defined as:

    multi sub    kv($list)  returns Seq:D
    multi method kv(List:D:) returns Seq:D

Usage:

    kv LIST
    LIST.kv

Returns an interleaved sequence of indexes and values. For example

    &lt;a b c>.kv

Returns

    (0, 'a', 1, 'b', 2, 'c').Seq

## 99.2.6 routine pairs

Defined as:

    multi sub    pairs($list)   returns Seq:D
    multi method pairs(List:D:) returns Seq:D

Usage:

    pairs LIST
    LIST.pairs

Returns a sequence of pairs, with the indexes as keys and the list values as values.

    &lt;a b c>.pairs   # (0 => 'a', 1 => 'b', 2 => 'c').Seq

## 99.2.7 routine join

Defined as:

    multi sub    join($separator, *@list) returns Str:D
    multi method join(List:D: $separator) returns Str:D

Usage:

    join SEPARATOR, LIST
    LIST.join(SEPARATOR)

Treats the elements of the list as strings, interleaves them with $separator and concatenates everything into a single string.

Example:

    join ', ', &lt;a b c>;             # a, b, c

Note that the method form does not flatten sublists:

    say (1, &lt;a b c>).join('|');     # 1|a b c

## 99.2.8 routine map

Defined as:

    multi sub    map(&amp;code, *@elems) returns Seq:D
    multi method map(List:D: &amp;code) returns Seq:D

Usage:

    map CODE, LIST
    LIST.map(CODE)

Invokes &code for each element and gathers the return values in a sequence and returns it. This happens lazily, i.e. &code is only invoked when the return values are accessed.

Examples:

    > ('hello', 1, 22/7, 42, 'world').map: { .WHAT.perl }
    (Str Int Rat Int Str)
    > map *.Str.chars, 'hello', 1, 22/7, 42, 'world'
    (5 1 8 2 5)

map inspects the arity of the code object, and tries to pass as many arguments to it as expected:

    sub b($a, $b) { "$a before $b" };
    say &lt;a b x y>.map(&amp;b).join(', ');   # a before b, x before y

iterates the list two items at a time.

Note that map does not flatten embedded lists and arrays, so

    ((1, 2), &lt;a b>).map({ .join(',')})

passes (1, 2) and <a b> in turn to the block, leading to a total of two iterations and the result sequence "1,2", "a,b". See method flatmap for an alternative that flattens.

## 99.2.9 sub flat

Defined as:

    sub flat(**@list is raw)

Constructs a list which contains any arguments provided in the order provided, and returns the result of calling the .flat method (inherited from Any ) on that list:

    flat 1, (2, (3, 4), $(5, 6)));  # (1, 2, 3, 4, $(5, 6)).Seq

## 99.2.10 method flatmap

Defined as:

    method flatmap(List:D: &amp;code) returns Seq:D

Usage:

    LIST.flatmap(CODE)

Like map iterates over the elements of the invocant list, feeding each element in turn to the code reference, and assembling the return values from these invocations in a result list.

Unlike map it flattens non-itemized lists and arrays, so

    say ((1, 2), &lt;a b>).flatmap(&amp;uc).join('|');     # 1|2|A|B

invokes uc four times.

## 99.2.11 routine grep

Defined as:

    multi sub    grep(Mu $matcher, *@elems, :k, :kv, :p, :v) returns Seq:D
    multi method grep(List:D:  Mu $matcher, :k, :kv, :p, :v) returns Seq:D

Usage:

    grep MATCHER, LIST
    grep MATCHER, LIST, :RETURN_AS
    LIST.grep(MATCHER)
    LIST.grep(MATCHER, :RETURN_AS)

Returns a sequence of elements against which $matcher smart-matches. The elements are returned in the order in which they appear in the original list.

Examples:

    > ('hello', 1, 22/7, 42, 'world').grep: Int
    (1 42)
    > grep { .Str.chars > 3 }, 'hello', 1, 22/7, 42, 'world'
    (hello 3.142857 world)

The optional named parameters :k, :kv, :p, :v provide the same functionality as on slices:

- k

Only return the index values of the matching elements in order.

- kv

Return both the index and matched elements in order.

- p

Return the index and the matched element as a Pair, in order.

- v

Only return the matched elements (same as not specifying any named parameter at all).

Examples:

    > ('hello', 1, 22/7, 42, 'world').grep: Int, :k
    (1 3)
    > grep { .Str.chars > 3 }, :kv, 'hello', 1, 22/7, 42, 'world'
    (0 hello 2 3.142857 4 world)
    > grep { .Str.chars > 3 }, :p, 'hello', 1, 22/7, 42, 'world'
    (0 => hello 2 => 3.142857 4 => world)

## 99.2.12 routine first

Defined as:

    multi sub    first(Mu $matcher, *@elems, :k, :kv, :p, :end)
    multi method first(List:D:  Mu $matcher, :k, :kv, :p, :end)

Usage:

    first MATCHER, LIST, :RETURN_AS, :FROM_END
    LIST.first(MATCHER, :RETURN_AS, :FROM_END)

Returns the first item of the list which smart-matches against $matcher, returns Nil when no values match. The optional named parameter :end indicates that the search should be from the end of the list, rather than from the start.

Examples:

    say (1, 22/7, 42, 300).first: * > 5;                  # 42
    say (1, 22/7, 42, 300).first: * > 5, :end;            # 300
    say ('hello', 1, 22/7, 42, 'world').first: Complex;   # Nil

The optional named parameters :k, :kv, :p provide the same functionality as on slices:

- k

Return the index value of the matching element. Index is always counted from the beginning of the list, regardless of whether the :end named parameter is specified or not.

- kv

Return both the index and matched element.

- p

Return the index and the matched element as a Pair.

Examples:

    say (1, 22/7, 42, 300).first: * > 5, :k;        # 2
    say (1, 22/7, 42, 300).first: * > 5, :p;        # 2 => 42
    say (1, 22/7, 42, 300).first: * > 5, :kv, :end; # 3 300

## 99.2.13 method head

Defined as:

    multi method head(List:D: Int(Cool) $number = 1) returns Seq:D

Usage:

    LIST.head
    LIST.head(NUMBER)

Returns the first NUMBER items of the list. Returns an empty list if NUMBER <= 0. Defaults to the first element seen if no NUMBER specified.

Examples:

    say ^10 .head(5)       # 0 1 2 3 4
    say ^Inf .head(5)      # 0 1 2 3 4
    say ^10 .head          # 0
    say ^Inf .head         # 0

## 99.2.14 method tail

Defined as:

    multi method tail(List:D: Int(Cool) $number = 1) returns Seq:D

Usage:

    LIST.tail
    LIST.tail(NUMBER)

Returns a Seq containing the last NUMBER items of the list. Returns an empty Seq if NUMBER <= 0. Defaults to the last element if no NUMBER is specified. Throws an exception if the list is lazy.

Examples:

    say ^10 .tail(5)      # 5 6 7 8 9
    say ^Inf .tail(5)     # Cannot tail a lazy list
    say ^10 .tail         # 9
    say ^Inf .tail        # Cannot tail a lazy list

## 99.2.15 routine categorize

Defined as:

    multi sub    categorize(&amp;mapper, *@values) returns Hash:D
    multi method categorize(List:D: &amp;mapper)   returns Hash:D

Usage:

    categorize MAPPER, LIST
    LIST.categorize(MAPPER)

Transforms a list of values into a hash representing the categorizations of those values according to a mapper; each hash key represents one possible categorization for one or more of the incoming list values, and the corresponding hash value contains an array of those list values categorized by the mapper into the category of the associated key.

Note that, unlike classify, which assumes that the return value of the mapper is a single value, categorize always assumes that the return value of the mapper is a list of categories that are appropriate to the current value.

Example:

    sub mapper(Int $i) returns List {
        $i %% 2 ?? 'even' !! 'odd',
        $i.is-prime ?? 'prime' !! 'not prime'
    }
    say categorize &amp;mapper, (1, 7, 6, 3, 2);   # {even => [6 2], not prime => [1 6],
                                               #  odd => [1 7 3], prime => [7 3 2]}

## 99.2.16 routine classify

Defined as:

    multi sub    classify(&amp;mapper, *@values) returns Hash:D
    multi method classify(List:D: &amp;mapper)   returns Hash:D

Usage:

    classify MAPPER, LIST
    LIST.classify(MAPPER)

Transforms a list of values into a hash representing the classification of those values according to a mapper; each hash key represents the classification for one or more of the incoming list values, and the corresponding hash value contains an array of those list values classified by the mapper into the category of the associated key.

Example:

    say classify { $_ %% 2 ?? 'even' !! 'odd' }, (1, 7, 6, 3, 2);
        #-> even => 6 2, odd => 1 7 3
    say ('hello', 1, 22/7, 42, 'world').classify: { .Str.chars };
        #-> 1 => 1, 2 => 42, 5 => hello world, 8 => 3.142857

## 99.2.17 method Bool

Defined as:

    multi method Bool(List:D:) returns Bool:D

Usage:

    LIST.Bool

Returns True if the list has at least one element, and False for the empty list.

## 99.2.18 method Str

Defined as:

    multi method Str(List:D:) returns Str:D

Usage:

    LIST.Str

Stringifies the elements of the list and joins them with spaces (same as .join(' ')).

## 99.2.19 method Int

Defined as:

    multi method Int(List:D:) return Int:D

Usage:

    LIST.Int

Returns the number of elements in the list (same as .elems).

## 99.2.20 method Numeric

Defined as:

    multi method Numeric(List:D:) return Int:D

Usage:

    LIST.Numeric

Returns the number of elements in the list (same as .elems).

## 99.2.21 method Capture

Defined as:

    method Capture() returns Capture:D

Usage:

    LIST.Capture

Returns a Capture where each Pair, if any, in the List has been converted to a named argument. All other elements in the List are converted to positional arguments in the order they are found, i.e. the first non pair item in the list becomes the first positional argument, which gets index 0, the second non pair item becomes the second positional argument, getting index 1 etc.

    my $list = (7, 5, a => 2, b => 17);
    my $capture = $list.Capture;
    say $capture.keys;                                # (0 1 a b)
    my-sub(|$capture);                                # 7, 5, 2, 17

    sub my-sub($first, $second, :$a, :$b) {
        say "$first, $second, $a, $b"
    }

A more advanced example demonstrating the returned Capture being matched against a Signature.

    my $list = (7, 5, a => 2, b => 17);
    say so $list.Capture ~~ :($ where * == 7,$,:$a,:$b); # True

    $list = (8, 5, a => 2, b => 17);
    say so $list.Capture ~~ :($ where * == 7,$,:$a,:$b); # False

## 99.2.22 routine pick

Defined as:

    multi sub    pick($count, *@list) returns Seq:D
    multi method pick(List:D: $count = 1) returns Mu

Usage:

    pick COUNT, LIST
    LIST.pick(COUNT)

Returns $count elements chosen at random and without repetition from the invocant. If * is passed as $count, or $count is greater than or equal to the size of the list, then all elements from the invocant list are returned in a random sequence.

Examples:

    say &lt;a b c d e>.pick;           # b
    say &lt;a b c d e>.pick: 3;        # (c a e)
    say  &lt;a b c d e>.pick: *;       # (e d a b c)

## 99.2.23 routine roll

Defined as:

    multi sub    roll($count, *@list) returns Seq:D
    multi method roll(List:D: $count = 1)

Usage:

    roll COUNT, LIST
    LIST.roll(COUNT)

Returns a sequence of $count elements, each randomly selected from the list. Each random choice is made independently, like a separate die roll where each die face is a list element.

If * is passed to $count, returns a lazy, infinite sequence of randomly chosen elements from the original list.

Examples:

    say &lt;a b c d e>.roll;       # b
    say &lt;a b c d e>.roll: 3;    # c c e
    say roll 8, &lt;a b c d e>;    # b a e d a e b c

    my $random_digits := (^10).roll(*);
    say $random_digits[^15];    # 3 8 7 6 0 1 3 2 0 8 8 5 8 0 5

## 99.2.24 routine eager

Defined as:

    multi method eager(List:D:) returns List:D
    sub eager(*@elems) returns List:D

Usage:

    eager LIST
    LIST.eager

Evaluates all elements in the list eagerly, and returns them as a list.

## 99.2.25 routine reverse

Defined as:

    multi sub    reverse(*@list ) returns List:D
    multi method reverse(List:D:) returns List:D

Usage:

    reverse(LIST)
    LIST.reverse

Returns a list with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

    say &lt;hello world!>.reverse      #  world! hello
    say reverse ^10                 # 9 8 7 6 5 4 3 2 1 0

## 99.2.26 routine rotate

Defined as:

    multi sub    rotate(@list,  Int:D $n = 1) returns List:D
    multi method rotate(List:D: Int:D $n = 1) returns List:D

Usage:

    rotate(LIST, INTEGER?)
    LIST.rotate(INTEGER?)

Returns the list rotated by $n elements.

Examples:

    &lt;a b c d e>.rotate(2);   # &lt;c d e a b>
    &lt;a b c d e>.rotate(-1);  # &lt;e a b c d>

## 99.2.27 routine sort

Defined as:

    multi sub    sort(*@elems)      returns Seq:D
    multi sub    sort(&amp;by, *@elems) returns Seq:D
    multi method sort(List:D:)      returns Seq:D
    multi method sort(List:D:, &amp;by) returns Seq:D

Usage:

    sort LIST
    sort SORT_BY, LIST
    LIST.sort
    LIST.sort(SORT_BY)

Sorts the list, smallest element first. By default infix:<cmp> is used for comparing list elements.

If &by is provided, and it accepts two arguments, it is invoked for pairs of list elements, and should return Order::Increase, Order::Same or Order::Decrease.

If &by accepts only one argument, the list elements are sorted according to by($a) cmp by($b) . The return values of &by are cached, so that &by is only called once per list element.

Examples:

    say (3, -4, 7, -1, 2, 0).sort;                  # -4 -1 0 2 3 7
    say (3, -4, 7, -1, 2, 0).sort: *.abs;           # 0 -1 2 3 -4 7
    say (3, -4, 7, -1, 2, 0).sort: { $^b leg $^a }; # 7 3 2 0 -4 -1

## 99.2.28 routine unique

Defined as:

    multi sub    unique(*@values, :&amp;as, :&amp;with) returns Seq:D
    multi method unique(List:D:,  :&amp;as, :&amp;with) returns Seq:D

Usage:

    unique LIST, :COMPARE_AS, :COMPARE_WITH
    LIST.unique(:COMPARE_AS, :COMPARE_WITH)

Returns a sequence of unique values from the invocant/argument list, such that only the first occurrence of each duplicated value remains in the result list. unique uses the semantics of the === operator to decide whether two objects are the same, unless the optional :with parameter is specified with another comparator. The order of the original list is preserved even as duplicates are removed.

Examples:

    say &lt;a a b b b c c>.unique    # a b c
    say &lt;a b b c c b a>.unique    # a b c

(Use squish instead if you know the input is sorted such that identical objects are adjacent.)

The optional :as parameter allows you to normalize/canonicalize the elements before unique-ing. The values are transformed for the purposes of comparison, but it's still the original values that make it to the result list:

Example:

    say &lt;a A B b c b C>.unique(:as(&amp;lc))          # a B c

One can also specify the comparator with the optional :with parameter. For instance if one wants a list of unique hashes, one could use the eqv comparator.

Example:

    my @list = {a => 42}, {b => 13}, {a => 42};
    say @list.unique(:with(&amp;[eqv]))               # {a=>42} {b=>13}

## 99.2.29 routine repeated

Defined as:

    multi sub    repeated(*@values, :&amp;as, :&amp;with) returns Seq:D
    multi method repeated(List:D:,  :&amp;as, :&amp;with) returns Seq:D

Usage:

    repeated LIST, :COMPARE_AS, :COMPARE_WITH
    LIST.repeated(:COMPARE_AS, :COMPARE_WITH)

Returns a sequence of repeated values from the invocant/argument list. It takes the same parameters as unique , but instead of passing through any elements when they're first seen, they're only passed through as soon as they're seen for the second time (or more).

Examples:

    say &lt;a a b b b c c>.repeated                    # a b b c
    say &lt;a b b c c b a>.repeated                    # b c b a
    say &lt;a A B b c b C>.repeated(:as(&amp;lc))          # A b b C

    my @list = {a => 42}, {b => 13}, {a => 42};
    say @list.repeated(:with(&amp;[eqv]))               # {a=>42}

## 99.2.30 routine squish

Defined as:

    multi sub    squish(*@values, :&amp;as) returns Seq:D
    multi method squish(List:D:,  :&amp;as) returns Seq:D

Usage:

    squish LIST, :COMPARE_AS
    LIST.squish(:COMPARE_AS)

Returns a sequence of values from the invocant/argument list where runs of more than one value are replaced with only the first instance. Like unique , squish uses the semantics of the === operator to decide whether two objects are the same. Unlike unique , this function only removes adjacent duplicates; identical values further apart are still kept. The order of the original list is preserved even as duplicates are removed.

Examples:

    say &lt;a a b b b c c>.squish  # a b c
    say &lt;a b b c c b a>.squish  # a b c b a

The optional :as parameter, just like with unique , allows values to be temporarily transformed before comparison.

## 99.2.31 routine reduce

Defined as:

    multi sub    reduce(&amp;with, *@values)
    multi method reduce(List:D: &amp;with)

Usage:

    reduce CODE, LIST
    LIST.reduce(CODE)

Generates a single "combined" value from a list of arbitrarily many of values, by repeatedly applying a function which knows how to combine two values.

More precisely, the specified &with is first called for the first two values of the list, then for the result of that calculation and the third value, and so on - and the final result is returned. In other words, (2, 4, 6, 8).reduce(*+*) is the same as (((2+4)+6)+8).

If @values contains just a single element, that element is returned immediately. If it contains no elements, an exception is thrown. For this reason, you may want to prefix the input list with an explicit identity value:

    say reduce { $^a ~ $^b }, '', |@strings;               # like @strings.join
    say reduce { $^a > $^b ?? $^a !! $^b }, 0, |@numbers;  # like @numbers.max

As a special case, if &with is the function object of an operator, its inherent identity value and associativity is respected - in other words, (VAL1, VAL2, VAL3).reduce(&[OP]) is the same as VAL1 OP VAL2 OP VAL3 even for operators which aren't left-associative, and an empty @values list is allowed now. And since reducing with an infix operator is a common thing to do, the [ ] meta-operator provides a syntactic shortcut:

    # The following all do the same thing...
    say reduce { $^a + $^b }, 0, |@numbers;
    say reduce * + *, 0, |@numbers;
    say reduce &amp;[+], @numbers;
    say [+] @numbers;

Since reduce is an implicit loop, it responds to next, last and redo statements.

Practical example:

    # Generate a random-ish math formula like "(4 + ((3 * x) + 11) / 6))"

    my @ops = [Z] (&lt;+ - * />, 1..20)».roll(4);

    say ('x', |@ops).reduce: -> $formula, [$op, $number] {
        Bool.pick ?? "($formula $op $number)"
                  !! "($number $op $formula)"
    }

Note: In the functional programming world, this operation is generally called a left fold.

## 99.2.32 routine combinations

Defined as:

    multi sub    combinations($n, $k)                     returns Seq:D
    multi method combinations(List:D: Int:D $of)          returns Seq:D
    multi method combinations(List:D: Range:D $of = 0..*) returns Seq:D

Usage:

    combinations INTEGER, INTEGER
    LIST.combinations(INTEGER)
    LIST.combinations(RANGE)

The Int variant returns all $of-combinations of the invocant list. For example

    say .join('|') for &lt;a b c>.combinations(2);

prints

    a|b
    a|c
    b|c

because all the 2-combinations of 'a', 'b', 'c' are ['a', 'b'], ['a', 'c'], ['b', 'c'].

The Range variant combines all the individual combinations into a single list, so

    say .join('|') for &lt;a b c>.combinations(2..3);

prints

    a|b
    a|c
    b|c
    a|b|c

because that's the list of all 2- and 3-combinations.

The subroutine form combinations($n, $k) is equivalent to (^$n).combinations($k), so

    .say for combinations(4, 2)

prints

    0 1
    0 2
    0 3
    1 2
    1 3
    2 3

## 99.2.33 routine permutations

Defined as:

    multi sub    permutations($n)      returns Seq:D
    multi method permutations(List:D:) returns Seq:D

Usage:

    permutations(INTEGER)
    LIST.permutations

Returns all possible permutations of a list as a sequence of lists. So

    say .join('|') for &lt;a b c>.permutations

prints

    a|b|c
    a|c|b
    b|a|c
    b|c|a
    c|a|b
    c|b|a

permutations treats all list elements as distinguishable, so (1, 1, 2).permutations still returns a list of 6 elements, even though there are only three distinct permutations.

The subroutine form permutations($n) is equivalent to (^$n).permutations, so

    .say for permutations 3;

prints

    1 2 3
    1 3 2
    2 1 3
    2 3 1
    3 1 2
    3 2 1

## 99.2.34 method rotor

Defined as:

    method rotor(*@cycle, Bool() :$partial) returns Seq:D

Usage:

    LIST.rotor(EXPR, :partial?)

Returns a sequence of lists, where each sublist is made up of elements of the invocant.

In the simplest case, @cycle contains just one integer, in which case the invocant list is split into sublists with as many elements as the integer specifies. If :$partial is True, the final chunk is included even if it doesn't satisfy the length requirement:

    say ('a'..'h').rotor(3).join('|');              # a b c|d e f
    say ('a'..'h').rotor(3, :partial).join('|');    # a b c|d e f|g h

If the element of @cycle is a Pair instead, the key of the pair specifies the length of the return sublist, and the value the gap between sublists; negative gaps produce overlap:

    say ('a'..'h').rotor(2 => 1).join('|');         # a b|d e|g h
    say ('a'..'h').rotor(3 => -1).join('|');        # a b c|c d e|e f g

If @cycle contains more than element, rotor cycles through it to find the number of elements for each sublist:

    say ('a'..'h').rotor(2, 3).join('|');           # a b|c d e|f g
    say ('a'..'h').rotor(1 => 1, 3).join('|');      # a|c d e|f

Combining multiple cycles and :partial also works:

    say ('a'..'h').rotor(1 => 1, 3 => -1, :partial).join('|');
                                                    # a|c d e|e|g h

See this blog post for more elaboration on rotor.

## 99.2.35 routine zip

Defined as:

    sub zip(**@e) returns Seq:D

Usage:

    zip LISTS

Zips two or more lists or other iterables together by returning a sequence made of a list of all first elements of all lists, then a list of all second elements of a list etc.

    say .join for zip  &lt;a b c>, &lt;d e f>;

Produces the output

    ad
    be
    cf

zip has an infix synonym, the Z operator.

    say .join for &lt;a b c> Z &lt;d e f>;    # same output as above

When the first input list is exhausted, no more elements are returned; so trailing elements from longer input lists are discarded.

If you just wish to skip missing entries in shorter sublists, use roundrobin instead:

    for roundrobin(@queue1, @queue2, @queue3) -> $next {
        ...
    }

## 99.2.36 sub roundrobin

Defined as:

    multi roundrobin(List:D: --> Seq)

Usage:

    roundrobin LISTS

roundrobin is very similar to zip. The difference is that roundrobin will not stop on lists that run out of elements but simply skip any undefined value:

    my @a = 1;
    my @b = 1..2;
    my @c = 1..3;
    for flat roundrobin(@a, @b, @c) -> $x { $x.say }

will display the following values: 1, 1, 1, 2, 2, 3

## 99.2.37 routine sum

Defined as:

    multi sub    sum($list)  returns Numeric:D
    multi method sum(List:D:) returns Numeric:D

Usage:

    sum LIST
    LIST.sum

Returns the sum of all elements in the list or 0 if the list is empty. Throws an exception if an element can not be coerced into Numeric.

    say (1, 3, pi).sum;       # 7.14159265358979
    say (1, "0xff").sum;      # 256
    say sum(0b1111, 5);       # 20

## 99.2.38 method fmt

Defined as:

    method fmt($format = '%s', $separator = ' ') returns Str:D

Returns a string where each element in the list has been formatted according to $format and where each element is separated by $separator.

For more information about formats strings, see sprintf.

    my @a = 8..11;
    say @a.fmt('%03d', ',');                          # 008,009,010,011

# 100 class Lock

Low-level thread locking primitive

    class Lock { ... }

A Lock is a low-level constructor for ensuring that only one thread works with a certain object at a given time, or runs a piece of code (called the critical section).

    my $x = 0;
    my $l = Lock.new;
    await (^10).map: {
        start {
            $l.protect({ $x++ });
        }
    }
    say $x;         # 10

Locks are reentrant, that is, a thread that holds the lock can lock it again without blocking.

High-level Perl 6 code should avoid the direct usage of locks, because they are not composable. Instead, high-level constructs such as Promise, Channel and Supply should be used whenever possible.

# 100.1 Methods

## 100.1.1 method protect

Defined as:

    method protect(Lock:D: &amp;code)

Usage:

    LOCK.protect(CODE)

Runs &code and makes sure it is only run in one thread at once.

## 100.1.2 method lock

Defined as:

    method lock(Lock:D:)

Usage:

    LOCK.lock

Acquires the lock. If it is currently not available, waits for it.

## 100.1.3 method unlock

Defined as:

    method unlock(Lock:D:)

Usage:

    LOCK.unlock

Releases the lock.

## 100.1.4 method condition

Defined as:

    my class ConditionVariable {
        method wait();
        method signal();
        method signal_all();
    }

    method condition(Lock:D:) returns ConditionVariable:D

Usage:

    LOCK.condition

Returns a condition variable. Compare http://web.stanford.edu/class/cs140/cgi-bin/lecture.php?topic=locks or https://en.wikipedia.org/wiki/Monitor_%28synchronization%29 for background.

# 101 class Macro

Compile-time routine

    class Macro is Routine { }

A macro is a Routine whose invocation typically happens during parsing. By returning an AST, a macro can inject code into the calling location.

# 102 class Map

Immutable mapping from strings to values

    class Map does Associative is Iterable { }

A Map is an immutable mapping from string keys to values of arbitrary types. It serves as a base class for Hash, which is mutable.

In list context a Map behaves as a list of Pair objects.

Note that the order in which keys, values and pairs are retrieved is generally arbitrary, but the keys, values and pairs methods return them always in the same order when called on the same object.

    my %e := Map.new('a', 1, 'b', 2);
    say %e.keys;    # can print "a b\n" or "b a\n";
    say %e.values;  # prints "1 2\n" if the previous line
                    # printed "a b\n", "b a\n" otherwise

# 102.1 Methods

## 102.1.1 method new

Defined as:

    proto method new(*@, *%) {*}
    multi method new(*@args, *%pairs)

Usage:

    Map.new(ARGS)

Creates a new Map from a list of alternating keys and values, with the same semantics as described for hash assigning in the Hash documentation.

## 102.1.2 method elems

Defined as:

    method elems(Map:D:) returns Int:D:

Usage:

    MAP.elems

Returns the number of pairs stored in the Map.

## 102.1.3 method ACCEPTS

Defined as:

    multi method ACCEPTS(Map:D: Positional $topic)
    multi method ACCEPTS(Map:D: Cool:D     $topic)
    multi method ACCEPTS(Map:D: Regex      $topic)
    multi method ACCEPTS(Map:D: Any        $topic)

Usage:

    MAP.ACCEPTS(TOPIC)

Used in smart-matching if the right-hand side is an Map.

If the topic is list-like (Positional), returns True if any of the list elements exist as a key in the Map.

If the topic is of type Cool (strings, integers etc.), returns True if the topic exists as a key.

If the topic is a regex, returns True if any of the keys match the regex.

As a fallback, the topic is coerced to a list, and the Positional behavior is applied.

To retrieve a value from the Map by key, use the { } postcircumfix operator:

    my $value = $map{$key};

To check whether a given key is stored in a Map, modify the access with the :exists adverb:

    if %h{$key}:exists {
        say "%h{} has key $key";
    }

## 102.1.4 method keys

Defined as:

    method keys(Map:D:) returns List:D

Usage:

    MAP.keys

Returns a list of all keys in the Map.

## 102.1.5 method values

Defined as:

    method values(Map:D:) returns List:D

Usage:

    MAP.values

Returns a list of all values in the Map.

## 102.1.6 method pairs

Defined as:

    method pairs(Map:D:) returns List:D

Usage:

    MAP.pairs

Returns a list of all pairs in the Map.

## 102.1.7 method antipairs

Defined as:

    method antipairs(Map:D:) returns Seq:D

Usage:

    MAP.antipairs

Returns all keys and their respective values as a Seq of Pairs where the keys and values have been exchanged, i.e. the opposite of method pairs. Unlike the invert method, there is no attempt to expand list values into multiple pairs.

    my $m = Map.new('a' => (2, 3), 'b' => 17);
    say $m.antipairs;                                  # ((2 3) => a 17 => b)

## 102.1.8 method invert

Defined as:

    method invert(Map:D:) returns Seq:D

Usage:

    MAP.invert

Returns all keys and their respective values as a Seq of Pairs where the keys and values have been exchanged. The difference between invert and antipairs is that invert expands list values into multiple pairs.

    my $m = Map.new('a' => (2, 3), 'b' => 17);
    say $m.invert;                                    # (2 => a 3 => a 17 => b)

## 102.1.9 method kv

Defined as:

    method kv(Map:D:) returns List:D

Usage:

    MAP.kv

Returns a list of keys and values interleaved.

    Map.new('a', 1, 'b', 2).kv  # a, 1, b, 2 OR b, 2, a, 1

## 102.1.10 method Int

Defined as:

    method Int(Map:D:) returns Int:D

Usage:

    MAP.Int

Returns the number of pairs stored in the Map (same as .elems).

    my $m = Map.new('a' => 2, 'b' => 17);
    say $m.Int;                                       # 2

## 102.1.11 method Numeric

Defined as:

    method Numeric(Map:D:) returns Int:D

Usage:

    MAP.Numeric

Returns the number of pairs stored in the Map (same as .elems).

    my $m = Map.new('a' => 2, 'b' => 17);
    say $m.Numeric;                                   # 2

## 102.1.12 method Bool

Defined as:

    method Bool(Map:D:) returns Bool:D

Usage:

    MAP.Bool

Returns True if the invocant contains at least one key/value pair.

    my $m = Map.new('a' => 2, 'b' => 17);
    say $m.Bool;                                      # True

## 102.1.13 method Capture

Defined as:

    method Capture(Map:D:) returns Capture:D

Usage:

    MAP.Capture

Returns a Capture where each key, if any, has been converted to a named argument with the same value as it had in the original Map. The returned Capture will not contain any positional arguments.

    my $map = Map.new('a' => 2, 'b' => 17);
    my $capture = $map.Capture;
    my-sub(|$capture);                                # 2, 17

    sub my-sub(:$a, :$b) {
        say "$a, $b"
    }

# 103 class Match

Result of a successful regex match

    class Match is Capture is Cool { ... }

Match objects are the result of a successful regex match. They store a reference to the original string (.orig), positional and named captures, the positions of the start and end of the match in the original string, and a payload referred to as AST (abstract syntax tree), which can be used to build data structures from complex regexes and grammars.

Submatches are also Match objects (or lists of Match objects, if the corresponding regex was quantified), so each match object can be seen as the root of a tree of match objects.

# 103.1 Methods

## 103.1.1 method orig

Returns the original string that the regex was matched against.

## 103.1.2 method from

Returns the index of the starting position of the match.

## 103.1.3 method to

Returns the index of the end position of the match.

## 103.1.4 method made

Returns the payload that was set with #method make.

## 103.1.5 method ast

Alias for #method made.

## 103.1.6 method Str

Returns the matched text.

## 103.1.7 method caps

Returns a list of pairs, with the index or submatch name as key and the submatches as values. The list is ordered by starting position of the submatches.

## 103.1.8 method chunks

Returns a list of pairs, with the index or submatch name as key and the submatches as values. The list is ordered by starting position of the submatches.

Those parts of the string that were not matched by submatches are interleaved with the other pairs, with the string ~ as key.

## 103.1.9 method list

Returns a list of positional submatches.

## 103.1.10 method hash

Returns a hash of named submatches.

## 103.1.11 method prematch

Returns the part of the original string leading up to the match.

## 103.1.12 method postmatch

Returns the part of the original string following the match.

## 103.1.13 method make

    method make(Match:D: Mu $ast)
    sub make(Mu $ast)

Sets the AST to $ast, and returns it.

This is just a little sugar for $/.made = $ast which is a very common operation in actions. $ast may be anything that makes sense for the use case. It's typically some tree node.

The sub form operates on the current $/, which can be a convenient shortcut:

    method my-action ($/) {
        make "foo: $/";
    }

# 104 role Metamodel::AttributeContainer

Metaobject that can hold attributes

    role Metamodel::AttributeContainer { ... }

Classes, roles and grammars can have attributes. Storage and introspection of attributes is implemented by this role.

# 104.1 Methods

## 104.1.1 method add_attribute

    method add_attribute(Metamodel::AttributeContainer: $obj, $name, $attribute)

Adds an attribute. $attribute must be an object that supports the methods name, type and package, which are called without arguments. It can for example be of type Attribute.

## 104.1.2 method attributes

    method attributes(Metamodel::AttributeContainer: $obj)

Returns a list of attributes. For most Perl 6 types, these will be objects of type Attribute.

## 104.1.3 method set_rw

    method set_rw(Metamodel::AttributeContainer: $obj)

Marks a type whose attributes default to having a write accessor. For example in

    class Point is rw {
        has $.x;
        has $.y;
    }

The is rw trait on the class calls the set_rw method on the meta class, making all the attributes implicitly writable, so that you can write;

    my $p = Point.new(x => 1, y => 2);
    $p.x = 42;

## 104.1.4 method rw

    method rw(Metamodel::AttributeContainer: $obj)

Returns a true value if method set_rw has been called on this object, that is, if new public attributes are writable by default.

TODO: compose_attributes, get_attribute_for_usage Also TODO: describe :local, :excl, :all options of method attributes

# 105 role Metamodel::C3MRO

Metaobject that supports the C3 method resolution order

    role Metamodel::C3MRO { }

Meta model role for the C3 method resolution order (MRO).

The method resolution order for a type is a flat list of types including the type itself, and (recursively) all super classes. It determines in which order the types will be visited for determining which method to call with a given name, or for finding the next method in a chain with nextsame, callsame, nextwith or callwith.

    class CommonAncestor { };   # implicitly inherits from Any
     class Child1 is CommonAncestor { }
     class Child2 is CommonAncestor { }
     class GrandChild2 is Child2 { }
     class Weird is Child1 is GrandChild2 { };

     say Weird.^mro;
         # (Weird) (Child1) (GrandChild2) (Child2) (CommonAncestor) (Any) (Mu)

C3 is the default resolution order for classes and grammars in Perl 6. Note that roles generally do not appear in the method resolution order (unless they are punned into a class, from which another type inherits), because methods are copied into classes at role application time.

# 105.1 Methods

## 105.1.1 compute_mro

    method compute_mro($type)

Computes the method resolution order.

## 105.1.2 mro

    method mro($type)

Returns a list of types in the method resolution order.

    say Int.^mro    # (Int) (Cool) (Any) (Mu)

Returns a list of types in the method resolution order, even those that are marked is hidden.

## 105.1.3 mro_unhidden

    method mro_unhidden($type)

Returns a list of types in method resolution order, excluding those that are marked with is hidden.

# 106 class Metamodel::ClassHOW

Metaobject representing a Perl 6 class.

    class Metamodel::ClassHOW
        does Metamodel::Naming
        does Metamodel::Documenting
        does Metamodel::Versioning
        does Metamodel::Stashing
        does Metamodel::AttributeContainer
        does Metamodel::MethodContainer
        does Metamodel::PrivateMethodContainer
        does Metamodel::MultiMethodContainer
        does Metamodel::RoleContainer
        does Metamodel::MultipleInheritance
        does Metamodel::DefaultParent
        does Metamodel::C3MRO
        does Metamodel::MROBasedMethodDispatch
        does Metamodel::MROBasedTypeChecking
        does Metamodel::Trusting
        does Metamodel::BUILDPLAN
        does Metamodel::Mixins
        does Metamodel::ArrayType
        does Metamodel::BoolificationProtocol
        does Metamodel::REPRComposeProtocol
        does Metamodel::InvocationProtocol
        does Metamodel::Finalization
            { }

Metamodel::ClassHOW is the meta class behind the class keyword.

    say so Int.HOW ~~ Metamodel::ClassHOW;      # True
    say say Int.^methods(:all).pick.name;       # sin

# 106.1 Methods

## 106.1.1 method add_fallback

    method add_fallback(Metamodel::ClassHOW:D: $condition, $calculator)

Installs a method fallback, that is, add a way to call methods that weren't statically added.

Both $condition and $calculator must be callables that receive the invocant and the method name once a method is called that can't be found in the method cache.

If $condition returns a true value, $calculator is called with the same arguments, and must return the code object to be invoked as the method, and is added to the method cache..

If $condition returns a false value, the next fallback (if any) is tried, and if none matches, an exception of type X::Method::NotFound is thrown.

User-facing code (that is, code not dabbling with meta classes) should use method FALLBACK instead.

## 106.1.2 method can

    method can(Metamodel::ClassHOW:D: $obj, $method-name)

Given a method names, it returns a List of methods that are available with this name.

    class A      { method x($a) {} };
    class B is A { method x()   {} };
    say B.^can('x').elems;              # 2
    for B.^can('x') {
        say .arity;                     # 1, 2
    }

In this example, class B has two possible methods available with name x (though a normal method call would only invoke the one installed in B directly). The one in B has arity 1 (i.e. it expects one argument, the invocant (self)), and the one in A expects 2 arguments (self and $a).

## 106.1.3 method compose

    method compose(Metamodel::ClassHOW:D: $obj)

A call to compose brings the meta object and thus the class it represents into a fully functional state, so if you construct or modify a class, you must call the compose method before working with the class.

It updates the method cache, checks that all methods that are required by roles are implemented, does the actual role composition work, and sets up the class to work well with language interoperability.

# 107 role Metamodel::Finalization

Metaobject supporting object finalization

DESTROY

    role Metamodel::Finalization { ... }

This role takes care that DESTROY submethods are called (if they exist) when an object is garbage-collected.

# 107.1 Methods

## 107.1.1 method setup_finalization

    method setup_finalization(Metamodel::Finalization:D: $obj)

Collects the DESTROY submethods from this class and all its superclasses, and marks the class as needing action on garbage collection.

A metamodel for a kind that implements finalization semantics must call this method at type composition time.

## 107.1.2 method destroyers

    method destroyers(Metamodel::Finalization:D: $obj) returns List:D

Returns a list of all finalization methods.

# 108 role Metamodel::MROBasedMethodDispatch

Metaobject that supports resolving inherited methods

    role Metamodel::MROBasedMethodDispatch { ... }

This role implements locating methods based on the method resolution order of related (usually "super"/"parent") types.

# 108.1 Methods

## 108.1.1 method find_method

    method find_method(Metamodel::MROBasedMethodDispatch:D: $obj, $name, $no_fallback)

Given a method name, returns the method object of that name which is closest in the method resolution order (MRO). If no method can be found, it returns a VM-specific sentinel value (typically a low-level NULL value).

If :no_fallback is supplied, fallback methods are not considered.

## 108.1.2 method find_method_qualified

    method find_method(Metamodel::MROBasedMethodDispatch:D: $obj, $type, $name)

Given a method name and a type, returns the method from that type. This is used in calls like

    self.SomeParentClass::the_method();

TODO: publish_method_cache

# 109 role Metamodel::MethodContainer

Metaobject that supports storing and introspecting methods

    class Metamodel::MethodContainer { ... }

roles, classes, grammars and enums can contain methods. This role implements the API around storing and introspecting them.

    say .name for Int.^methods(:all);

    # don't do that, because it changes type Int globally.
    # just for demonstration purposes.
    Int.^add_method('double', method ($x:) { 2 * $x });
    say 21.double;

# 109.1 Methods

## 109.1.1 method add_method

    method add_method(Metamodel::MethodContainer: $obj, $name, $code)

Adds a method to the meta class, to be called with name $name. This should only be done before a type is composed.

## 109.1.2 method methods

    method methods(Metamodel::MethodContainer: $obj, :$all, :$local)

Returns a list of public methods available on the class (which includes methods from superclasses and roles). By default this stops at the classes Cool, Any or Mu; to really get all methods, use the :all adverb. If :local is set, only methods declared directly in the class are returned.

    class A {
        method x() { };
    }

    say A.^methods();                   # x
    say A.^methods(:all);               # x infinite defined ...

The returned list contains objects of type Method, which you can use to introspect their signatures and call them.

Some introspection method-look-alikes like WHAT will not show up, although they are present in any Perl 6 object. They are handled at the grammar level and will likely remain so for bootstrap reasons.

## 109.1.3 method method_table

    method method_table(Metamodel::MethodContainer:D: $obj) returns Hash:D

Returns a hash where the keys are method names, and the values are methods. Note that the keys are the names by which the methods can be called, not necessarily the names by which the methods know themselves.

TODO: submethod_table, declares_method, lookup, cache, cache_get, cache_add

# 110 role Metamodel::MultipleInheritance

Metaobject that supports multiple inheritance

    role Metamodel::MultipleInheritance { ... }

Classes, roles and grammars can have parent classes, that is, classes to which method lookups fall back to, and to whose type the child class conforms to.

This role implements the capability of having zero, one or more parent (or super) classes.

In addition, it supports the notion of hidden classes, whose methods are excluded from the normal dispatching chain, so that for example nextsame ignores it.

This can come in two flavors: methods from a class marked as is hidden are generally excluded from dispatching chains, and class A hides B adds B as a parent class to A, but hides it from the method resolution order, so that mro_unhidden skips it.

# 110.1 Methods

## 110.1.1 method add_parent

    method add_parent(Metamodel::MultipleInheritance:D: $Obj, $parent, :$hides)

Adds $parent as a parent type. If $hides is set to a true value, the parent type is added as a hidden parent.

$parent must be a fully composed typed. Otherwise an exception of type X::Inheritance::NotComposed is thrown.

## 110.1.2 method parents

    method parents(Metamodel::MultipleInheritance:D: $obj, :$all, :$tree)

Returns the list of parent classes. By default it stops at Cool, Any or Mu, which you can suppress by supplying the :all adverb. With :tree, a nested list is returned.

    class D { };
    class C1 is D { };
    class C2 is D { };
    class B is C1 is C2 { };
    class A is B { };

    say A.^parents(:all).perl;          # (B, C1, C2, D, Any, Mu)
    say A.^parents(:all, :tree).perl;
        # ([B, [C1, [D, [Any, [Mu]]]], [C2, [D, [Any, [Mu]]]]],)

## 110.1.3 method hides

    method hides(Metamodel::MultipleInheritance:D: $obj)

Returns a list of all hidden parent classes.

## 110.1.4 method hidden

    method hidden(Metamodel::MultipleInheritance:D: $obj)

Returns a true value if (and only if) the class is marked is hidden.

## 110.1.5 method set_hidden

    method set_hidden(Metamodel::MultipleInheritance:D: $obj)

Marks the type as hidden.

# 111 role Metamodel::Naming

Metaobject that supports named types

    role Metamodel::Naming { }

Meta model role for (optionally) named things, like classes, roles and enums.

# 111.1 Methods

## 111.1.1 method name

    method name($type)

Returns the name of the meta object, if any.

    say 42.^name;       # Int

## 111.1.2 method set_name

    method set_name($type, $new_name)

Sets the new name of the meta object.

# 112 class Metamodel::Primitives

Metaobject that supports low-level type operations

    class Metamodel::Primitives is SuperClass { ... }

Metamodel::Primitives provides low-level operations for working with types, which are otherwise only available as implementation-dependent directives.

These primitives are available as class methods.

Here is an example that steals the meta model instance from the Int class to create a custom type (usually you would create your own meta class if you mess with something as low-level), which allows calling of just one method called why:

    my Mu $type := Metamodel::Primitives.create_type(Int.HOW, 'P6opaque');
    $type.^set_name('why oh why?');
    my %methods =  why => sub ($) { say 42 };
    Metamodel::Primitives.install_method_cache($type, %methods, :authoritative);
    $type.why;      # 42
    $type.list;     # No such method 'list' for invocant of type 'why oh why?'

# 112.1 Methods

## 112.1.1 method create_type

    method create_type(Mu $how, $repr = 'P6opaque')

Creates and returns a new type from a meta object $how and a representation name.

## 112.1.2 method set_package

    method set_package(Mu $type, $package)

Sets the package associated with the type.

## 112.1.3 method install_method_cache

    method install_method_cache( Mu $type, %cache, :$authoritative = True)

Installs a method cache, that is, a mapping from method names to code objects. If :authoritative is missing, or set to True, then calls of methods that do not exist in the cache will throw an exception of type X::Method::NotFound. If :authoritative is set to False, the usual fallback mechanism are tried.

## 112.1.4 method configure_type_checking

    method configure_type_checking(
        Mu $type,
        @cache,
        :$authoritative = True,
        :$call_accepts = False
    )

Configures the type checking for $type. @cache is a list of known types against which $type checks positively (so in a classical class-based system, the type itself and all recursive superclasses). If :authoritative is missing or True, this type will fail checks against all types not in @cache. If :call_accepts is True, the method ACCEPTS will be called for type checks against this type.

## 112.1.5 method configure_destroy

    method configure_destroy(Mu $type, $destroy)

Configures whether DESTROY methods are called (if present) when the garbage collector collects an object of this type (if $destroy is set to a true value). This comes with a performance overhead, so should only be set to a true value if necessary.

## 112.1.6 method compose_type

    method compose_type(Mu $type, $configuration)

Composes $type (that is, finalizes it to be ready for instantiation). See https://github.com/perl6/nqp/blob/master/docs/6model/repr-compose-protocol.markdown for what $configuration can contain (until we have better docs, sorry).

## 112.1.7 method rebless

    method rebless(Mu $object, Mu $type)

Changes $obj to be of type $type. This only works if $type type-checks against the current type of $obj, and if the storage of $object is a subset of that of $type.

## 112.1.8 method is_type

    method is_type(Mu \obj, Mu \type) returns Bool:D

Type-checks obj against type

# 113 role Metamodel::PrivateMethodContainer

Metaobject that supports private methods

    role Metamodel::PrivateMethodContainer { ... }

In Perl 6, classes, roles and grammars can have private methods, that is, methods that are only callable from within the class, and are not inherited to types derived by inheritance.

    class A {
        # the ! declares a private method
        method !double($x) {
            say 2 * $x;
        }
        method call-double($y) {
            # call with ! instead of .
            self!double($y);
        }
    }

For the purposes of dispatching and scoping, private methods are closer to subroutines than to methods. However they share access to self and attributes with methods.

# 113.1 Methods

## 113.1.1 method add_private_method

    method add_private_method(Metamodel::PrivateMethodContainer: $obj, $name, $code)

Adds a private method $code with name $name.

## 113.1.2 method private_method_table

    method private_method_table(Metamodel::PrivateMethodContainer: $obj)

Returns a hash of name => &method_object

TODO: document find_private_method, once we've figured out how to represent or catch nqp::null in Perl 6 land

# 114 role Metamodel::RoleContainer

Metaobject that supports holding/containing roles

    role Metamodel::RoleContainer { ... }

Implements the ability to hold roles to be held for composition.

    class A does SomeRole { ... }

roughly corresponds to

    class A {
        BEGIN A.^add_role(SomeRole);
    }

# 114.1 Methods

## 114.1.1 method add_role

    method add_role(Metamodel::RoleContainer:D: $obj, Mu $role)

Adds the $role to the list of roles to be composed.

## 114.1.2 method roles_to_compose

    method roles_to_compose(Metamodel::RoleContainer:D: $obj) returns List:D

returns a list of roles added with add_role, which are to be composed at type composition time.

# 115 role Metamodel::Trusting

Metaobject that supports trust relations between types

    role Metamodel::Trusting is SuperClass { ... }

Normally, code in a class or role can only access its own private methods. If another type declares that it trusts that first class, then access to private methods of that second type is possible. Metamodel::Trusting implements that aspect of the Perl 6 object system.

    class A {
        my class B {
            trusts A;   # that's where Metamodel::Trusting comes in
            method !private_method() {
                say "Private method in B";
            }
        }
        method build-and-poke {
            # call a private method from B
            # disallowed if A doesn't trust B
            B.new()!B::private_method();
        }
    }

    A.build-and-poke    # Private method in A

# 115.1 Methods

## 115.1.1 method add_trustee

    method add_trustee(Metamodel::Trusting:D: $type, Mu $trustee)

Trust $trustee.

    class A {
        BEGIN A.^add_trustee(B);
        # same as 'trusts B';
    }

## 115.1.2 method trusts

    method trusts(Metamodel::Trusting:D: $type) returns List

Returns a list of types that the invocant trusts.

    class A { trusts Int; };
    say .^name for A.^trusts;       # Int

## 115.1.3 method is_trusted

    method is_trusted(Metamodel::Trusting:D: $type, $claimant)

Returns 1 if $type trusts $claimant, and 0 otherwise. Types always trust themselves.

# 116 class Method

Member function

    class Method is Routine { }

A type for methods. To create a method outside a class definition, use the declarators my and method:

    my $m = method ($invocant: $param) {
        say "$invocant: '$param'";
    }
    "greeting".$m("hello");         # greeting: 'hello'

    &lt;a b c>.&amp;(my method (List:D:){dd self; self}).say;
    # OUTPUT«("a", "b", "c")␤(a b c)␤»

# 117 class Mix

Immutable collection of distinct objects with Real weights

    class Mix does Mixy { }

A Mix is an immutable mix, meaning a collection of distinct elements in no particular order that each have a real-number weight assigned to them. (For mutable mixes, see MixHash instead.)

Mixes are often used for performing weighted random selections - see .roll.

Objects/values of any type are allowed as mix elements. Within a Mix, items that would compare positively with the === operator are considered the same element, with a combined weight.

    my $recipe = (butter => 0.22, sugar => 0.1,
                   flour => 0.275, sugar => 0.02).Mix

     say $recipe.elems;      # 3
     say $recipe.keys.sort;  # butter flour sugar
     say $recipe.pairs.sort; # "butter" => 0.22 "flour" => 0.275 "sugar" => 0.12
     say $recipe.total;      # 0.615

Mixes can be treated as object hashes using the { } postcircumfix operator, which returns the corresponding numeric weight for keys that are elements of the mix, and 0 for keys that aren't:

    say $recipe&lt;butter>;     # 0.22
    say $recipe&lt;sugar>;      # 0.12
    say $recipe&lt;chocolate>;  # 0

# 117.1 Creating Mix objects

Mixes can be composed using the mix subroutine (or Mix.new, for which it is a shorthand). Any positional parameters, regardless of their type, become elements of the mix - with a weight of 1 for each time the parameter occurred:

    my $n = mix "a", "a", "b" => 0, "c" => 3.14;
    say $n.keys.map(&amp;WHAT);  # (Str) (Pair) (Pair)
    say $n.pairs;            # "a" => 2 ("b" => 0) => 1 ("c" => 3.14) => 1

Alternatively, the .Mix coercer (or its functional form, Mix()) can be called on an existing object to coerce it to a Mix. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a mix with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the mix, and the (cumulative) values become the associated numeric weights:

    my $n = ("a", "a", "b" => 0, "c" => 3.14).Mix;
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)
    say $n.pairs;            # "a" => 2 "c" => 3.14

# 117.2 Operators

TODO: Expand this section (using the corresponding section in lib/Type/Bag.pod as a guide) after ab5tract's set/bag/mix operator redesign.

See Set/Bag Operators for a complete list of set and bag operators with detailed explanations.

## 117.2.1 sub mix

    sub mix(*@args --> Mix)

Creates a new Mix from @args.

# 117.3 See Also

Sets, Bags, and Mixes

# 118 class MixHash

Mutable collection of distinct objects with Real weights

    class MixHash does Mixy { }

A MixHash is a mutable mix, meaning a collection of distinct elements in no particular order that each have a real-number weight assigned to them. (For immutable mixes, see Mix instead.)

Objects/values of any type are allowed as mix elements. Within a MixHash, items that would compare positively with the === operator are considered the same element, with a combined weight.

    my $recipe = (butter => 0.22, sugar => 0.1,
                   flour => 0.275, sugar => 0.02).MixHash

     say $recipe.elems;      # 3
     say $recipe.keys.sort;  # butter flour sugar
     say $recipe.pairs.sort; # "butter" => 0.22 "flour" => 0.275 "sugar" => 0.12
     say $recipe.total;      # 0.615

MixHashes can be treated as object hashes using the { } postcircumfix operator, which returns the corresponding numeric weight for keys that are elements of the mix, and 0 for keys that aren't. It can also be used to modify weights; Setting a weight to 0 automatically removes that element from the mix, and setting a weight to a non-zero number adds that element if it didn't already exist:

    say $recipe&lt;butter>;     # 0.22
     say $recipe&lt;sugar>;      # 0.12
     say $recipe&lt;chocolate>;  # 0

     $recipe&lt;butter> = 0;
     $recipe&lt;chocolate> = 0.30;
     say $recipe.pairs;       # "sugar" => 0.12 "flour" => 0.275 "chocolate" => 0.3

# 118.1 Creating MixHash objects

MixHashes can be composed using MixHash.new. Any positional parameters, regardless of their type, become elements of the mix - with a weight of 1 for each time the parameter occurred:

    my $n = MixHash.new: "a", "a", "b" => 0, "c" => 3.14;
    say $n.keys.map(&amp;WHAT);  # (Str) (Pair) (Pair)
    say $n.pairs;            # "a" => 2 ("b" => 0) => 1 ("c" => 3.14) => 1

Alternatively, the .MixHash coercer (or its functional form, MixHash()) can be called on an existing object to coerce it to a MixHash. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a mix with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the mix, and the (cumulative) values become the associated numeric weights:

    my $n = ("a", "a", "b" => 0, "c" => 3.14).MixHash;
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)
    say $n.pairs;            # "a" => 2 "c" => 3.14

# 118.2 Operators

TODO: Expand this section (using the corresponding section in lib/Type/BagHash.pod as a guide) after ab5tract's set/bag/mix operator redesign.

See Set/Bag Operators for a complete list of set and bag operators with detailed explanations.

# 118.3 See Also

Sets, Bags, and Mixes

# 119 role Mixy

Collection of distinct objects with Real weights

    role Mixy does Baggy { }

A role for collections of weighted values. See Mix and MixHash. Mixy objects differ from Baggy objects in that the weights of Mixy are Reals rather than Ints.

# 119.1 Methods

## 119.1.1 method total

    method total(--> Real)

Returns the sum of all the weights

    mix('a', 'b', 'c', 'a', 'a', 'd').total == 6; # True
    {a => 5.6, b => 2.4}.Mix.total == 8; # True

## 119.1.2 method roll

    method roll($count = 1)

Similar to a Bag.roll, but with Real weights rather than integral ones.

# 119.2 See Also

Sets, Bags, and Mixes

# 120 class Mu

The root of the Perl 6 type hierarchy.

    class Mu { ... }

The root of the Perl 6 type hierarchy. For the origin of the name, see https://en.wikipedia.org/wiki/Mu_%28negative%29. One can also say that there are many undefined values in Perl 6, and Mu is the most undefined value.

Note that most classes do not derive from Mu directly, but rather from Any.

# 120.1 Methods

## 120.1.1 routine defined

    multi sub    defined(Mu) returns Bool:D
    multi method defined()   returns Bool:D

Returns False on the type object, and True otherwise.

    say Int.defined;                # False
    say 42.defined;                 # True

Very few types (like Failure) override defined to return False even for instances:

    sub fails() { fail 'oh noe' };
    say fails().defined;            # False

## 120.1.2 routine isa

    multi method isa(Mu $type)      returns Bool:D
    multi method isa(Str:D $type)   returns Bool:D

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type.

    my $i = 17;
    say $i.isa("Int");   # True
    say $i.isa(Any);     # True

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

    my $s = "String";
    say $s ~~ Str;       # True

## 120.1.3 routine does

    method does(Mu $type)      returns Bool:D

Returns True if and only if the invocant conforms to type $type.

    my $d = Date.new('2016-06-03');
    say $d.does(Dateish);             # True    (Date does role Dateish)
    say $d.does(Any);                 # True    (Date is a subclass of Any)
    say $d.does(DateTime);            # False   (Date is not a subclass of DateTime)

Using the smart match operator ~~ is a more idiomatic alternative.

    my $d = Date.new('2016-06-03');
    say $d ~~ Dateish;                # True
    say $d ~~ Any;                    # True
    say $d ~~ DateTime;               # False

## 120.1.4 routine Bool

    multi sub    Bool(Mu) returns Bool:D
    multi method Bool()   returns Bool:D

Returns False on the type object, and True otherwise.

Many built-in types override this to be False for empty collections, the empty string or numerical zeros

    say Mu.Bool;                    # False
    say Mu.new.Bool;                # True
    say [1, 2, 3].Bool;             # True
    say [].Bool;                    # False
    say { 'hash' => 'full'}.Bool;   # True
    say {}.Bool;                    # False

## 120.1.5 method Str

    multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable. Method Str warns on type objects, and produces the empty string.

    say Mu.Str;                     #!> use of uninitialized value of type Mu in string context

## 120.1.6 routine gist

    multi sub    gist(Mu) returns Str
    multi method gist()   returns Str

Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use .perl to get all elements.

The default gist method in Mu re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific that may truncate output.

gist is the method that say calls implicitly, so say $something and say $something.gist generally produce the same output.

    say Mu.gist;        # (Mu)
    say Mu.new.gist;    # Mu.new()

## 120.1.7 routine perl

    multi sub    perl(Mu) returns Str
    multi method perl()   returns Str

Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value

## 120.1.8 method clone

    method clone(*%twiddles)

Creates a shallow clone of the invocant. If named arguments are passed to it, their values are used in every place where an attribute name matches the name of a named argument.

    class Point2D {
         has ($.x, $.y);
         multi method gist(Point2D:D:) {
             "Point($.x, $.y)";
         }
     }

     my $p = Point2D.new(x => 2, y => 3);

     say $p;                     # Point(2, 3)
     say $p.clone(y => -5);      # Point(2, -5)

## 120.1.9 method new

    multi method new(*%attrinit)

Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.

Classes may provide their own new method to override this default.

new triggers an object construction mechanism that calls submethods named BUILD in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.

## 120.1.10 method bless

    method bless(*%attrinit) returns Mu:D

Lower-level object construction method than new.

Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.

You can use this method when writing custom constructors:

    class Point {
        has $.x;
        has $.y;
        multi method new($x, $y) {
            self.bless(:$x, :$y);
        }
    }
    my $p = Point.new(-1, 1);

(Though each time you write a custom constructor, remember that it makes subclassing harder).

## 120.1.11 method CREATE

    method CREATE() returns Mu:D

Allocates a new object of the same type as the invocant, without initializing any attributes.

    say Mu.CREATE.defined;  # True

## 120.1.12 method print

    multi method print() returns Bool:D

Prints value to $*OUT after stringification using .Str method without adding a newline at end.

    "abc\n".print;          # abc␤

## 120.1.13 method put

    multi method put() returns Bool:D

Prints value to $*OUT after stringification using .Str method adding a newline at end.

    "abc".put;              # abc␤

## 120.1.14 method say

    multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

    say 42;                 # 42␤

## 120.1.15 method ACCEPTS

    multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smart matching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).

The Mu:U multi performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

    say 42 ~~ Mu;           # True
    say 42 ~~ Int;          # True
    say 42 ~~ Str;          # False

Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.

## 120.1.16 method WHICH

    multi method WHICH() returns ObjAt:D

Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH.

    say 42.WHICH eq 42.WHICH;       # True

## 120.1.17 method WHERE

    method WHERE() returns Int

Returns an Int representing the memory address of the object.

## 120.1.18 method WHY

    multi method WHY()

Returns the attached Pod value. For instance,

        sub cast(Spell $s)
         #= Initiate a specified spell normally
         #= (do not use for class 7 spells)
         {
         do-raw-magic($s);
         }
         say &amp;cast.WHY;

prints

    Initiate a specified spell normally (do not use for class 7 spells)

See the documentation specification for details about attaching Pod to variables, classes, functions, methods, etc.

## 120.1.19 trait is export

    multi sub trait_mod:&lt;is>(Mu:U \type, :$export!)

Marks a type as being exported, that is, available to external users.

    my class SomeClass is export { }

A user of a module or class automatically gets all the symbols imported that are marked as is export.

See Exporting and Selective Importing Modules for more details.

## 120.1.20 method return

    method return();

The method return will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

    sub f { (1|2|3).return };
    dd f(); # OUTPUT«any(1, 2, 3)␤»

## 120.1.21 method return-rw

Same as method return but provides the invocant as a writeable container to the invocant.

## 120.1.22 method take

    method take()

Takes the given item and passes it to the enclosing gather block.

    #| randomly select numbers for lotto
    my $num-selected-numbers = 6;
    my $max-lotto-numbers = 49;
    gather for ^$num-selected-numbers {
        take (1 .. $max-lotto-numbers).pick(1);
    }.say;    #-> 32 22 1 17 32 9  (for example)

## 120.1.23 method so

    method so()

Returns a Bool value representing the logical non-negation of an expression. One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,

    my @args = &lt;-a -e -b -v>;
    my $verbose-selected = any(@args) eq '-v' | '-V';
    if $verbose-selected.so {
        say "Verbose option detected in arguments";
    } #-> Verbose option detected in arguments

## 120.1.24 method not

    method not()

Returns a Bool value representing the logical negation of an expression. Thus it is the opposite of so.

    my @args = &lt;-a -e -b>;
    my $verbose-selected = any(@args) eq '-v' | '-V';
    if $verbose-selected.not {
        say "Verbose option not present in arguments";
    } #-> Verbose option not present in arguments

Since there is also a prefix version of not, the above code reads better like so:

    my @args = &lt;-a -e -b>;
    my $verbose-selected = any(@args) eq '-v' | '-V';
    if not $verbose-selected {
        say "Verbose option not present in arguments";
    } #-> Verbose option not present in arguments

# 121 class NFC

Codepoint-String in Normal Form C (Composed)

    class NFC is Uni { ... }

A Codepoint string in the "C" Unicode Normalization Form

# 122 class NFD

Codepoint-String in Normal Form D (Decomposed)

    class NFD is Uni { ... }

A Codepoint string in the "D" Unicode Normalization Form

# 123 class NFKC

Codepoint-String in Normal Form KC (Compatibility Composed)

    class NFKC is Uni { ... }

A Codepoint string in the "KC" Unicode Normalization Form

# 124 class NFKD

Codepoint-String in Normal Form KD (Compatibility Decomposed)

    class NFKD is Uni { ... }

A Codepoint string in the "KD" Unicode Normalization Form

# 125 class Nil

Absence of a value or a benign failure

    class Nil is Cool { }

The value Nil may be used to fill a spot where a value would normally go, and in so doing, explicitly indicate that no value is present. It may also used as a cheaper and less explosive alternative to a Failure .

The class Nil is the same exact thing as its only possible value, Nil.

    say Nil === Nil.new         #-> True

Along with Failure, Nil is one of the two types which may always be returned from a routine even when the routine specifies a particular return type. It may also be returned regardless of the definedness of the return type, however, Nil is considered undefined for all other purposes.

    sub a( --> Int:D ) { return Nil }
    a().say;                    #-> Nil

Nil is what is returned from empty routines or clauses, or routines that use a bare return statement.

    sub a { }; a().say;         #-> Nil
    sub b { return }; b().say;  #-> Nil
    say (if 1 { });             #-> Nil
    { ; }().say;                #-> Nil
    say EVAL "";                #-> Nil

In a list, Nil takes the space of one value. Iterating a Nil behaves like iteration of any non-iterable value, producing a sequence of one Nil.

    (1, Nil, 3).elems.say;      #-> 3
    (for Nil { $_ }).perl.say;  #-> (Nil,)

Any method call on Nil other than those specifically listed below, and consequently, any subscripting operation, will succeed and return Nil.

    say Nil.ITotallyJustMadeThisUp;  #-> Nil
    say (Nil)[100];                  #-> Nil
    say (Nil){100};                  #-> Nil

When assigned, a Nil evaporates into the type object of the type of the container you assigned it into.

    my Int $x = 42;
    $x = Nil;
    $x.say;                     #-> (Int)

Because an untyped variable is type Any, assigning a Nil to one will result in an (Any) type object.

    my $x = Nil;
    $x.say;          #-> (Any)
    my Int $y = $x;  # error:  Type check failed in assignment to '$y';
                     # expected 'Int' but got 'Any'

If you are looking for a variable which transforms objects into type objects when said variable appears on the RHS, you can type the container as Nil.

    my Nil $x;
    my Str $s = $x;
    $s.say;          #-> (Str)

There is an important exception to this transforms-into-type-object rule: assigning Nil to a variable which has a default will restore that default.

    my Int $x is default(42) = -1;
    my $y = 1;
    for $x, $y -> $val is rw { $val = Nil unless $val > 0 }
    $x.say;          #-> 42

# 125.1 Methods

## 125.1.1 method append

    method append(*@)

Warns the user that they tried to append onto a Nil.

## 125.1.2 method gist

    method gist() returns Str:D

Returns "Nil".

## 125.1.3 method Str

    method Str()

Warns the user that they tried to stringify a Nil.

## 125.1.4 method new

    method new(*@)

Returns Nil

## 125.1.5 method prepend

    method prepend(*@)

Warns the user that they tried to prepend onto a Nil.

## 125.1.6 method push

    method push(*@)

Warns the user that they tried to push onto a Nil.

## 125.1.7 method unshift

    method unshift(*@)

Warns the user that they tried to unshift onto a Nil.

## 125.1.8 method Numeric

    method Numeric()

Warns the user that they tried to numify a Nil.

# 126 class Num

Floating-point number

    class Num is Cool does Real { }

A Num object stores a floating-point number. It is immutable. On most platforms, it's an IEEE 754 64-bit floating point numbers, aka "double precision".

## 126.0.1 NaN

The value NaN is an instance of Num and represents a float point not-a-number value. It is defined and boolifies to True. NaN is the result of undefined float point number operations and depends on the CPU or software implementation of float point numbers on the system running the code.

## 126.0.2 method rand

    method rand(Num:D:) returns Num

Returns a pseudo random number between 0 and the invocant.

## 126.0.3 sub srand

    sub srand(Int $seed) returns Int:D

Seeds the pseudo random number generator used by Num.rand with the provided value. Note that srand is called with a platform dependent value when a Perl 6 program is started.

# 127 class NumStr

Dual Value Floating-point number and String

    class NumStr is Num is Str

The dual value types (often referred to as allomorphs) allow for the representation of a value as both a string and a numeric type, typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some quoting constructs:

    my $f = &lt;42.1e0>; say $f.WHAT; # (NumStr)

A NumStr can be used interchangeably where one might use a Str or a Num :

    my $f = &lt;42.1e0>;
    my $i = $f + 0.1e0;
    my $s = $f ~ " and a bit more";

# 127.1 Methods

## 127.1.1 method new

    method new(Num $i, Str $s)

The constructor requires both the Num and the Str value, when constructing one directly the values can be whatever is required:

    my $f = NumStr.new(42.1e0, "forty two and a bit");
    say +$f; # -> 42.1
    say ~$f; # -> "forty two and a bit"

## 127.1.2 method Numeric

    method Numeric

The numeric coercion is applied when the NumStr is used in a numeric context, such as a numeric comparison or smart match against a numeric value. It will return the Num value.

## 127.1.3 method Num

    method Num

Returns the Num value of the NumStr.

## 127.1.4 method Str

Returns the string value of the NumStr.

# 127.2 Operators

## 127.2.1 infix cmp

    multi sub infix:&lt;cmp>(NumStr:D $a, NumStr:D $b)

Compare two NumStr objects. The comparison is done on the Num value first and then on the Str value. If you want to compare in a different order then you would coerce to a Num or Str value first:

    my $f = NumStr.new(42.1e0, "smaller");
    my $g = NumStr.new(43.1e0, "larger");
    say $f cmp $g;          # Less
    say $f.Str cmp $g.Str;  # More

# 128 role Numeric

Number or object that can act as a number

    role Numeric { ... }

Common role for numbers and types that can act as numbers.

Binary numeric operations return an object of the "wider" type:

    Int         narrowest
    Rat
    FatRat
    Num
    Complex     widest

So for example the product of a Rat and an Int is a Rat.

Unary operations that in pure math usually return an irrational number generally return Num in Perl 6.

# 128.1 Methods

## 128.1.1 method Real

    method Real(Numeric:D:) returns Real:D

If this Numeric is equivalent to a Real, return that Real. Fail with X::Numeric::Real otherwise.

## 128.1.2 method Int

    method Int(Numeric:D:) returns Int:D

If this Numeric is equivalent to a Real, return the equivalent of calling truncate on that Real to get an Int. Fail with X::Numeric::Real otherwise.

## 128.1.3 method Rat

    method Rat(Numeric:D: Real $epsilon = 1.0e-6) returns Rat:D

If this Numeric is equivalent to a Real, return a Rat which is within $epsilon of that Real's value. Fail with X::Numeric::Real otherwise.

## 128.1.4 method Num

    method Num(Numeric:D:) returns Num:D

If this Numeric is equivalent to a Real, return that Real as a Num as accurately as is possible. Fail with X::Numeric::Real otherwise.

## 128.1.5 method narrow

    method narrow(Numeric:D) returns Numeric:D

Returns the number converted to the narrowest type that can hold it without loss of precision.

    say (4.0 + 0i).narrow.perl;     # 4
    say (4.0 + 0i).narrow.^name;    # Int

## 128.1.6 method ACCEPTS

    multi method ACCEPTS(Numeric:D: $other)

Returns True if $other is numerically the same as the invocant.

## 128.1.7 routine log

    multi sub    log(Numeric:D, Numeric $base = e) returns Numeric:D
    multi method log(Numeric:D: Numeric $base = e) returns Numeric:D

Calculates the logarithm to base $base. Defaults to the natural logarithm.

## 128.1.8 routine log10

    multi sub    log10(Numeric:D ) returns Numeric:D
    multi method log10(Numeric:D:) returns Numeric:D

Calculates the logarithm to base 10.

## 128.1.9 routine exp

    multi sub    exp(Numeric:D, Numeric:D $base = e) returns Numeric:D
    multi method exp(Numeric:D: Numeric:D $base = e) returns Numeric:D

Returns $base to the power of the number, or e to the power of the number if called without a second argument.

## 128.1.10 method roots

    multi method roots(Numeric:D: Int:D $n) returns Positional

Returns a list of the $n complex roots, which evaluate to the original number when raised to the $nth power.

## 128.1.11 routine abs

    multi sub    abs(Numeric:D ) returns Real:D
    multi method abs(Numeric:D:) returns Real:D

Returns the absolute value of the number.

## 128.1.12 routine sqrt

    multi sub    sqrt(Numeric:D) returns Numeric:D
    multi method sqrt(Numeric:D) returns Numeric:D

Returns a square root of the number. For real numbers the positive square root is returned.

On negative real numbers, sqrt returns NaN rather than a complex number, in order to not confuse people who are not familiar with complex arithmetic. If you want to calculate complex square roots, coerce to Complex first, or use the roots method.

## 128.1.13 method conj

    multi method conj(Numeric:D) returns Numeric:D

Returns the complex conjugate of the number. Returns the number itself for real numbers.

## 128.1.14 method Bool

    multi method Bool(Numeric:D:)

Returns False if the number is equivalent to zero, and True otherwise.

## 128.1.15 method succ

    method succ(Numeric:D:)

Returns the number incremented by one (successor).

## 128.1.16 method pred

    method pred(Numeric:D:)

Returns the number decremented by one (predecessor).

# 129 class ObjAt

Unique identification for an object

    class ObjAt { }

Objects of type ObjAt are the return value of .WHICH calls on other objects, and identify an object uniquely.

If two objects compare equally via ===, their .WHICH methods return the same ObjAt object.

# 130 enum Order

Human readable form for comparison operators.

    enum Order (:Less(-1), :Same(0), :More(1));

# 130.1 Operators

## 130.1.1 infix cmp

    multi sub infix:&lt;cmp>(\a, \b) returns Order:D

Coerces it's arguments to Stringy.

## 130.1.2 infix <=>

    multi sub infix:«&lt;=>»(Int:D \a, Int:D \b) returns Order:D

Specialized form for Int.

# 131 class Pair

Key/value pair

    class Pair does Associative { ... }

Consists of two parts, a key and a value. Pairs can be seen as the atomic units in Hashes, and they are also used in conjunction with named arguments and parameters.

There are many syntaxes for creating Pairs:

    Pair.new('key', 'value') # The canonical way
    'key' => 'value'         # this...
    :key&lt;value>              # ...means the same as this
    :key&lt;value1 value2>      # But this is  key => &lt;value1 value2>
    :foo(127)                # short for  foo => 127
    :127foo                  # the same   foo => 127

Variants of this are

    :key                     # same as   key => True
    :!key                    # same as   key => False

Any variable can be turned into a Pair of it's name and it's value.

    my $bar = 10;
    my %h = :$bar;
    dd %h; OUTPUT«Hash %h = {:bar(10)}␤»

# 131.1 Methods

## 131.1.1 method antipair

Defined as:

    method antipair() returns Pair:D

Usage:

    PAIR.antipair

Returns a new Pair object with key and value exchanged.

    my $p = (6 => 'Perl').antipair;
    say $p.key;         # Perl
    say $p.value;       # 6

## 131.1.2 method key

Defined as:

    multi method key(Pair:D:)

Usage:

    PAIR.key

Returns the key part of the Pair.

## 131.1.3 method value

Defined as:

    multi method value(Pair:D:) is rw

Usage:

    PAIR.value

Returns the value part of the Pair.

## 131.1.4 infix cmp

Defined as:

    multi sub infix:&lt;cmp>(Pair:D, Pair:D)

Usage:

    PAIR1 cmp PAIR2

The type-agnostic comparator; compares two Pairs. Compares first their key parts, and then compares the value parts if the keys are equal.

## 131.1.5 method fmt

Defined as:

    multi method fmt(Pair:D:) returns Str:D

Usage:

    PAIR.fmt(FORMATSTRING)

Takes a format string, and returns a string the key and value parts of the Pair formatted. Here's an example:

    my $pair = :Earth(1);
    say $pair.fmt("%s is %.3f AU away from the sun")
    # Prints "Earth is 1.000 AU away from the sun"

For more about format strings, see sprintf.

## 131.1.6 method kv

Defined as:

    multi method kv(Pair:D:) returns List:D

Usage:

    PAIR.kv

Returns a two-element List with the key and value parts of Pair, in that order. This method is a special case of the same-named method on Hash, which returns all its entries as a list of keys and values.

## 131.1.7 method pairs

Defined as:

    multi method pairs(Pair:D:)

Usage:

    PAIR.pairs

Returns a list of one Pair, namely this one.

## 131.1.8 method freeze

Defined as:

    method freeze(Pair:D:)

Usage:

    PAIR.freeze

Makes the value of the Pair read-only, by removing it from its Scalar container, and returns it.

    my $str = "apple";
    my $p = Pair.new('key', $str);
    $p.value = "orange";              # this works as expected
    $p.say;                           # key => orange
    $p.freeze.say;                    # orange
    $p.value = "a new apple";         # Fails with 'Cannot modify an immutable Str'

## 131.1.9 method Str

Defined as:

    multi method Str(Pair:D:) returns Str:D

Usage:

    Pair.Str

Returns a string representation of the invocant formatted as key ~ \t ~ value.

    my $b = eggs => 3;
    say $b.Str;                                       # eggs  3

# 132 class Parameter

Element of a

    class Parameter { }

Represents a parameter, for purpose of introspection.

The usual way to obtain a Parameter object is to create a signature, and call .params on it to obtain a list of the Parameters.

    my $sig   = :(Str $x);
    my $param = $sig.params[0];
    say $param.type;              # Str()

See Signature for more information, and also for an explanation on what most of the concepts related to parameters mean.

# 132.1 Methods

## 132.1.1 method name

Returns the variable name, which includes all sigils and twigils. This name is used internally when applied to code, or in a declaration determines the name declared. This name is not necessarily useable by a caller -- if it is, it will also appear as an alias. Often, the name will chosen descriptively as a form of self-documentation.

If the parameter is anonymous, Nil will be returned.

## 132.1.2 method sigil

Returns a string containing the parameter's sigil, for a looser definition of "sigil" than what is considered part of the variable's name|method name. Still returns a sigil even if the parameter is anonymous.

This "sigil" is actually an introspection used to help determine the normal binding style of a parameter, if it has not been altered through a trait.

Will bind to Default behavior
C<$> Scalar Generate new Scalar, use instead of Scalar in argument, if any
C<@> Positional Bind directly to the argument
C<@> PositionalBindFailover If binding failed, call argument's .cache method, bind to result
C<%> Associative Bind directly to the argument
C<&> Callable Bind directly to the argument
C<|> (anything) Bind to all remaining arguments, make new Capture if needed
C<\> (anything) Bind directly to the argument, keep existing Scalar, if any

## 132.1.3 method type

Returns the nominal type constraint of the parameter.

## 132.1.4 method constraints

Returns additional constraints on the parameter (usually as an all-Junction).

## 132.1.5 method named

Returns True if it's a named parameter.

## 132.1.6 method named_names

Returns the list of externally usable names/aliases for a named parameter.

## 132.1.7 method positional

Returns True if the parameter is positional.

## 132.1.8 method slurpy

Returns True for slurpy parameters.

## 132.1.9 method twigil

Returns a string containing the twigil part of the parameter's name.

## 132.1.10 method optional

Returns True for optional parameters.

## 132.1.11 method raw

Returns True for raw parameters.

    sub f(\raw) {
        raw = 5;
    }
    f(my $x);   # works
    f(42);      # dies in the assignment

Raw parameters bind either a variable or a value passed to it, with no decontainerization taking place. That means that if a variable was passed to it, you can assign to the parameter. This is different from rw-parameter which can only bind to variables, never to values.

This is the normal behavior for parameters declared with a sigil of '\', which is not really a sigil insofar as it is only used on the parameter. Other parameters may become raw through use of the 'is raw' trait. These still use their sigil in code.

    sub f($raw is raw) {
        $raw = 5;
    }

## 132.1.12 method capture

Returns True for parameters that capture the rest of the argument list into a single Capture object.

    sub how_many_extra_positionals($!, |capture) { capture.elems.say }
    how_many_extra_positionals(0, 1, 2, 3);                        #-> 3
    say &amp;how_many_extra_positionals.signature.params[1].capture;   #-> True

Like raw parameters, Capture parameters do not force any context on the values bound to them, which is why their sigils are only used in declarations.

## 132.1.13 method rw

Returns True for is rw parameters.

## 132.1.14 method copy

Returns True for is copy parameters.

## 132.1.15 method readonly

Returns True for read-only parameters (the default).

## 132.1.16 method invocant

Returns True if the parameter is the invocant parameter.

## 132.1.17 method default

Returns a closure that upon invocation returns the default value for this parameter, or Any if no default was provided.

## 132.1.18 method type_captures

Returns a list of variable names of type captures associated with this parameter. Type captures define a type name within the attached code, which is an alias to the type gleaned from the argument during a call.

    sub a(::T ::U $x) { T.say }
    a(8);                                       #-> Int
    say &amp;a.signature.params[0].type_captures;   #-> T U
    sub b($x) { $x.WHAT.say } # does the same thing, but uglier.

The type used may change from call to call. Once they are defined, type captures can be used wherever you would use a type, even later in same the signature:

    sub c(::T $x, T $y, $z) { my T $zz = $z };
    c(4, 5, 6);          # OK
    c(4, 5, "six");      # Fails when assigning to $zz, wants Int not Str
    c("four", 5, "six"); # Fails when binding $y, wants Str, not Int

Type captures may be used at the same time as type constraints.

    sub d(::T Numeric $x, T $y);
    d(4, 5);            # OK
    d(4e0, 5e0);        # OK
    d(4e0, 5);          # Fails when binding $y
    d("four", "five");  # Fails when binding $x

## 132.1.19 method sub_signature

If the parameter has a sub-signature, returns a Signature object for it. Otherwise returns Any.

# 133 class Pod::Block

Block in a Pod document

    class Pod::Block { }

Class for a Pod block, and base class for most other Pod classes.

A Pod block has contents (more pod blocks or strings) and a config hash.

Useful subclasses:

Class | Used for
--- | ---
L<Pod::Block::Para> | paragraphs
L<Pod::Block::Named> | named blocks
L<Pod::Block::Code> | code blocks
L<Pod::Block::Comment> | comments
L<Pod::Block::Table> | =begin/end table
| tabular data
L<Pod::Heading> | =head1 etc. headings
L<Pod::Item> | list items

# 133.1 Methods

## 133.1.1 method contents

    method contents() returns Positional:D

Returns a list of contents of this block.

## 133.1.2 method config

    method config returns Map:D

Returns a hash of configs.

# 134 class Pod::Block::Code

Verbatim code block in a Pod document

    class Pod::Block::Code is Pod::Block { }

Class for a code (verbatim) Pod block.

# 134.1 Methods

## 134.1.1 method allowed

    method allowed() returns Positional:D

Returns a list of formatting codes that are allowed inside the code block.

# 135 class Pod::Block::Named

Named block in a Pod document

    class Pod::Block::Named is Pod::Block { }

Class for a named Pod block. For example

...

creates a Pod::Block::Named with name mysection.

# 135.1 Methods

## 135.1.1 method name

    method name() returns Str:D

Returns the name of the block.

# 136 class Pod::Block::Para

Paragraph in a Pod document

    class Pod::Block::Para is Pod::Block { }

Class for a Pod paragraph.

# 137 class Pod::Item

Item in a Pod enumeration list

    class Pod::Item is Pod::Block

Class for items in Pod enumeration lists.

# 137.1 Methods

## 137.1.1 method level

    method level() returns Int

Returns the level of the enumeration list, starting at 1.

# 138 role Positional

Object that supports looking up values by index

    role Positional { ... }

Role for objects which support indexing them using postcircumfix:«[ ]» (usually list-like objects). Example types with Positional role include List, Array, Range, and Buf.

# 138.1 Methods

## 138.1.1 method of

    method of()

Returns the type constraint for elements of the positional container. Defaults to Mu.

# 139 role PositionalBindFailover

Failover for binding an Iterable to a Positional

    role PositionalBindFailover { ... }

This role provides an interface by which an Iterable can be coerced into a Positional, so that you can for example write:

    sub fifths(@a) {       # @a is constraint to Positional
        @a[4];
    }
    my $seq := gather {     # a Seq, which is not Positional
        take $_ for 1..*;
    }
    say fifths($seq);       # 5

The invocation of fifths in the example above would ordinarily give a type error, because $seq is of type Seq, which doesn't do the Positional interface that the @-sigil implies.

But the signature binder recognizes that Seq does the PositionalBindFailover role, and calls its cache method to coerce it to a List, which does the Positional role.

# 139.1 Methods

## 139.1.1 method cache

    method cache(PositionalBindFailover:D:) returns List:D

Returns a List based on the iterator method, and caches it. Subsequent calls to cache always return the same List object.

## 139.1.2 method list

    method list(PositionalBindFailover:D:) returns List:D

Returns a List based on the iterator method without caching it.

## 139.1.3 method iterator

    method iterator(PositionalBindFailover:D:) { ... }

This method stub ensure that a class implementing role PositionalBindFailover provides an iterator method.

# 140 class Proc

Running process (filehandle-based interface)

    class Proc { ... }

Proc is a representation of an invocation of an external process. It provides access to the input, output and error stream as well as the exit code. It is typically created through the run subroutine:

    my $proc = run 'echo', 'Hallo world', :out;
    my $captured-output = $proc.out.slurp-rest;
    say "Output was $captured-output.perl()";       # Output was "Hallo world\n"

Piping several commands is easy too. To achieve the equivalent of the pipe echo "Hello, world" | cat -n in Perl 6, and capture the output from the second command, you can do

    my $p1 = run 'echo', 'Hello, world', :out;
    my $p2 = run 'cat', '-n', :in($p1.out), :out;
    say $p2.out.get;

# 140.1 Methods

## 140.1.1 method new

    method new(Proc:U:
            :$in = '-',
            :$out = '-',
            :$err = '-',
            Bool :$bin = False,
            Bool :$chomp = True,
            Bool :$merge = False,
            Str:D :$enc = 'UTF-8',
            Str:D $nl = "\n",
        ) returns Proc:D
    sub run(
            :$in = '-',
            :$out = '-',
            :$err = '-',
            Bool :$bin = False,
            Bool :$chomp = True,
            Bool :$merge = False,
            Str:D :$enc = 'UTF-8',
            Str:D $nl = "\n",
            :$cwd = $*CWD,
            Hash() :$env = %*ENV,
            *@args
    )  returns Proc:D

new creates a new Proc object, whereas run creates one, and spawns it with the command and arguments provided in @args.

$in, $out and $err are the three standard streams of the to-be-launched program, and default to "-", which means they inherit the stream from the parent process. Setting one (or more) of them to True makes the stream available as an IO::Pipe object of the same name, so for example $proc.out. Or you can pass an existing IO::Handle object (for example IO::Pipe) in, in which case this handle is used for the stream.

$bin controls whether the streams are handled as binary (i.e. Blob object) or text (i.e. Str objects). If $bin is False, $enc holds the character encoding to encode strings sent to the input stream and decode binary data from the output and error streams.

With $chomp set to True, newlines are stripped from the output and err streams when reading with lines or get. $nl controls what your idea of a newline is.

If $merge is set to True, the standard output and error stream end up merged in $proc.out.

## 140.1.2 method sink

When sunk, the Proc object will throw X::Proc::Unsuccessful if the process it run exited unsuccessfully.

## 140.1.3 method spawn

    method spawn(Proc:D *@args ($, *@), :$cwd = $*CWD, Hash() :$env = %*ENV) returns Bool:D

Runs the Proc objects with the given command, argument list, working directory and environment.

## 140.1.4 method exitcode

    method exitcode(Proc:D) returns Int:D

Returns the exit code of the external process, or -1 if it has not exited yet.

## 140.1.5 method signal

    method signal(Proc:D)

Returns the signal number with which the external process was killed, or 0 or an undefined value otherwise.

## 140.1.6 method pid

    method pid(Proc:D)

Returns the Process Identifier (pid) of the external process, if available.

# 141 class Proc::Async

Running process (asynchronous interface)

    class Proc::Async { ... }

Note: only the MoarVM backend of Rakudo implements Proc::Async at the moment.

Proc::Async allows you to run external commands asynchronously, capturing standard output and error handles, and optionally write to its standard input.

        # command with arguments
         my $proc = Proc::Async.new('echo', 'foo', 'bar');

         # subscribe to new output from out and err handles:
         $proc.stdout.tap(-> $v { print "Output: $v" });
         $proc.stderr.tap(-> $v { print "Error:  $v" });

         say "Starting...";
         my $promise = $proc.start;

         # wait for the external program to terminate
         await $promise;
         say "Done.";

This produces the following output:

    Starting...
    Output: foo bar
    Done.

An example that opens an external program for writing:

    use v6;
    my $prog = Proc::Async.new(:w, 'hexdump', '-C');
    my $promise = $prog.start;
    await $prog.write(Buf.new(12, 42));
    $prog.close-stdin;
    await $promise;

# 141.1 Methods

## 141.1.1 method new

    method new(:$path, *@args, :$w) returns Proc::Async:D

Creates a new Proc::Async object with external program name or path $path and the command line arguments @args.

If :w is passed to new, then a pipe to the external program's standard input stream (stdin) is opened, to which you can write with write and say.

## 141.1.2 method stdout

    method stdout(Proc::Async:D: :$bin) returns Supply:D

Returns the Supply for the external program's standard output stream. If :bin is passed, the standard output is passed along in binary as Blob, otherwise it is interpreted as UTF-8, decoded, and passed along as Str.

    $proc.stdout.tap( -> $str {
        say "Got output '$str' from the external program";
    });

You must call stdout before you call #method start. Otherwise an exception of class X::Proc::Async::TapBeforeSpawn is thrown.

If stdout is not called, the external program's standard output is not captured at all.

Note that you cannot call stdout both with and without :bin on the same object; it will throw an exception of type X::Proc::Async::CharsOrBytes if you try.

## 141.1.3 method stderr

    method stderr(Proc::Async:D: :$bin) returns Supply:D

Returns the Supply for the external program's standard error stream. If :bin is passed, the standard error is passed along in binary as Blob, otherwise it is interpreted as UTF-8, decoded, and passed along as Str.

    $proc.stderr.tap( -> $str {
        say "Got error '$str' from the external program";
    });

You must call stderr before you call #method start. Otherwise an exception of class X::Proc::Async::TapBeforeSpawn is thrown.

If stderr is not called, the external program's standard error stream is not captured at all.

Note that you cannot call stderr both with and without :bin on the same object; it will throw an exception of type X::Proc::Async::CharsOrBytes if you try.

## 141.1.4 method w

    method w(Proc::Async:D:)

Returns a true value if :w was passed to the constructor, that is, if the external program is started with its input stream made available to output to the program through the .print, .say and .write methods.

## 141.1.5 method start

    method start(Proc::Async:D:, :$scheduler = $*SCHEDULER, :$cwd = $*CWD) returns Promise:D

Initiates spawning of the external program. Returns a promise that will be kept with a Proc object once the external program exits, and that will be broken if the program cannot be started.

If start is called on a Proc::Async object on which it has already been called before, an exception of type X::Proc::Async::AlreadyStarted is thrown.

Note: If you wish to await the Promise and discard its result, using

    try await $p.start;

will throw if the program exited with non-zero status, as the Proc returned as the result of the Promise throws when sunk and in this case it will get sunk outside the try. To avoid that, sink it yourself inside the try:

    try sink await $p.start;

## 141.1.6 method started

    method started(Proc::Async:D:) returns Bool:D

Returns False before .start has been called, and True afterwards.

## 141.1.7 method path

    method path(Proc::Async:D:)

Returns the name and/or path of the external program that was passed to the new method as first argument.

## 141.1.8 method args

    method args(Proc::Async:D:) returns Positional:D

Returns the command line arguments for the external programs, as passed to the new method.

## 141.1.9 method write

    method write(Proc::Async:D: Blob:D $b, :$scheduler = $*SCHEDULER)

Write the binary data in $b to the standard input stream of the external program.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method write, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

## 141.1.10 method print

    method print(Proc::Async:D: Str(Any) $str, :$scheduler = $*SCHEDULER)

Write the text data in $str to the standard input stream of the external program, encoding it as UTF-8.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method print, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

## 141.1.11 method say

    method say(Proc::Async:D: $output, :$scheduler = $*SCHEDULER)

Calls method gist on the $output, adds a newline, encodes it as UTF-8, and sends it to the standard input stream of the external program, encoding it as UTF-8.

Returns a Promise that will be kept once the data has fully landed in the input buffer of the external program.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method say, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

## 141.1.12 method close-stdin

    method close-stdin(Proc::Async:D:)

Closes the standard input stream of the external program. Programs that read from STDIN often only terminate when their input stream is closed. So if waiting for the promise from #method start hangs (for a program opened for writing), it might be a forgotten close-stdin.

The Proc::Async object must be created for writing (with Proc::Async.new(:w, $path, @args)). Otherwise an X::Proc::Async::OpenForWriting exception will the thrown.

start must have been called before calling method close-stdin, otherwise an X::Proc::Async::MustBeStarted exception is thrown.

## 141.1.13 method kill

    kill(Proc::Async:D: $signal = "HUP")

Sends a signal to the running program. The signal can be a signal name ("KILL" or "SIGKILL"), an integer (9) or an element of the Signal enum (Signal::SIGKILL).

# 142 class Promise

Status/result of an asynchronous computation

    my enum PromiseStatus (:Planned(0), :Kept(1), :Broken(2));
    class Promise { ... }

A Promise is used to handle the result of a computation that might not have finished. It allows the user to execute code once the computation is done (with the then method), execution after a time delay (with in), combining promises, and waiting for results.

    my $p = Promise.start({ sleep 2; 42});
    $p.then({ say .result });   # will print 42 once the block finished
    say $p.status;              # Planned
    $p.result;                  # waits for the computation to finish
    say $p.status;              # Kept

There are two typical scenarios for using promises. The first is to use a factory method (start, in, anyof, allof) on the type object; those will make sure that the promise is automatically kept or broken for you, and you can't call break or keep on these promises yourself.

The second is to create your promises yourself with Promise.new. If you want to ensure that only your code can keep or break the promise, you can use the vow method to get a unique handle, and call keep or break on it:

        sub async-get-with-promise($user-agent, $url) {
             my $p = Promise.new;
             my $v = $p.vow;

             # do an asynchronous call on a fictive user agent,
             # and return the promise:
             $user-agent.async-get($url,
                     on-error => -> $error {
                         $v.break($error);
                     },
                     on-success => -> $response {
                         $v.keep($response);
                     }
             );
             return $p;
         }

Further examples can be found in the concurrency page.

# 142.1 Methods

## 142.1.1 method start

    sub start(&amp;code);
    method start(Promise:U: &amp;code, :$scheduler = $*SCHEDULER) returns Promise:D

Creates a new Promise that runs the given code object. The promise will be kept when the code terminates normally, or broken if it throws an exception. The return value or exception can be inspected with the result method.

The scheduler that handles this promise can be passed as a named argument.

    # these two are equivalent:
    my $p1 = Promise.start({ do something here });
    my $p2 = start { do something here };

## 142.1.2 method in

    method in(Promise:U: $seconds, :$scheduler = $*SCHEDULER) returns Promise:D

Creates a new Promise that will be kept in $seconds seconds, or later.

    my $p = Promise.in(5).then({ say "5 seconds later" });
    # do other stuff here

    await $p;   # wait here until the 5 seconds are over

## 142.1.3 method at

    method at(Promise:U: $time, :$scheduler = $*SCHEDULER) returns Promise:D

Creates a new Promise that will be kept at the given time, or later.

    my $p = Promise.at(now + 5).then({ say "5 seconds later" });
    # do other stuff here

    await $p;   # wait here until the 5 seconds are over

## 142.1.4 method allof

    method allof(Promise:U: *@promises) returns Promise:D

Returns a new promise that will be kept when all the promises passed as arguments are kept or broken. The result of the individual Promises is not reflected in the the result of the returned promise: it simply indicates that all the promises have been completed in some way. If the results of the individual promises are important then they should be inspected after the the allof promise is kept.

In the following requesting the result of a broken promise will case the original Exception to be thrown. (You may need to run it several times to see the exception.)

    my @promises;
    for 1..5 -> $t {
        push @promises, start {
            sleep $t;
            die "OH NOEZ" if rand &lt; 0.2;
        };
    }
    my $all-done = Promise.allof(@promises);
    await $all-done;
    @promises>>.result;
    say "Promises kept so we get to live another day!";

## 142.1.5 method anyof

    method anyof(Promise:U: *@promises) returns Promise:D

Returns a new promise that will be kept as soon as any of the promises passed as arguments is kept or broken. The result of the completed Promise is not reflected in the result of the returned promise which will always be Kept.

You can use this to wait at most a number of seconds for a promise:

    my $timeout = 5;
    await Promise.anyof(
        Promise.in($timeout),
        start {
            # do a potentially long-running calculation here
        },
    );

## 142.1.6 method then

    method then(Promise:D: &amp;code)

Schedules a piece of code to be run after the invocant has been kept or broken, and returns a new promise for this computation. In other words, creates a chained promise.

    my $timer = Promise.in(2);
    my $after = $timer.then({ say "2 seconds are over!"; 'result' });
    say $after.result;  # 2 seconds are over
                        # result

## 142.1.7 method keep

    multi method keep(Promise:D:);
    multi method keep(Promise:D: \result);

Keeps a promise, optionally setting the result. If no result is passed, the result will be True.

Throws an exception of type X::Promise::Vowed if a vow has already been taken. See method vow for more information.

    my $p = Promise.new;

    if Bool.pick {
        $p.keep;
    }
    else {
         $p.break;
    }

## 142.1.8 method break

    multi method break(Promise:D:);
    multi method break(Promise:D: \result);

Breaks a promise, optionally setting the result. If no result is passed, the result will be False.

Throws an exception of type X::Promise::Vowed if a vow has already been taken. See method vow for more information.

    my $p = Promise.new;

    $p.break('sorry');
    say $p.status;          # Broken
    say $p.cause;           # sorry

## 142.1.9 method result

    method result(Promise:D)

Waits for the promise to be kept or broken. If it is kept, returns the result; otherwise throws the result as an exception.

## 142.1.10 method cause

    method cause(Promise:D)

If the promise was broken, returns the result (or exception). Otherwise, throws an exception of type X::Promise::CauseOnlyValidOnBroken.

## 142.1.11 method Bool

    multi method Bool(Promise:D:)

Returns True for a kept or broken promise, and False for one in state Planned.

## 142.1.12 method status

    method status(Promise:D) returns PromiseStatus

Returns the current state of the promise: Kept, Broken or Planned:

    say "promise got Kept" if $promise.status ~~ Kept;

## 142.1.13 method scheduler

    method scheduler(Promise:D:)

Returns the scheduler that manages the promise.

## 142.1.14 method vow

    my class Vow {
        has Promise $.promise;
        method keep() { ... }
        method break() { ... }
    }
    method vow(Promise:D:) returns Vow:D

Returns an object that holds the sole authority over keeping or breaking a promise. Calling keep or break on a promise that has vow taken throws an exception of type X::Promise::Vowed.

    my $p   = Promise.new;
    my $vow = $p.vow;
    $vow.keep;
    say $p.status;          # Kept

## 142.1.15 method Supply

    method Supply(Promise:D:)

Returns a Supply that will emit the result of the Promise being Kept or quit with the cause if the Promise is Broken.

## 142.1.16 sub await

    multi sub await(Promise:D)
    multi sub await(*@)

Waits until one or more promises are all fulfilled, and then returns their values. Also works on channels. Any broken promises will rethrow their exceptions.

# 143 class Proxy

Item container with custom storage and retrieval

    class Proxy { ... }

A Proxy is an object that allows you to execute whenever a value is retrieved from a container (FETCH) or when it is set (STORE).

To create a container that returns twice of what was stored in it, you do something like this:

    sub double() is rw {
        my $storage = 0;
        Proxy.new(
            FETCH => method ()     { $storage },
            STORE => method ($new) { $storage = 2 * $new }
        )
     }
     my $doubled := double();
     $doubled = 4;
     say $doubled;       # 8

# 143.1 Methods

## 143.1.1 method new

    method new(:&amp;FETCH!, :&amp;STORE!) returns Proxy:D

Creates a new Proxy object. &FETCH is called with one argument (the proxy object) when the value is accessed, and must return the value that the fetch produces. &STORE is called with two arguments (the proxy object, and the new value) when a new value is stored in the container.

# 144 role QuantHash

Collection of objects represented as hash keys

    role QuantHash does Associative { }

A QuantHash represents a set of objects, represented as the keys of a Hash. When asked to behave as a list it ignores its .values and returns only .keys (possibly replicated by weight in the case of bag types). For any QuantHash, the .total methods returns the current sum of the values.

All standard QuantHash containers have a default value that is false (such as 0 or '' or Nil or Bool::False), and keep around only those entries with non-default values, automatically deleting any entry if its value goes to that (false) default value.

# 145 class Range

Interval of ordered values

    class Range is Iterable does Positional { ... }

Ranges serve two main purposes: to generate lists of consecutive numbers or strings, and to act as a matcher to check if a number or string is within a certain range.

Ranges are constructed using one of the four possible range operators, which consist of two dots, and optionally a caret which indicates that the endpoint marked with it is excluded from the range.

    1 .. 5  # 1 &lt;= $x &lt;= 5
    1^.. 5  # 1 &lt;  $x &lt;= 5
    1 ..^5  # 1 &lt;= $x &lt;  5
    1^..^5  # 1 &lt;  $x &lt;  5

The caret is also a prefix operator for constructing numeric ranges starting from zero:

    ^$x     # same as 0 ..^ $x.Numeric

Iterating a range (or calling the list method) uses the same semantics as the ++ prefix and postfix operators, i.e., it calls the succ method on the start point, and then the generated elements.

Ranges always go from small to larger elements; if the start point is bigger than the end point, the range is considered empty.

    for 1..5 { .say }       # five iterations
    ('a' ^..^ 'f').list     # 'b', 'c', 'd', 'e'
    5 ~~ ^5;                # False
    4.5 ~~ 0..^5            # True
    (1.1..5).list;          # (1.1, 2.1, 3.1, 4.1)

Use the ... sequence operator to produce lists of elements that go from larger to smaller values, or to use offsets other than increment-by-1.

Use Inf or * (Whatever) to indicate an end point to be open-ended.

    for 1..* { .say }       # start from 1, continue until stopped
    for 1..Inf { .say }     # the same

# 145.1 Methods

## 145.1.1 method min

    method min(Range:D:)

Returns the start point of the range.

## 145.1.2 method excludes-min

    method excludes-min(Range:D:) returns Bool:D

Returns True if the start point is excluded from the range, and False otherwise.

## 145.1.3 method max

    method max(Range:D:)

Returns the end point of the range.

## 145.1.4 method excludes-max

    method excludes-max(Range:D:) returns Bool:D

Returns True if the end point is excluded from the range, and False otherwise.

## 145.1.5 method bounds

    method bounds(Range:D:) returns Positional

Returns a list consisting of the start and end point.

## 145.1.6 method infinite

    method infinite(Range:D:) returns Bool:D

Returns True if either end point was declared with Inf or *.

## 145.1.7 method is-int

    method is-int(Range:D:) returns Bool:D

Returns True if both end points are Int values.

## 145.1.8 method int-bounds

    method bounds(Range:D:) returns Positional

If the Range is an integer range (as indicated by is-int), then this method returns a list with the first and last value it will iterate over (taking into account excludes-min and excludes-max). Returns a Failure if it is not an integer range.

## 145.1.9 method minmax

Defined as:

    multi method minmax(Range:D:) returns List:D

If the Range is an integer range (as indicated by is-int), then this method returns a list with the first and last value it will iterate over (taking into account excludes-min and excludes-max). If the range is not an integer range, the method will return a two element list containing the start and end point of the range unless either of excludes-min or excludes-max are True in which case a Failure is returned.

    my $r1 = (1..5); my $r2 = (1^..5);
    say $r1.is-int, ', ', $r2.is-int;                 # True, True
    say $r1.excludes-min, ', ', $r2.excludes-min;     # False, True
    say $r1.minmax, ', ', $r2.minmax;                 # (1 5), (2 5)

    my $r3 = (1.1..5.2); my $r4 = (1.1..^5.2);
    say $r3.is-int, ', ', $r4.is-int;                 # False, False
    say $r3.excludes-max, ', ', $r4.excludes-max;     # False, True
    say $r3.minmax;                                   # (1.1 5.2)
    say $r4.minmax;                                   # Failure

## 145.1.10 method elems

    method elems(Range:D:) returns Numeric:D

Returns the number of elements in the range, e.g. when being iterated over, or when used as a List. Returns Inf if either end point was specified as Inf or *.

## 145.1.11 method list

    method list(Range:D:) returns List:D

Generates the list of elements that the range represents.

## 145.1.12 method flat

    method flat(Range:D:) returns List:D

Generates the list of elements that the range represents.

## 145.1.13 method pick

    method pick(Range:D:        ) returns Any:D
    method pick(Range:D: $number) returns Seq:D

Performs the same function as Range.list.pick, but attempts to optimize by not actually generating the list if it is not necessary.

## 145.1.14 method roll

    method roll(Range:D:        ) returns Any:D
    method roll(Range:D: $number) returns Seq:D

Performs the same function as Range.list.roll, but attempts to optimize by not actually generating the list if it is not necessary.

# 146 class Rat

Rational number (limited-precision)

    class Rat is Cool does Rational[Int, UInt64] { ... }

Rat objects store rational numbers as a pair of a numerator and denominator. Number literals with a dot but without exponent produce Rats.

    3.1;    # Rat.new(31, 10)

Thus arithmetic with short dotted-decimal numbers does not suffer from floating point errors.

To prevent the numerator and denominator from becoming pathologically large, the denominator is limited to 64 bit storage. On overflow of the denominator a Num (floating-point number) is returned instead.

For example this function crudely approximates a square root, and overflows the denominator quickly:

    sub approx-sqrt($n, $iterations) {
        my $x = $n;
        $x = ($x + $n / $x) / 2 for ^$iterations;
        return $x;
    }
    say approx-sqrt(2, 5).WHAT;     # Rat()
    say approx-sqrt(2, 10).WHAT;    # Num()

If you want arbitrary precision arithmetic with rational numbers, use the FatRat type instead.

Rat objects are immutable.

# 146.1 Methods

## 146.1.1 method perl

    multi method perl(Rat:D:) returns Str:D

Returns a string representation corresponding to the unambiguous val()-based representation of rational literals. If the number can be represented exactly in decimal, it will be. Otherwise uses the form "<3/5> ", without internal spaces, and including the angles that keep the / from being treated as a normal division operator.

    say (1/3).perl;                # &lt;1/3>
    say (2/4).perl;                # 0.5

# 147 class RatStr

Dual Value Rational number and String

    class RatStr is Rat is Str

The dual value types (often referred to as allomorphs) allow for the representation of a value as both a string and a numeric type, typically they will be created for you when the context is "stringy" but they can be determined to be numbers, such as in some quoting constructs:

    my $f = &lt;42.1>; say $f.WHAT; # (RatStr)

A RatStr can be used interchangeably where one might use a Str or a Rat :

    my $f = &lt;42.1>;
    my $i = $f + 0.1;
    my $s = $f ~ " and a bit more";

# 147.1 Methods

## 147.1.1 method new

    method new(Rat $i, Str $s)

The constructor requires both the Rat and the Str value, when constructing one directly the values can be whatever is required:

    my $f = RatStr.new(42.1, "forty two and a bit");
    say +$f; # -> 42.1
    say ~$f; # -> "forty two and a bit"

## 147.1.2 method Numeric

    method Numeric

The numeric coercion is applied when the RatStr is used in a numeric context, such as a numeric comparison or smart match against a numeric value. It will return the Rat value.

## 147.1.3 method Rat

    method Rat

Returns the Rat value of the RatStr.

## 147.1.4 method Str

Returns the string value of the RatStr.

# 147.2 Operators

## 147.2.1 infix cmp

    multi sub infix:&lt;cmp>(RatStr:D $a, RatStr:D $b)

Compare two RatStr objects. The comparison is done on the Rat value first and then on the Str value. If you want to compare in a different order then you would coerce to the Rat or Str values first:

    my $f = RatStr.new(42.1, "smaller");
    my $g = RatStr.new(43.1, "larger");
    say $f cmp $g;          # Less
    say $f.Str cmp $g.Str;  # More

# 148 role Rational

Number stored as numerator and denominator

    role Rational[::NuT, ::DeT] does Real { ... }

Rational is the common role for numbers that are stored as pairs of numerator and denominator. It is parameterized by the types of the numerator and denominator.

Built into Perl 6 are Rat and FatRat, which both do the Rational role.

# 148.1 Methods

## 148.1.1 method new

    method new(NuT:D $numerator, DeT:D $denominator) returns Rational:D

Creates a new rational object from numerator and denominator.

## 148.1.2 method numerator

    method numerator(Rational:D:) returns NuT:D

Returns the numerator.

## 148.1.3 method denominator

    method denominator(Rational:D:) returns DeT:D

Returns the denominator.

## 148.1.4 method nude

    method nude(Rational:D:) returns Positional

Returns a list of the numerator and denominator.

## 148.1.5 method norm

    method norm(Rational:D:) returns Rational:D

Returns a normalized Rational object, i.e. with positive denominator, and numerator and denominator coprime.

## 148.1.6 method base-repeating

    method base-repeating(Rational:D: Int:D() $base)

Returns a list of two strings that, when concatenated, represent the number in base $base. The second element is the one that repeats. For example:

    my ($non-rep, $repeating) = (19/3).base-repeating(10);
    say $non-rep;                               # 6.
    say $repeating;                             # 3
    printf '%s(%s)', $non-rep, $repeating;      # 6.(3)

19/3 is 6.333333... with the 3 repeating indefinitely.

If no repetition occurs, the second string is empty:

    say (5/2).base-repeating(10).perl;          # ("2.5", "")

The precision for determining the repeating group is limited to 1000 characters, above that, the second string is ???.

# 149 role Real

Non-complex number

    role Real does Numeric { ... }

Common role for non-Complex numbers.

# 149.1 Methods

## 149.1.1 method Rat

    method Rat(Real:D: Real $epsilon = 1e-6)

Converts the number to a Rat with the precision $epsilon.

## 149.1.2 routine rand

    sub term:&lt;rand> returns Num:D
    method rand(Real:D:) returns Real:D

Returns a pseudo-random number between zero and the number.

The term form returns a pseudo-random Num between 0e0 and 1e0.

## 149.1.3 method sign

    method sign(Real:D:)

Returns -1 if the number is negative, 0 if it is zero and 1 otherwise.

## 149.1.4 method round

    method round(Real:D: $scale = 1)

Rounds the number to scale $scale. If $scale is 1, rounds to an integer. If scale is 0.1, rounds to one digit after the comma etc.

## 149.1.5 method floor

    method floor(Real:D) returns Int:D

Return the largest integer not greater than the number.

## 149.1.6 method ceiling

    method ceiling(Real:D) returns Int:D

Returns the smallest integer not less than the number.

## 149.1.7 method truncate

    method truncate(Real:D) returns Int:D

Rounds the number towards zero.

## 149.1.8 method base

    method base(Real:D: Int:D $base where 2..36, $digits?) returns Str:D

Converts the number to a string, using $base as base. For $base larger than ten, capital Latin letters are used.

    255.base(16)            # 'FF'

The optional $digits argument asks for that many digits of fraction (which may not be negative). If omitted, a reasonable default is chosen based on type. For Int this default is 0. For Num, the default is 8. For Rational, the number of places is scaled to the size of the denominator, with a minimum of 6.

The final digit produced is always rounded.

    say pi.base(10, 5);     # 3.14159

To convert a string to a number use the :16($string) notation where 16 is the base:

    say :16("FF")           # 255
    say :23("FF")           # 360

# 150 class Regex

String pattern

    class Regex is Method { }

A regex is a kind of pattern that describes a set of strings. The process of finding out whether a given string is in the set is called matching. The result of such a matching is a Match object, which evaluates to True in boolean context if the string is in the set.

A regex is typically constructed by a regex literal

    rx/ ^ab /;      # describes all strings starting with 'ab'
    / ^ ab /;       # same
    rx/ \d ** 2/;   # describes all strings containing at least two digits

To match a string against a regex, you can use the smart match operator:

    my $match = 'abc' ~~ rx/ ^ab /;
    say $match.Bool;                # True
    say $match.orig;                # abc
    say $match.Str;                 # ab
    say $match.from;                # 0
    say $match.to;                  # 2

Or you can evaluate the regex in boolean context, in which case it matches against the $_ variable

    $_ = 'abc';
    if / ^ab / {
        say '"abc" begins with "ab"';
    }
    else {
        say 'This is a weird alternative Universe';
    }

# 150.1 Methods

## 150.1.1 method ACCEPTS

    multi method ACCEPTS(Regex:D: Mu) returns Match:D
    multi method ACCEPTS(Regex:D: @)
    multi method ACCEPTS(Regex:D: %)

Matches the regex against the argument passed in. If the argument is Positional, it returns the first successful match of any list item. If the argument is Associative, it returns the first successful match of any key. Otherwise it interprets the argument as a Str and matches against it.

In the case of Positional and Associative matches, Nil is returned on failure.

## 150.1.2 method Bool

    multi method Bool(Regex:D:) returns Bool:D

Matches against the caller's $_ variable, and returns True for a match or False for no match.

# 151 class Routine

Code object with its own lexical scope and `return` handling

    class Routine is Block { }

A Routine is a code object meant for larger unities of code than Block. Routine is the common superclass for Sub and Method, the two primary code objects for code reuse.

Routines serve as a scope limiter for return (i.e. a return returns from the innermost outer Routine).

Routine is also the level at which multiness (multi subs and multi methods) are handled.

# 151.1 Methods

## 151.1.1 method name

    method name(Routine:D:) returns Str:D

Returns the name of the sub or method.

## 151.1.2 method multi

    method multi(Routine:D:) returns Bool:D

Returns True if the routine is a multi sub or method.

## 151.1.3 method candidates

    method candidates(Routine:D:) returns Positional:D

Returns a list of multi candidates, or a one-element list with itself if it's not a multi

## 151.1.4 method wrap

    method wrap(Routine:D: &amp;wrapper)

Wraps (i.e. in-place modifies) the routine. That means a call to this routine first calls &wrapper, which then can (but doesn't have to) call the original routine with the callsame, callwith, nextsame and nextwith dispatchers. The return value from the routine is also the return value from the wrapper.

wrap returns a wrap handler, which you can pass to unwrap to restore the original routine.

## 151.1.5 method unwrap

    method unwrap(Routine:D: $wraphandler)

Restores the original routine after it has been wrapped with wrap.

## 151.1.6 method yada

    method yada(Routine:D:) returns Bool:D

Returns True if the routine is a stub

    say (sub f() { ... }).yada;      # True
    say (sub g() { 1;  }).yada;      # False

## 151.1.7 trait is cached

    multi sub trait_mod:&lt;is>(Routine $r, :$cached!)

NOTE: this feature is currently EXPERIMENTAL.

Causes the return value of a routine to be stored, so that when subsequent calls with the same list of arguments are made, the stored value can be returned immediately instead of re-running the routine.

Useful when storing and returning the computed value is much faster than re-computing it every time, and when the time saving trumps the cost of the use of more memory.

Even if the arguments passed to the routine are "reference types" (such as objects or arrays), then for the purpose of caching they will only be compared based on their contents. Thus the second invocation will hit the cache in this case:

    say foo( [1, 2, 3] );   # runs foo
    say foo( [1, 2, 3] );   # doesn't run foo, uses cached value

    use experimental :cached;

     sub nth-prime(Int:D $x where * > 0) is cached {
         say "Calculating {$x}th prime";
         return (2..*).grep(*.is-prime)[$x - 1];
     }

     say nth-prime(43);
     say nth-prime(43);
     say nth-prime(43);

produces this output:

    Calculating 43th prime
     191
     191
     191

## 151.1.8 trait is pure

    multi sub trait_mod:&lt;is>(Routine $r, :!$pure)

Marks a subroutine as pure, that is, it asserts that for the same input, it will always produce the same output without any additional side effects.

This is a hint to the compiler that it can constant-fold calls to such functions when the arguments are known at compile time.

    sub double(Numeric:D $x) is pure {
        2 * $x;
    }

## 151.1.9 trait is rw

    multi sub trait_mod:&lt;is>(Routine $r, :$rw!)

When a routine is modified with this trait, its return value will be writable. This is useful when returning variables or writable elements of hashes or arrays, for example:

    sub walk(\thing, *@keys) is rw {
         my $current := thing;
         for @keys -> $k {
             if $k ~~ Int {
                 $current := $current[$k];
             }
             else {
                 $current := $current{$k};
             }
         }
         $current;
     }

     my %hash;
     walk(%hash, 'some', 'key', 1, 2) = 'autovivified';

     say %hash.perl;

produces

    ("some" => {"key" => [Any, [Any, Any, "autovivified"]]}).hash

Note that return marks return values as read only; if you need an early exit from an is rw routine, you have to use return-rw instead.

## 151.1.10 trait is export

    multi sub trait_mod:&lt;is>(Routine $r, :$export!)

Marks a routine as exported to the rest of the world

    module Foo {
         sub double($x)  <b>is export</b>  {
             2 * $x
         }
     }

     import Foo;         # makes sub double available
     say double 21;      # 42

From inside another file you'd say use Foo; to load a module and import the exported functions.

See Exporting and Selective Importing Modules for more details.

## 151.1.11 trait is DEPRECATED

    multi sub trait_mod:&lt;is>(Routine:D $r, :$DEPRECATED!)

Marks a routine as deprecated, optionally with a message what to use instead.

This code

    sub f() is DEPRECATED('the literal 42') { 42 }
     say f();

produces this output:

    42
     Saw 1 occurrence of deprecated code.
     ================================================================================
     Sub f (from GLOBAL) seen at:
       deprecated.p6, line 2
     Please use the literal 42 instead.
     --------------------------------------------------------------------------------
     Please contact the author to have these occurrences of deprecated code
     adapted, so that this message will disappear!

## 151.1.12 trait is hidden-from-backtrace

    multi sub trait_mod:&lt;is>(Routine:D, :$hidden-from-backtrace!)

Hides a routine from showing up in a default backtrace. For example

    sub inner { die "OH NOEZ" };
     sub outer { inner() };
     outer();

produces the error message and backtrace

    OH NOEZ
       in sub inner at bt.p6:1
       in sub outer at bt.p6:2
       in block &lt;unit> at bt.p6:3

but if inner is marked with hidden-from-backtrace

    sub inner is hidden-from-backtrace { die "OH NOEZ" };
     sub outer { inner() };
     outer();

the error backtrace does not show it:

    OH NOEZ
       in sub outer at bt.p6:2
       in block &lt;unit> at bt.p6:3

TODO: explain export tags

# 152 class Scalar

A mostly transparent container used for indirections

    class Scalar { ... }

A Scalar is an internal indirection which is for most purposes invisible during ordinary use of Perl 6. It is the default container type associated with the $ sigil. A literal Scalar may be placed around a literal value by enclosing the value in $(…). This notation will appear in the output of a .perl method in certain places where it is important to note the presence of Scalars.

When a value is assigned to a $-sigiled variable, the variable will actually bind to a Scalar, which in turn will bind to the value. When a Scalar is assigned to a $-sigiled variable, the value bound to by that Scalar will be bound to the Scalar which that variable was bound to (a new one will be created if necessary.)

In addition Scalars delegate all method calls to the value which they contain. As such, Scalars are for the most part invisible. There is, however, one important place where Scalars have a visible impact: a Scalar will shield its contents from flattening by most Perl 6 core list operations.

A $-sigiled variable may be bound directly to a value with no intermediate Scalar using the binding operator :=. You can tell if this has been done by examining the introspective pseudo-method .VAR:

    my $a = 1;
    $a.WHAT.say;     # says "(Int)"
    $a.VAR.WHAT.say; # says "(Scalar)"
    my $b := 1;
    $b.WHAT.say;     # says "(Int)"
    $b.VAR.WHAT.say; # says "(Int)"

This same thing happens when values are assigned to an element of an Array, however, Lists directly contain their values:

    my @a = 1, 2, 3;
    @a[0].WHAT.say;            # says "(Int)"
    @a[0].VAR.WHAT.say;        # says "(Scalar)"
    [1, 2, 3][0].WHAT.say;     # says "(Int)"
    [1, 2, 3][0].VAR.WHAT.say; # says "(Scalar)"
    (1, 2, 3)[0].WHAT.say;     # says "(Int)"
    (1, 2, 3)[0].VAR.WHAT.say; # says "(Int)"

Array elements may be bound directly to values using := as well, however this is to be discouraged as it may lead to confusion. Doing so will break exact round-tripping of .perl output -- since Arrays are assumed to place Scalars around each element, Scalars are not denoted with $ in the output of Array.perl.

    [1, $(2, 3)].perl.say      # says [1, (2, 3)]
    (1, $(2, 3)).perl.say      # says (1, $(2, 3))

Binding a Scalar to a $-sigiled variable replaces the existing Scalar in that variable, if any, with the given Scalar. That means more than one variable may refer to the same Scalar. Because the Scalar may be mutated, this makes it possible to alter the value of both variables by altering only one of them:

    my $a = 1;
    my $b := $a;
    $b = 2;
    $a.say;       # says "2"

SSA-style constants bind directly to their value with no intervening Scalar, even when =/assignment is used. They may be forced to use a Scalar by assigning a $-sigiled variable to them, at which point, they behave entirely like $-sigiled variables.

    my \c = 1;
    c.WHAT.say;              # says "(Int)"
    c.VAR.WHAT.say;          # says "(Int)"
    my $a = 1;
    my \d = $a;              # just "my \d = $ = 1" works, too
    d.WHAT.say;              # says "(Int)"
    d.VAR.WHAT.say;          # says "(Scalar)"
    d = 2;                   # ok
    c = 2;                   # error, cannot modify an immutable Int

# 153 role Scheduler

Scheme for automatically assigning tasks to threads

    role Scheduler {
        has &amp;.uncaught_handler is rw
    }

Common role for schedulers. A scheduler is a piece of code that determines which resources to use to run which task, and when.

Some operations for example on Proc::Async, Promise, Supply allow you to specify a scheduler explicitly; they generally expect those schedulers to follow the interface defined by Scheduler

# 153.1 Methods

## 153.1.1 method uncaught_handler

    method uncaught_handler() is rw

RW-Accessor for the handler that is caught for uncaught exceptions from the code that is being scheduled and run.

## 153.1.2 method cue

    method cue(:&amp;code, Instant :$at, :$in, :$every, :$times = 1; :&amp;catch)

Schedules a callable (&code) for execution. The adverbs control when and how the code is run:

$at can be an Instant before which the code won't be run. Alternatively $in is the number of seconds (possibly fractional) to wait before running the code.

If $every is specified, it is interpreted as the number of seconds (possibly fractional) to wait before re-executing the code.

$times tells the scheduler how many times to run the code.

&catch is called with the Exception as its sole argument if &code dies.

# 154 class Semaphore

Control access to shared resources by multiple processes

    class Semaphore { }

Protect your shared code, data or device access using semaphores. An example is a printer manager managing a pool of printers without the need of storing print jobs when all printers are occupied. The next job is just blocked until a printer becomes available.

    class print-manager {
      has Array $!printers;
      has Semaphore $!print-control;

      method BUILD( Int:D :$nbr-printers ) {
        for ^$nbr-printers -> $pc {
          $!printers[$pc] = { :name{"printer-$pc"}, ... };
        }

        $!print-control .= new($nbr-printers);
      }

      method print( $print-job ) {
        $!print-control.acquire;

        find-available-printer-and-print-it($job);

        $!print-control.release;
      }
    }

Another example is a protection around code updating sensitive data. In such a case the semaphore is typically initialized to 1.

It is important to have a release on every exit of your program! While this is obvious, it is easy to fall in traps such as throwing an exception caused by some event. When the program dies there is no problem. When the exception is caught your program might eventually come back to the acquire method and will hang indefinitely.

# 154.1 Methods

## 154.1.1 method new

    method new( int $permits )

Initialize the semaphore with the number of permitted accesses. E.g. when set to 2, program threads can pass the acquire method twice until it blocks on the third time acquire is called.

## 154.1.2 method acquire

    method acquire()

Acquire access. When other threads have called the method before and the the number of permits are used up, the process blocks until threads passed before releases the semaphore.

## 154.1.3 method try_acquire

    method try_acquire() returns Bool

Same as acquire but will not block. Instead it returns True if access is permitted or False otherwise.

## 154.1.4 method release

    method release()

Release the semaphore raising the number of permissions. Any blocked thread will get access after that.

# 155 class Seq

An iterable, lazy sequence of values

    class Seq is Cool does Iterable does PositionalBindFailover { }

A Seq represents anything that can lazily produce a sequence of values. A Seq is born in a state where iterating it will consume the values. However, calling .cache on a Seq will return a List that is still lazy, but stores the generated values for later access. The same is true when assigning a Seq to an array.

A typical use case is method lines in IO::Handle , which could use quite much memory if it stored all the lines read from the file. So

    for open('README').lines -> $line {
        say $line;
    }

won't keep all lines from the file in memory.

This implies that you cannot iterate the same Seq object twice (otherwise it couldn't throw away old values), so this dies:

    my @a = 1, 2, 3;
     my @b = &lt;a b c>;
     my \c = @a Z=> @b;
     .say for c;
     .say for c; # dies with "This Seq has already been iterated, and its values consumed [...]"
                 # of type  <a href="#_type_X::Seq::Consumed.pod6">X::Seq::Consumed</a>

A high-level construct to generate a Seq is gather/take, as well as many built-in methods like map and grep, low-level constructors to create a Seq from an iterator or from looping constructs are available too.

# 155.1 Methods

## 155.1.1 method new

    method new(Iterator:D $iter) returns Seq:D

Creates a new Seq object from the iterator passed as the single argument.

## 155.1.2 method iterator

    method iterator(Seq:D:) returns Iterator:D

Returns the underlying iterator, and marks the invocant as consumed. If called on an already consumed sequence, throws an error of type X::Seq::Consumed.

## 155.1.3 method is-lazy

    method is-lazy(Seq:D:) returns Bool:D

Returns True if the sequence is lazy and potentially infinite, and False otherwise. If called on an already consumed sequence, throws an error of type X::Seq::Consumed.

## 155.1.4 method eager

    method eager(Seq:D:) returns Bool:D

Returns an eagerly evaluated List based on the invocant sequence, and marks it as consumed. If called on an already consumed sequence, throws an error of type X::Seq::Consumed.

## 155.1.5 method from-loop

    proto method from-loop(|) returns Seq:D
    multi method from-loop(&amp;body)
    multi method from-loop(&amp;body, &amp;cond, :$repeat)
    multi method from-loop(&amp;body, &amp;cond, &amp;afterward)

Creates a new Seq based callbacks.

The first form produces an infinite Seq by calling &body each time a new element is requested, using the return value from &body as the item. This emulates (or implements) a loop { body } construct.

The second form calls &cond before each call to &body, and terminates the sequence if &cond returns a false value. If $repeat is set to a true value, the first call to &cond is omitted, and &body called right away. This emulates (or implements) while cond { body } and repeat { body } while cond loops.

The third form enables C-style looping by calling a third callback, &afterward, after each call to &body.

# 156 class Set

Immutable collection of distinct objects

    class Set does Setty { }

A Set is an immutable set, meaning a collection of distinct elements in no particular order. (For mutable sets, see SetHash instead.)

Objects/values of any type are allowed as set elements. Within a Set, every element is guaranteed to be unique (in the sense that no two elements would compare positively with the === operator):

    my $fruits = set &lt;peach apple orange apple apple>;

     say $fruits.elems;      # 3
     say $fruits.keys.sort;  # apple orange peach

Sets can be treated as object hashes using the { } postcircumfix operator, which returns the value True for keys that are elements of the set, and False for keys that aren't:

    say $fruits&lt;apple>;  # True
    say $fruits&lt;kiwi>;   # False

# 156.1 Creating Set objects

Sets can be composed using the set subroutine (or Set.new, for which it is a shorthand). Any positional parameters, regardless of their type, become elements of the set:

    my $n = set "zero" => 0, "one" => 1, "two" => 2;
    say $n.keys.perl;        # ("zero" => 0, "one" => 1, "two" => 2).list
    say $n.keys.map(&amp;WHAT);  # (Pair) (Pair) (Pair)

Alternatively, the .Set coercer (or its functional form, Set()) can be called on an existing object to coerce it to a Set. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a set with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the set - and keys mapped to values which boolify to False are skipped:

    my $n = ("zero" => 0, "one" => 1, "two" => 2).Set;
    say $n.keys.perl;        # ("one", "two").list
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)

Furthermore, you can get a Set by using set operators (see next section) on objects of other types such as List, which will internally call .Set on them before performing the operation. Be aware of the tight precedence of those operators though, which may require you to use parens around arguments:

    say (1..5) (^) 4;  # set(1, 2, 3, 5)

# 156.2 Operators

Perl 6 provides common set operators, which can take Sets (or any other collections) as input, and return result sets as new Set objects. For example:

    my ($a, $b) = set(1, 2, 3), set(2, 4);

     say $a (&lt;) $b;  # False
     say $a (&amp;) $b;  # set(2)
     say $a (^) $b;  # set(1, 3, 4)

     # Unicode versions:
     say $a ⊂ $b;  # False
     say $a ∩ $b;  # set(2)
     say $a ⊖ $b;  # set(1, 3, 4)

See Set/Bag Operators for a complete list of set operators with detailed explanations.

# 156.3 Subroutines

## 156.3.1 sub set

    sub set(*@args --> Set)

Creates a Set from the given @args

# 156.4 See Also

Sets, Bags, and Mixes

# 157 class SetHash

Mutable collection of distinct objects

    class SetHash does Setty { }

A SetHash is a mutable set, meaning a collection of distinct elements in no particular order. (For immutable sets, see Set instead.)

Objects/values of any type are allowed as set elements. Within a Set, every element is guaranteed to be unique (in the sense that no two elements would compare positively with the === operator):

    my $fruits = &lt;peach apple orange apple apple>.SetHash;

     say $fruits.elems;      # 3
     say $fruits.keys.sort;  # apple orange peach

SetHashes can be treated as object hashes using the { } postcircumfix operator, which returns the value True for keys that are elements of the set, and False for keys that aren't. Assigning a value that boolifies to True or False, respectively, can be used to add or remove a set element:

    say $fruits&lt;apple>;     # True
     say $fruits&lt;kiwi>;      # False

     $fruits&lt;apple kiwi> = False, True;
     say $fruits.keys.sort;  # kiwi orange peach

# 157.1 Creating SetHash objects

SetHashes can be composed using SetHash.new. Any positional parameters, regardless of their type, become elements of the set:

    my $n = SetHash.new: "zero" => 0, "one" => 1, "two" => 2;
    say $n.keys.perl;        # ("zero" => 0, "one" => 1, "two" => 2).list
    say $n.keys.map(&amp;WHAT);  # (Pair) (Pair) (Pair)

Alternatively, the .SetHash coercer (or its functional form, SetHash()) can be called on an existing object to coerce it to a SetHash. Its semantics depend on the type and contents of the object. In general it evaluates the object in list context and creates a set with the resulting items as elements, although for Hash-like objects or Pair items, only the keys become elements of the set - and keys mapped to values which boolify to False are skipped:

    my $n = ("zero" => 0, "one" => 1, "two" => 2).SetHash;
    say $n.keys.perl;        # ("one", "two").list
    say $n.keys.map(&amp;WHAT);  # (Str) (Str)

# 157.2 Operators

Perl 6 provides common set operators, which can take SetHashes (or any other collections) as input, although result sets are returned as immutable Sets. For example:

    my ($a, $b) = SetHash.new(1, 2, 3), SetHash.new(2, 4);

     say $a (&lt;) $b;  # False
     say $a (&amp;) $b;  # set(2)
     say $a (^) $b;  # set(1, 3, 4)
     say $a (|) $b;  # set(1, 2, 3, 4)

     # Unicode versions:
     say $a ⊂ $b;  # False
     say $a ∩ $b;  # set(2)
     say $a ⊖ $b;  # set(1, 3, 4)
     say $a ∪ $b;  # set(1, 2, 3, 4)

See Set/Bag Operators for a complete list of set operators with detailed explanations.

# 157.3 See Also

Sets, Bags, and Mixes

# 158 role Setty

Collection of distinct objects

    role Setty does QuantHash { }

A role for collections which make sure that each element can only appear once. See Set and SetHash.

# 158.1 Methods

## 158.1.1 method grab

    method grab($count = 1)

Removes and returns $count elements chosen at random (without repetition) from the set.

If * is passed as $count, or $count is greater than or equal to the size of the set, then all its elements are removed and returned in random order.

Only works on mutable sets; When used on an immutable set, it results in an exception.

## 158.1.2 method grabpairs

    method grabpairs($count = 1)

Removes $count elements chosen at random (without repetition) from the set, and returns a list of Pair objects whose keys are the grabbed elements and whose values are True.

If * is passed as $count, or $count is greater than or equal to the size of the set, then all its elements are removed and returned as Pairs in the aforementioned way in random order.

Only works on mutable sets; When used on an immutable set, it results in an exception.

## 158.1.3 method pick

    multi method pick($count = 1)

Returns $count elements chosen at random (without repetition) from the set.

If * is passed as $count, or $count is greater than or equal to the size of the set, then all its elements are returned in random order.

## 158.1.4 method roll

    multi method roll($count = 1)

Returns a lazy list of $count elements, each randomly selected from the set. Each random choice is made independently, like a separate die roll where each die face is a set element.

If * is passed as $count, the list is infinite.

## 158.1.5 method keys

Returns a list of all elements of the set.

## 158.1.6 method values

Returns a list containing as many True values as the set has elements.

## 158.1.7 method kv

Returns a list of the set's elements and True values interleaved.

## 158.1.8 method elems

    method elems(--> Int)

The number of elements of the set.

## 158.1.9 method total

    method total(--> Int)

The total of all the values of the QuantHash object. For a Setty object, this is just the number of elements.

## 158.1.10 method ACCEPTS

    method ACCEPTS($other)

Returns True if $other and self contain all the same elements, and no others.

# 158.2 See Also

Sets, Bags, and Mixes

# 159 class Signature

Parameter list pattern

    class Signature { ... }

A signature is a static description of the parameter list of a code object. That is, it describes what and how many arguments you need to pass to the code or function in order to call it.

Passing arguments to a signature binds the arguments, contained in a Capture, to the signature.

# 159.1 Signature Literals

Signatures appear in parenthesis after subroutine and method names, on blocks after a -> or <-> arrow, as the input to variable declarators like my , or as a separate term starting with a colon.

    sub f <b>($x)</b>  { }
     #    ^^^^ Signature of sub f
     method x <b>()</b>  { }
     #       ^^ Signature of a method
     my $s = sub  <b>(*@a)</b>  { }
     #           ^^^^^ Signature of an anonymous function

     for @list ->  <b>$x</b>  { }
     #            ^^   Signature of a  <a href="#_type_Block.pod6">block</a>

     my  <b>($a, @b)</b>  = 5, (6, 7, 8);
     #  ^^^^^^^^ Signature of a variable declarator

     my $sig =  <b>:($a, $b)</b> ;
     #          ^^^^^^^^ Standalone Signature object

Signature literals can be used to define the signature of a callback or a closure.

    sub f(&amp;c:(Int)){}
    sub will-work(Int){}
    sub won't-work(Str){}
    f(&amp;will-work);
    f(&amp;won't-work); # fails at runtime
    f(-> Int { 'this works too' } );

Smart matching signatures against a List is supported.

    my $sig = :(Int $i, Str $s);
    say (10, 'answer') ~~ $sig;
    # OUTPUT«True␤»
    given ('answer', 10) {
        when :(Str, Int) { say 'match' }
        when $sig { say 'mismatch' }
    }
    # OUTPUT«match␤»

When smart matching against a Hash, the signature is assumed to consist of the keys of the Hash.

    my %h = left => 1, right => 2;
    say %h ~~ :(:$left, :$right);
    # OUTPUT«True␤»

## 159.1.1 Parameter Separators

A signature consists of zero or more parameters , separated by comma.

    :($a <b>,</b>  @b <b>,</b>  %c)
     sub add($a <b>,</b>  $b) { $a + $b }

As an exception the first parameter may be followed by a colon instead of a comma to mark the invocant of a method. The invocant is the object that was used to call the method, which is usually bound to self . By specifying it in the signature, you can change the variable name it is bound to.

    :( <b>$a:</b>  @b, %c)       # first argument is the invocant

      <a href="#_syntax_class.pod6">class</a>  Foo {
         method whoami( <b>$me:</b> ) {
             "Well I'm class  <b>$me</b> .^ <a href="#_routine_name.pod6">name</a> (), of course!"
         }
     }
     say Foo.whoami; # => Well I'm class Foo, of course!

## 159.1.2 Type Constraints

Parameters can optionally have a type constraint (the default is Any ). These can be used to restrict the allowed input to a function.

    :( <b> <a href="#_type_Int.pod6">Int</a> </b>  $a,  <b> <a href="#_type_Str.pod6">Str</a> </b>  $b)

     sub divisors( <b> <a href="#_type_Int.pod6">Int</a> </b>  $n) { $_ if $n  <a href="%%">%%</a>  $_ for 1..$n }
     divisors 2.5; # !!! Calling 'divisors' will never work with argument types ( <a href="#_type_Rat.pod6">Rat</a> )

Anonymous arguments are fine too, if a parameter is only needed for its type constraint.

    :( <b>$</b> ,  <b>@</b> , %a)               # two anonymous and a "normal" parameter
     :( <b> <a href="#_type_Int.pod6">Int</a> </b> ,  <b> <a href="#_type_Positional.pod6">Positional</a> </b> )  # just a type is also fine (two parameters)
     sub baz( <b> <a href="#_type_Str.pod6">Str</a> </b> ) { "Got passed a Str" }

Type constraints may also be type captures.

In addition to those nominal types, additional constraints can be placed on parameters in the form of code blocks which must return a true value to pass the type check

    sub f(Real $x where { $x > 0 }, Real $y where { $y >= $x }) { }

In fact it doesn't need to be a code block, anything on the right of the where-block will be used to smart-match the argument against it. So you can also write

    multi factorial(Int $ where 0) { 1 }
    multi factorial(Int $x)        { $x * factorial($x - 1) }

The first of those can be shortened to

    multi factorial(0) { 1 }

i.e., you can use a literal directly as a type and value constraint on an anonymous parameter.

### 159.1.2.1 Constraining Defined and Undefined Values

Normally, a type constraint only checks whether the value passed is of the correct type.

    sub limit-lines (Str $s, Int $limit) {
         my @lines = $s.lines;
         @lines[0 .. min @lines.elems, $limit].join("\n")
     }
     say (limit-lines "a \n b \n c \n d \n", 3).perl; # "a \n b \n c "
     say limit-lines Str,      3;  # Uh-oh. Dies with "Cannot call 'lines';"
     say limit-lines "a \n b", Int # Always returns the max number of lines

In this case, we really only want to deal with defined strings. To do this, we use the :D type constraint.

    sub limit-lines (Str <b>:D</b>  $s, Int $limit) {
         ...
     }
     # Dies with "Parameter '$s' requires an instance, but a type object was passed
     #   in sub limit-lines"
     say limit-lines Str, 3;

This is much better than the way the program failed before, since here the reason for failure is clearer.

It's also possible undefined types are the only ones that make sense for a routine to accept. This can be constrained with the :U type constraint. For example, we can turn the &limit-lines into a multi function to make use of the :U constraint.

    multi limit-lines (Str $s, Int:D $limit) {
         ...
     }
     multi limit-lines (Str $s, Int <b>:U</b>  $) { $s }
     say limit-lines "a \n b \n c", Int; # "a \n b \n c"

For explicitly indicating the normal behaviour, :_ can be used, but this is unnecessary. :(Num:_ $) is the same as :(Num $).

### 159.1.2.2 Constraining signatures of Callables

To constrain block and subroutine references based on their signature write the signature after the argument name.

    sub f(&amp;c:(Int, Str)) { say c(10, 'ten') };
    sub g(Int $i, Str $s){ $s ~ $i };
    f(&amp;g);
    # OUTPUT«ten10␤»

### 159.1.2.3 Constraining Return Types

The token --> followed by a type will force a type check on successful execution of a routine. The return type arrow has to be placed at the end of the parameter list. The keyword returns following a signature declaration has the same function. Nil is considered as being defined for the type check. Type objects and thus undefined values will pass the test unless the type smiley :D is used.

    sub foo(--> Int) { my Int $i; $i };
    sub foo(--> Int:D) { 1 }
    sub foo() returns Int { 1 };
    sub does-not-work(--> Int) { "" }; # throws X::TypeCheck::Return

If the type constraint is a constant expression, it is used as the return value of the routine. Any return statement in that routine has to be argumentless.

    sub foo(--> 123) { return }

Nil and Failure are always allowed as return types, regardless of any type constraint.

    sub foo(--> Int) { Nil };
    say foo.perl; # Nil

Type captures and coercion types are not supported.

### 159.1.2.4 Coercion Type

To accept one type but coerce it automatically to another, use the accepted type as an argument to the target type. If the accepted type is Any it can be omitted.

    sub f(Int(Str) $want-int, Str() $want-str){ say $want-int.WHAT, $want-str.WHAT }
    f '10', 10;
    # OUTPUT«(Int)(Str)␤»

## 159.1.3 Slurpy (A.K.A. Variadic) Parameters

An array or hash parameter can be marked as slurpy by leading asterisk(s), which means it can bind to an arbitrary amount of arguments (zero or more).

These are called "slurpy" because they slurp up any remaining arguments to a function, like someone slurping up noodles.

    :($a, @b)              # exactly two arguments, where the second one must be Positional
     :($a,  <b>*@b</b> )          # at least one argument, @b slurps up any beyond that
     :( <b>*%h</b> )              # no positional arguments, but any number of named arguments

    sub one-arg (@)     { }
     sub slurpy  ( <b>*@</b> ) { }
     one-arg(5, 6, 7) ; # !!! too many arguments
     one-arg (5, 6, 7); # ok, same as one-arg((5, 6, 7))
     slurpy  (5, 6, 7); # ok
     one-arg  5, 6, 7 ; # !!! too many arguments
     slurpy   5, 6, 7 ; # ok

    sub named-names ( <b>*%named-args</b> ) { %named-args. <a href="#_routine_keys.pod6">keys</a>  }
     say named-names :foo(42) :bar&lt;baz> # => foo bar

Note that positional parameters aren't allowed after slurpy parameters.

    :(*@args, $last) # !!! Cannot put required parameter after variadic parameters

Slurpy parameters declared with one asterisk will flatten arguments by dissolving one or more layers of bare Iterables. Slurpy parameters declared with two stars do not do so:

    sub a(*@a) { @a.join("|").say };
    a(1, [1, 2], ([3, 4], 5)); # 1|1|2|3|4|5
    sub b(**@b) { @b.join("|").say };
    b(1, [1, 2], ([3, 4], 5)); # 1|1 2|3 4 5

Normally a slurpy parameter will create an Array, create a new Scalar container for each argument, and assign the value from each argument to those Scalars. If the original argument also had an intermediary Scalar it is bypassed during this process, and is not available inside the called function.

Slurpy parameters have special behaviors when combined with some traits and modifiers, as described below.

## 159.1.4 Single Argument Rule Slurpy

The single argument rule allows to treat arguments to subroutines, for-loops and list constructors based on context. Many methods on positional types can work with a single arguments the same way as with a list or arguments. Using +@ as a sigil in a Signature provides syntactic sugar to make that task a little easier. Any single argument of a non-positional type will be promoted to a list with a single item.

    sub f(+@a){ dd @a };
    f(1);
    # OUTPUT«[1]␤»
    f(1, 2, 3);
    # OUTPUT«[1, 2, 3]␤»
    my @b = &lt;a b c>;
    f @b;
    # OUTPUT«["a", "b", "c"]␤»

## 159.1.5 Type Captures

Type Captures allow to defer the specification of a type constraint to the time the function is called. They allow to refer to a type both in the signature and the function body.

    sub f(::T $p1, T $p2, ::C){
        # $p1 and $p2 are of the same type T, that we don't know yet
        # C will hold a type we derive from a type object or value
        my C $closure = $p1 / $p2;
            return sub (T $p1) {
                    $closure * $p1;
            }
    }

    # The first parameter is Int and so must be the 2nd.
    # We derive the 3rd type from calling the operator that is used in &amp;f.
    my &amp;s = f(10, 2, Int.new / Int.new);
    say s(2); # 10 / 2 * 2 == 10

## 159.1.6 Positional vs. Named

A parameter can be positional or named. All parameters are positional, except slurpy hash parameters and parameters marked with a leading colon :.

    :($a)               # a positional parameter
    :(:$a)              # a named parameter of name 'a'
    :(*@a)              # a slurpy positional parameter
    :(*%h)              # a slurpy named parameter

On the caller side, positional arguments are passed in the same order as the parameters were declared.

    sub pos($x, $y) { "x=$x y=$y" }
    pos(4, 5);                          # x=4 y=5

In the case of named arguments and parameters, only the name is used for mapping arguments to parameters

        sub named(:$x, :$y) { "x=$x y=$y" }
         named( y  <a href="=&gt;">=></a>  5, x => 4);             # x=4 y=5

It is possible to have a different name for a named parameter than the variable name:

    sub named(:official($private) { "Official business!" if $private }
    named :official;

Aliases are also possible that way:

    sub paint( :color(:colour($c)) ) { }    # 'color' and 'colour' are both OK
    sub paint( :color(:$colour) ) { }       # same API for the caller

A function with named arguments can be called dynamically, dereferencing a Pair with | to turn it into a named argument.

    multi f(:$named){ note &amp;?ROUTINE.signature };
    multi f(:$also-named){ note &amp;?ROUTINE.signature };
    for 'named', 'also-named' -> $n {
        f(|($n => rand))                    # «(:$named)␤(:$also-named)␤»
    }

    my $pair = :named(1);
    f |$pair;                               # «(:$named)␤»

The same can be used to convert a Hash into named arguments.

    my %pairs = also-named => 4;
    f |%pairs;                              # «(:$also-named)␤»

## 159.1.7 Optional and Mandatory Parameters

Positional parameters are mandatory by default, and can be made optional with a default value or a trailing question mark:

    :(Str $id)          # required parameter
    :($base = 10)       # optional parameter, default value 10
    :(Int $x?)          # optional parameter, default is the Int type object

Named parameters are optional by default, and can be made mandatory with a trailing exclamation mark:

    :(:%config)         # optional parameter
    :(:$debug = False)  # optional parameter, defaults to False
    :(:$name!)          # mandatory 'name' named parameter

Default values can depend on previous parameters, and are (at least notionally) computed anew for each call

    :($goal, $accuracy = $goal / 100);
    :(:$excludes = ['.', '..']);        # a new Array for every call

## 159.1.8 Destructuring Parameters

Parameters can be followed by a sub-signature in brackets, which will destructure the argument given. The destructuring of a list is just its elements:

        sub first(@array  <b>($first, *@rest)</b> ) { $first }

or

        sub first( <b>[$f, *@]</b> ) { $f }

While the destructuring of a hash is its pairs:

        sub all-dimensions (%  <b>(:length(:$x), :width(:$y), :depth(:$z))</b> ) {
             $x  <a href="#_routine_andthen.pod6">andthen</a>  $y andthen $z andthen True
         }

In general, an object is destructured based on its attributes. A common idiom is to unpack a Pair 's key and value in a for loop:

        for @guest-list. <a href="#_routine_pairs.pod6">pairs</a>  ->  <b>(:key($index), :value($guest)</b> ) {
             ...
         }

However, this unpacking of objects as their attributes is only the default behavior. To make an object get destructured differently, change its Capture method.

## 159.1.9 Long Names

To exclude certain parameters from being considered in multiple dispatch, separate them with a double semi-colon.

    multi sub f(Int $i, Str $s;; :$b) { dd $i, $s, $b };
    f(10, 'answer');
    # OUTPUT«10␤"answer"␤Any $b = Any␤»

## 159.1.10 Capture Parameters

Prefixing a parameter with a vertical bar | makes the parameter a Capture , using up all the remaining positional and named arguments.

This is often used in proto definitions (like proto foo (|) {*}) to indicate that the routine's multi definitions can have any type constraints. See proto for an example.

If bound to a variable arguments can be forwarded as a whole using the slip operator |.

    sub a(Int $i, Str $s) { say $i.WHAT, $s.WHAT }
    sub b(|c) { say c.WHAT; a(|c) }
    b(42, "answer");
    # OUTPUT«(Capture)␤(Int)(Str)␤»

## 159.1.11 Parameter Traits and Modifiers

By default, parameters are bound to their argument and marked as read-only. One can change that with traits on the parameter.

The is copy trait causes the argument to be copied, and allows it to be modified inside the routine

    sub count-up ($x is copy) {
        $x = Inf if $x ~~ Whatever;
        .say for 1..$x;
    }

The is rw trait makes the parameter only bind to a variable (or other writable container). Assigning to the parameter changes the value of the variable at the caller side.

    sub swap($x is rw, $y is rw) {
        ($x, $y) = ($y, $x);
    }

On slurpy parameters, is rw is reserved for future use by language designers.

The is raw trait is automatically applied to parameters declared with a backslash as a "sigil", and may also be used to make normally sigiled parameters behave like these do. In the special case of slurpies, which normally produce an Array full of Scalars as described above, is raw will instead cause the parameter to produce a List. Each element of that list will be bound directly as raw parameter.

# 159.2 Methods

## 159.2.1 method params

    method params(Signature:D:) returns Positional

Returns the list of Parameter objects that make up the signature.

## 159.2.2 method arity

    method arity(Signature:D:) returns Int:D

Returns the minimal number of positional arguments required to satisfy the signature.

## 159.2.3 method count

    method count(Signature:D:) returns Real:D

Returns the maximal number of positional arguments which can be bound to the signature. Returns Inf if there is a slurpy positional parameter.

## 159.2.4 method returns

Whatever the Signature's return constraint is:

    :($a, $b --> Int).returns # Int

## 159.2.5 method ACCEPTS

    multi method ACCEPTS(Signature:D:  <a href="#_type_Capture.pod6">Capture</a>  $topic)
     multi method ACCEPTS(Signature:D: @topic)
     multi method ACCEPTS(Signature:D: %topic)
     multi method ACCEPTS(Signature:D: Signature $topic)

The first three see if the argument could be bound to the capture, i.e., if a function with that Signature would be able to be called with the $topic:

    (1, 2, :foo) ~~ :($a, $b, :foo($bar))   # True
    &lt;a b c d> ~~ :(Int $a)                  # False

The last returns True if anything accepted by $topic would also be accepted by the Signature.

    :($a, $b) ~~ :($foo, $bar, $baz?)   # True
    :(Int $n) ~~ :(Str)                 # False

# 160 class Slip

A kind of List that automatically flattens into an outer container

    class Slip is List { ... }

A Slip is a List that automatically flatten into an outer List (or other list-like container or iterable).

For example it allows you to write a map that produces more than one value into the result without nesting:

    say &lt;a b c>.map({ ($_, $_.uc).Slip }).join('|');        # a|A|b|B|c|C

In contrast, when returning an ordinary List, the resulting list is nested:

    say &lt;a b c>.map({ $_, $_.uc }).join('|');               # a A|b B|c C

To create a Slip, either coerce another list-like type to it by calling the Slip method, or use the slip subroutine:

    # This says "1" and then says "2", rather than saying "(1 2)"
    .say for gather {
        take slip(1, 2);
    }

A Slip may also be created by using the prefix:<|> operator. This differs from the slip subroutine in both precedence and treatment of single arguments. In fact, prefix:<|> only takes a single argument, so it that way, it behaves closer to the .Slip method than the slip subroutine.

    my $l = (1, 2, 3);
    say (1, slip 2, 3).perl;  # says (1, 2, 3)      , slips 2, 3 into (1, …)
    say (0, slip $l).perl;    # says (0, $(1, 2, 3)), $l does not break apart
    say (0, $l.Slip).perl;    # says (0, 1, 2, 3)   , slips from $l into (0, …)
    say (|$l).perl;           # says slip(1, 2, 3)  , breaks apart $l
    say (0, (|$l, 4), 5);     # says (0 (1 2 3 4) 5), slips from $l into (…, 4)
    say (0, ($l.Slip, 4), 5); # says (0 (1 2 3 4) 5), slips from $l into (…, 4)
    say (0, (slip $l, 4), 5); # says (0 (1 2 3) 4 5), slips ($l, 4) into (0, …, 5)
    say (0, ($l, 4).Slip, 5); # says (0 (1 2 3) 4 5), slips ($l, 4) into (0, …, 5)

Loops that do not want to produce a value for an iteration use Slips, rather than empty Lists to do so, as do if statements that do not run their blocks.

# 160.1 Methods

## 160.1.1 sub slip

    sub slip(*@) returns Slip:D

Creates a Slip from its arguments.

# 160.2 Constants

## 160.2.1 Empty

Empty is a Slip of the empty List.

# 161 class Stash

Table for "our"-scoped symbols

    class Stash is Hash { }

A Stash is a hash that is used for symbol tables at the package scoping level in Perl 6.

To get a Stash, you can call the .WHO pseudo-method on a package (because it answers the question who lives here?), or if you write the package name as a literal, append two colons:

    class Boring {
        class Nested { };
        our sub package_sub { }
        my sub lexical { };
        method a_method() { }
    }

    say Boring::.^name;             # Stash
    say Boring.WHO === Boring::;    # True

Since it inherits from Hash, you can use all the usual hash functionality:

    say Boring::.keys.sort;         # &amp;package_sub Nested
    say Boring::&lt;Nested>;           # (Nested)

As the example above shows only "our"-scoped things appear in the Stash (nested classes are "our" by default, but can be excluded with "my".) Lexicals and methods are not included in a Stash, since they do not live in the package table. Lexicals live in a separate lexical pad, which is only visible from inside the scope. Methods (in the case that the package is also a class) have a separate method table, and are accessible through introspection on the class itself, via .can and .^methods.

# 162 class Str

String of characters

    class Str is Cool does Stringy { }

Built-in class for strings. Objects of type Str are immutable.

# 162.1 Methods

## 162.1.1 routine chop

    multi sub    chop(Str:D)  returns Str:D
    multi method chop(Str:D: $chars = 1) returns Str:D

Returns the string with $chars characters removed from the end.

## 162.1.2 routine chomp

Defined as:

    multi sub    chomp(Str:D ) returns Str:D
    multi method chomp(Str:D:) returns Str:D

Usage:

    chomp($string);
    $string.chomp;

Returns the string with a logical newline (any codepoint that has the NEWLINE property) removed from the end.

Examples:

    say chomp("abc\n");       # abc
    say "def\r\n".chomp;      # def  NOTE: \r\n is a single grapheme!
    say "foo\r".chomp;        # foo

## 162.1.3 routine lc

Defined as:

    multi sub    lc(Str:D ) returns Str:D
    multi method lc(Str:D:) returns Str:D

Usage:

    lc($string);
    $string.lc;

Returns a lower-case version of the string.

Examples:

    lc("A"); # returns "a"
    "A".lc;  # returns "a"

## 162.1.4 routine uc

    multi sub    uc(Str:D ) returns Str:D
    multi method uc(Str:D:) returns Str:D

Returns an uppercase version of the string.

## 162.1.5 routine fc

    multi sub    fc(Str:D ) returns Str:D
    multi method fc(Str:D:) returns Str:D

Does a Unicode "fold case" operation suitable for doing caseless string comparisons. (In general, the returned string is unlikely to be useful for any purpose other than comparison.)

## 162.1.6 routine tc

    multi sub    tc(Str:D ) returns Str:D
    multi method tc(Str:D:) returns Str:D

Does a Unicode "titlecase" operation, that is changes the first character in the string to title case, or to upper case if the character has no title case mapping

## 162.1.7 routine tclc

    multi sub    tclc(Str:D ) returns Str:D
    multi method tclc(Str:D:) returns Str:D

Turns the first character to title case, and all other characters to lower case

## 162.1.8 routine wordcase

    multi sub    wordcase(Cool $x)  returns Str
     multi sub    wordcase(Str:D $x) returns Str
     multi method wordcase(Str:D: :&amp;filter = &amp; <a href="#_routine_tclc.pod6">tclc</a> , Mu :$where = True) returns Str

Returns a string in which &filter has been applied to all the words that match $where. By default, this means that the first letter of every word is capitalized, and all the other letters lowercased.

## 162.1.9 method lcfirst

Perl 6 does not have a lcfirst function.

## 162.1.10 method ucfirst

Perl 6 does not have a ucfirst function. See tc.

## 162.1.11 method unival

    multi method unival(Str:D) returns Numeric

Returns the numeric value that the first codepoint in the invocant represents, or NaN if it's not numeric.

    say '4'.unival;     # 4
    say '¾'.unival;     # 0.75
    say 'a'.unival;     # NaN

## 162.1.12 method univals

    multi method univals(Str:D) returns List

Returns a list of numeric values represented by each codepoint in the invocant string, and NaN for non-numeric characters.

    say '4a¾".univals;  # 4 NaN 0.75

## 162.1.13 method length

Perl 6 does not have a length function. See chars, elems, or codes.

## 162.1.14 routine chars

    multi sub    chars(Cool $x)  returns Int:D
    multi sub    chars(Str:D $x) returns Int:D
    multi sub    chars(str $x)   returns int
    multi method chars(Str:D:)   returns Int:D

Returns the number of characters in the string in graphemes. On the JVM, this currently erroneously returns the number of codepoints instead.

## 162.1.15 method encode

    multi method encode(Str:D: $encoding = $?ENC, $nf = $?NF) returns Blob

Returns a Blob which represents the original string in the given encoding and normal form. The actual return type is as specific as possible, so $str.encode('UTF-8') returns a utf8 object, $str.encode('ISO-8859-1') a buf8.

## 162.1.16 routine index

    multi sub    index(Cool $s, Str:D $needle, Cool $startpos = 0) returns Int
    multi method index(Cool $needle, Cool $startpos = 0) returns Int

Searches for $needle in the string starting from $startpos. It returns the offset into the string where $needle was found, and an undefined value if it was not found.

Examples:

    say index "Camelia is a butterfly", "a";     # 1
    say index "Camelia is a butterfly", "a", 2;  # 6
    say index "Camelia is a butterfly", "er";    # 17
    say index "Camelia is a butterfly", "Camel"; # 0
    say index "Camelia is a butterfly", "Onion"; # Nil

    say index("Camelia is a butterfly", "Onion").defined ?? 'OK' !! 'NOT'; # NOT

## 162.1.17 routine rindex

    multi sub    rindex(Str:D $haystack, Str:D $needle, Int $startpos = $haystack.chars) returns StrPos
    multi method rindex(Str:D $haystack: Str:D $needle, Int $startpos = $haystack.chars) returns StrPos

Returns the last position of $needle in $haystack not after $startpos. Returns an undefined value if $needle wasn't found.

Examples:

    say rindex "Camelia is a butterfly", "a";     # 11
    say rindex "Camelia is a butterfly", "a", 10; # 6

## 162.1.18 routine split

    multi sub    split(  Str:D $delimiter, Str:D $input, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional
    multi sub    split(Regex:D $delimiter, Str:D $input, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional
    multi sub    split(List:D $delimiters, Str:D $input, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional
    multi method split(Str:D:   Str:D $delimiter, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional
    multi method split(Str:D: Regex:D $delimiter, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional
    multi method split(Str:D: List:D $delimiters, $limit = Inf,
      :$skip-empty, :$v, :$k, :$kv, :$p) returns Positional

Usage:

    split( DELIMITER,  STRING [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )
    split( /PATTERN/,  STRING [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )
    split( DELIMITERS, STRING [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )
    STRING.split( DELIMITER  [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )
    STRING.split( /PATTERN/  [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )
    STRING.split( DELIMITERS [,LIMIT] [,:v] [,:k] [,:kv] [,:p] [,:skip-empty] )

Splits a string up into pieces based on delimiters found in the string.

If DELIMITER is a string, it is searched for literally and not treated as a regex. If DELIMITER is the empty string, it effectively returns all characters of the string separately (plus an empty string at the begin and at the end). If PATTERN is a regular expression, then that will be used to split up the string. If DELIMITERS is a list, then all of its elements will be considered a delimiter (either a string or a regular expression) to split the string on.

The optional LIMIT indicates in how many segments the string should be split, if possible. It defaults to Inf (or *, whichever way you look at it), which means "as many as possible".

A number of optional named parameters can be specified, which alter the result being returned. The :v, :k, :kv and :p named parameters all perform a special action with regards to the delimiter found.

- :skip-empty

If specified, do not return empty strings before or after a delimiter.

- :v

Also return the delimiter. If the delimiter was a regular expression, then this will be the associated Match object. Since this stringifies as the delimiter string found, you can always assume it is the delimiter string if you're not interested in further information about that particular match.

- :k

Also return the index of the delimiter. Only makes sense if a list of delimiters was specified: in all other cases, this will be 0.

- :kv

Also return both the index of the delimiter, as well as the delimiter.

- :p

Also return the index of the delimiter and the delimiter as a Pair.

Examples:

        say split(";", "a;b;c").perl;            # ("a", "b", "c")
         say split(";", "a;b;c", :v).perl;        # ("a", ";", "b", ";", "c")
         say split(";", "a;b;c", 2).perl;         # ("a", "b;c").Seq
         say split(";", "a;b;c", 2, :v).perl;     # ("a", ";", "b;c")
         say split(";", "a;b;c,d").perl;          # ("a", "b", "c,d")
         say split(/\;/, "a;b;c,d").perl;         # ("a", "b", "c,d")
         say split(&lt;; ,>, "a;b;c,d").perl;        # ("a", "b", "c", "d")
         say split(/&lt;[;,]>/, "a;b;c,d").perl;     # ("a", "b", "c", "d")
         say split(&lt;; ,>, "a;b;c,d", :k).perl;    # ("a", 0, "b", 0, "c", 1, "d")
         say split(&lt;; ,>, "a;b;c,d", :kv).perl;   # ("a", 0, ";", "b", 0, ";", "c", 1, ",", "d")

         say "".split("x").perl;                  # ("",)
         say "".split("x", :skip-empty).perl;     # ("",)

         say "abcde".split("").perl;              # ("", "a", "b", "c", "d", "e", "")
         say "abcde".split("",:skip-empty).perl;  # ("a", "b", "c", "d", "e")

## 162.1.19 routine comb

    multi sub    comb(Str:D   $matcher, Str:D $input, $limit = Inf)
    multi sub    comb(Regex:D $matcher, Str:D $input, $limit = Inf, Bool :$match)
    multi sub    comb(Int:D $size, Str:D $input, $limit = Inf)

    multi method comb(Str:D $input:)
    multi method comb(Str:D $input: Str:D   $matcher, $limit = Inf)
    multi method comb(Str:D $input: Regex:D $matcher, $limit = Inf, Bool :$match)
    multi method comb(Str:D $input: Int:D $size, $limit = Inf)

Searches for $matcher in $input and returns a list of all matches (as Str by default, or as Match if $match is True), limited to at most $limit matches.

If no matcher is supplied, a list of characters in the string (e.g. $matcher = rx/./) is returned.

Examples:

    say comb(/\w/, "a;b;c").perl;        # ("a", "b", "c").Seq
    say comb(/\N/, "a;b;c").perl;        # ("a", ";", "b", ";", "c").Seq
    say comb(/\w/, "a;b;c", 2).perl;     # ("a", "b").Seq
    say comb(/\w\;\w/, "a;b;c", 2).perl; # ("a;b",).Seq

If the matcher is an integer value, it is considered to be a matcher that is similar to / . ** matcher /, but which is about 30x faster.

## 162.1.20 routine lines

    multi sub    lines(Str:D $input, $limit = Inf) returns Positional
    multi method lines(Str:D $input: $limit = Inf) returns Positional

Returns a list of lines (without trailing newline characters), i.e. the same as a call to $input.comb( / ^^ \N* /, $limit ) would.

Examples:

    say lines("a\nb").perl;    # ("a", "b").Seq
    say lines("a\nb").elems;   # 2
    say "a\nb".lines.elems;    # 2
    say "a\n".lines.elems;     # 1

## 162.1.21 routine words

    multi sub    words(Str:D $input, $limit = Inf) returns Positional
    multi method words(Str:D $input: $limit = Inf) returns Positional

Returns a list of non-whitespace bits, i.e. the same as a call to $input.comb( / \S+ /, $limit ) would.

Examples:

    say "a\nb\n".words.perl;       # ("a", "b").Seq
    say "hello world".words.perl;  # ("hello", "world").Seq
    say "foo:bar".words.perl;      # ("foo:bar",).Seq
    say "foo:bar\tbaz".words.perl; # ("foo:bar", "baz").Seq

## 162.1.22 routine flip

    multi sub    flip(Str:D ) returns Str:D
    multi method flip(Str:D:) returns Str:D

Returns the string reversed character by character.

Examples:

    "Perl".flip;  # lreP
    "ABBA".flip;  # ABBA

## 162.1.23 sub printf

    multi sub printf(Str:D $format, *@args)

This function is mostly identical to the C library printf function.

The $format is scanned for % characters. Any % introduces a format token. Format tokens have the following grammar:

    grammar Str::PrintfFormat {
     regex format_token { '%': &lt;index>? &lt;precision>? &lt;modifier>? &lt;directive> }
     token index { \d+ '$' }
     token precision { &lt;flags>? &lt;vector>? &lt;precision_count> }
     token flags { &lt;[ \x20 + 0 \# \- ]>+ }
     token precision_count { [ &lt;[1..9]>\d* | '*' ]? [ '.' [ \d* | '*' ] ]? }
     token vector { '*'? v }
     token modifier { &lt; ll l h V q L > }
     token directive { &lt; % c s d u o x e f g X E G b p n i D U O F > }
    }

Directives guide the use (if any) of the arguments. When a directive (other than %) is used, it indicates how the next argument passed is to be formatted into the string to be printed.

The directives are:

% | a literal percent sign
c | a character with the given codepoint
s | a string
d | a signed integer, in decimal
u | an unsigned integer, in decimal
o | an unsigned integer, in octal
x | an unsigned integer, in hexadecimal
e | a floating-point number, in scientific notation
f | a floating-point number, in fixed decimal notation
g | a floating-point number, in %e or %f notation
X | like x, but using uppercase letters
E | like e, but using an uppercase "E"
G | like g, but with an uppercase "E" (if applicable)
b | an unsigned integer, in binary

Compatibility:

i | a synonym for %d
D | a synonym for %ld
U | a synonym for %lu
O | a synonym for %lo
F | a synonym for %f

Perl 5 (non-)compatibility:

n | produces a runtime exception
p | produces a runtime exception

Modifiers change the meaning of format directives, but are largely no-ops (the semantics are still being determined).

h interpret integer as native "short" (typically int16)
l interpret integer as native "long" (typically int32 or int64)
ll interpret integer as native "long long" (typically int64)
L interpret integer as native "long long" (typically uint64)
q interpret integer as native "quads" (typically int64 or larger)

Examples:

    printf('%c', 97);                  # a
    printf("%.2f", 1.969);             # 1.97
    printf("%+.3f", 3.141592);         # +3.142
    printf('%2$d %1$d', 12, 34);       # 34 12
    printf("%x", 255);                 # ff

Special case: printf("<b>%s</b>\n", "Perl 6") will not work use either of the following:

    printf Q:b "&lt;b>%s&lt;/b>\n",  "Perl 6";
    printf     "&lt;b>\%s&lt;/b>\n", "Perl 6";
    printf     "&lt;b>%s\&lt;/b>\n", "Perl 6";

## 162.1.24 sub sprintf

    multi sub sprintf( Str:D $format, *@args) returns Str:D

This function is mostly identical to the C library sprintf function.

The $format is scanned for % characters. Any % introduces a format token. Format tokens have the following grammar:

    grammar Str::SprintfFormat {
     regex format_token { '%': &lt;index>? &lt;precision>? &lt;modifier>? &lt;directive> }
     token index { \d+ '$' }
     token precision { &lt;flags>? &lt;vector>? &lt;precision_count> }
     token flags { &lt;[ \x20 + 0 \# \- ]>+ }
     token precision_count { [ &lt;[1..9]>\d* | '*' ]? [ '.' [ \d* | '*' ] ]? }
     token vector { '*'? v }
     token modifier { &lt; ll l h V q L > }
     token directive { &lt; % c s d u o x e f g X E G b p n i D U O F > }
    }

Directives guide the use (if any) of the arguments. When a directive (other than %) is used, it indicates how the next argument passed is to be formatted into the string.

The directives are:

% | a literal percent sign
c | a character with the given codepoint
s | a string
d | a signed integer, in decimal
u | an unsigned integer, in decimal
o | an unsigned integer, in octal
x | an unsigned integer, in hexadecimal
e | a floating-point number, in scientific notation
f | a floating-point number, in fixed decimal notation
g | a floating-point number, in %e or %f notation
X | like x, but using uppercase letters
E | like e, but using an uppercase "E"
G | like g, but with an uppercase "E" (if applicable)
b | an unsigned integer, in binary

Compatibility:

i | a synonym for %d
D | a synonym for %ld
U | a synonym for %lu
O | a synonym for %lo
F | a synonym for %f

Perl 5 (non-)compatibility:

n | produces a runtime exception
p | produces a runtime exception

Modifiers change the meaning of format directives, but are largely no-ops (the semantics are still being determined).

h interpret integer as native "short" (typically int16)
l interpret integer as native "long" (typically int32 or int64)
ll interpret integer as native "long long" (typically int64)
L interpret integer as native "long long" (typically uint64)
q interpret integer as native "quads" (typically int64 or larger)

Examples:

    sprintf "%ld a big number, %lld a bigger number\n", 4294967295, 4294967296;

Special case: sprintf("<b>%s</b>\n", "Perl 6") will not work use either of the following:

    sprintf Q:b "&lt;b>%s&lt;/b>\n",  "Perl 6";
    sprintf     "&lt;b>\%s&lt;/b>\n", "Perl 6";
    sprintf     "&lt;b>%s\&lt;/b>\n", "Perl 6";

## 162.1.25 method starts-with

    multi method starts-with(Str:D: Str(Cool) $needle) returns True:D

Returns True if the invocant is identical to or starts with $needle.

    say "Hello, World".starts-with("Hello");     # True
    say "https://perl6.org/".starts-with('ftp'); # False

## 162.1.26 method ends-with

    multi method ends-with(Str:D: Str(Cool) $needle) returns True:D

Returns True if the invocant is identical to or ends with $needle.

    say "Hello, World".ends-with('Hello');      # False
    say "Hello, World".ends-with('ld');         # True

## 162.1.27 method subst

    multi method subst(Str:D: $matcher, $replacement, *%opts)

Returns the invocant string where $matcher is replaced by $replacement (or the original string, if no match was found).

There is an in-place syntactic variant of subst spelled s/matcher/replacement/.

$matcher can be a Regex, or a literal Str. Non-Str matcher arguments of type Cool are coerced to Str for literal matching.

    my $some-string = "Some foo";
    my $another-string = $some-string.subst(/foo/, "string"); # gives 'Some string'
    $some-string.=subst(/foo/, "string"); # in-place substitution. $some-string is now 'Some string'

The replacement can be a closure:

    my $i = 41;
    my $str = "The answer is secret.";
    my $real-answer = $str.subst(/secret/, {++$i}); # The answer to everything

Here are other examples of usage:

    my $str = "Hey foo foo foo";
    $str.subst(/foo/, "bar", :g); # global substitution - returns Hey bar bar bar

    $str.subst(/foo/, "no subst", :x(0)); # targeted substitution. Number of times to substitute. Returns back unmodified.
    $str.subst(/foo/, "bar", :x(1)); #replace just the first occurrence.

    $str.subst(/foo/, "bar", :nth(3)); # replace nth match alone. Replaces the third foo. Returns Hey foo foo bar

The following adverbs are supported

short | long | meaning
--- | --- | ---
:g | :global | tries to match as often as possible
:nth(Int) |  | only substitute the nth's match
:ss | :samespace | preserves whitespace on substitution
:ii | :samecase | preserves case on substitution
:mm | :samemark | preserves character marks (e.g. 'ü' replaces with 'o' will result in 'ö')
:x(Int) |  | substitute exactly $x matches

Note that only in the s/// form :ii implies :i and :ss implies :s. In the method form, the :s and :i modifiers must be added to the regex, not the subst method call.

## 162.1.28 method subst-mutate

Where subst returns the modified string and leaves the original unchanged, it is possible to mutate the original string by using subst-mutate. If the match is successful, the method returns a Match object representing the successful match, or Any otherwise.

    my $some-string = "Some foo";
    my $match = $some-string.subst-mutate(/foo/, "string");
    say $some-string;  #-> Some string
    say $match;        #-> ｢foo｣
    $some-string.subst-mutate(/&lt;[oe]>/, '', :g); # remove all o'ss and e's, notice the :g named argument from .subst

## 162.1.29 routine substr

    multi sub    substr(Str:D $s, Int:D $from, Int:D $chars = $s.chars - $from) returns Str:D
    multi sub    substr(Str:D $s, Range $from-to) returns Str:D
    multi method substr(Str:D $s: Int:D $from, Int:D $chars = $s.chars - $from) returns Str:D
    multi method substr(Str:D $s: Range $from-to) returns Str:D

Returns a part of the string, starting from the character with index $from (where the first character has index 0) and with length $chars. If a range is specified, its first and last indices are used to determine the size of the substring.

Examples:

    substr("Long string", 6, 3);     # tri
    substr("Long string", 6);        # tring
    substr("Long string", 6, *-1);   # trin
    substr("Long string", *-3, *-1); # in

## 162.1.30 method substr-eq

    multi method substr-eq(Str:D:  Str(Cool) $test-string, Int(Cool) $from) returns Bool
    multi method substr-eq(Cool:D: Str(Cool) $test-string, Int(Cool) $from) returns Bool

Returns True if the $test-string exactly matches the String object, starting from the given initial index $from. For example, beginning with the string "foobar", the substring "bar" will match from index 3:

    my $string = "foobar";
    say $string.substr-eq("bar", 3);  #-> True

However, the substring "barz" starting from index 3 won't match even though the first three letters of the substring do match:

    my $string = "foobar";
    say $string.substr-eq("barz", 3);  #-> False

Naturally, to match the entire string, one merely matches from index 0:

    my $string = "foobar";
    say $string.substr-eq("foobar", 0);  #-> True

Since this method is inherited from the Cool type, it also works on integers. Thus the integer 42 will match the value 342 starting from index 1:

    my $integer = 342;
    say $integer.substr-eq(42, 1);  #-> True

As expected, one can match the entire value by starting at index 0:

    my $integer = 342;
    say $integer.substr-eq(342, 0);  #-> True

Also using a different value or an incorrect starting index won't match:

    my $integer = 342;
    say $integer.substr-eq(42, 3);  #-> False
    say $integer.substr-eq(7342, 0);  #-> False

## 162.1.31 method substr-rw

    method substr-rw($from, $length?)

A version of substr that returns a Proxy functioning as a writable reference to a part of a string variable. Its first argument, $from specifies the index in the string from which a substitution should occur, and its last argument, $length specifies how many characters are to be replaced.

For example, in its method form, if one wants to take the string "abc" and replace the second character (at index 1) with the letter "z", then one do this:

    my $string = "abc";
    $string.substr-rw(1, 1) = "z";
    $string.say;                    #-> azc

substr-rw also has a function form, so the above example can also be written like so:

    my $string = "abc";
    substr-rw($string, 1, 1) = "z";
    $string.say;                    #-> azc

It is also possible to alias the writable reference returned by substr-rw for repeated operations:

    my $string = "A character in the 'Flintstones' is: barney";
    $string ~~ /(barney)/;
    my $ref := substr-rw($string, $0.from, $0.to);
    $string.say;
    #-> A character in the 'Flintstones' is: barney
    $ref = "fred";
    $string.say;
    #-> A character in the 'Flintstones' is: fred
    $ref = "wilma";
    $string.say;
    #-> A character in the 'Flintstones' is: wilma

Notice that the start position and length of string to replace has been specified via the .from and .to methods on the Match object, $0. It is thus not necessary to count characters in order to replace a substring, hence making the code more flexible.

## 162.1.32 routine samemark

    multi sub samemark(Str:D $string, Str:D $pattern) returns Str:D
    method    samemark(Str:D: Str:D $pattern) returns Str:D

Returns a copy of $string with the mark/accent information for each character changed such that it matches the mark/accent of the corresponding character in $pattern. If $string is longer than $pattern, the remaining characters in $string receive the same mark/accent as the last character in $pattern. If $pattern is empty no changes will be made.

Examples:

    say 'åäö'.samemark('aäo');                        # aäo
    say 'åäö'.samemark('a');                          # aao

    say samemark('Pêrl', 'a');                        # Perl
    say samemark('aöä', '');                          # aöä

## 162.1.33 method succ

    method succ(Str:D) returns Str:D

Returns the string incremented by one.

String increment is "magical". It searches for the last alphanumeric sequence that is not preceded by a dot, and increments it.

    '12.34'.succ      # 13.34
    'img001.png'.succ # img002.png

The actual increment step works by mapping the last alphanumeric character to a character range it belongs to, and choosing the next character in that range, carrying to the previous letter on overflow.

    'aa'.succ   # ab
    'az'.succ   # ba
    '109'.succ  # 110
    'α'.succ    # β
    'a9'.succ   # b0

String increment is Unicode-aware, and generally works for scripts where a character can be uniquely classified as belonging to one range of characters.

## 162.1.34 method pred

    method pred(Str:D:) returns Str:D

Returns the string decremented by one.

String decrementing is "magical" just like string increment (see succ). It fails on underflow

    'b0'.pred           # a9
    'a0'.pred           # Failure
    'img002.png'.pred   # img001.png

## 162.1.35 routine ord

    multi sub    ord(Str:D)  returns Int:D
    multi method ord(Str:D:) returns Int:D

Returns the codepoint number of the base characters of the first grapheme in the string.

Example:

    ord("A") # 65
    "«".ord  # 171

## 162.1.36 method ords

    multi method ords(Str:D:) returns Positional

Returns a list of codepoint numbers, one for the base character of each grapheme in the string.

Example:

    "aå«".ords # (97 229 171)

## 162.1.37 method trans

    proto method trans(|) { $/ := nqp::getlexcaller('$/'); {*} }
    multi method trans(Str:D: Pair:D \what, *%n) returns Str
    multi method trans(Str:D: *@changes, :complement(:$c), :squash(:$s), :delete(:$d)) returns Str

Replaces one or many characters with one or many characters. Ranges are supported, both for keys and values. Regexes work as keys. In case a list of keys and values is used, substrings can be replaced aswell. When called with :complement anything but the matched value or range is replaced with a single value. With :delete the matched characters are removed. Combining :complement and :delete will remove anything but the matched values. The adverb :squash will reduce repeated matched characters to a single character.

Example:

    my $str = 'say $x&lt;b> &amp;&amp; $y&lt;a>';
    $str.=trans( '&lt;' => '«' );
    $str.=trans( '&lt;' => '«', '>' => '»' );

    $str.=trans( [ '&lt;'   , '>'   , '&amp;' ] =>
                 [ '&amp;lt;', '&amp;gt;', '&amp;amp;' ]);

    $str.=trans( ['a'..'y'] => ['A'..'z'] );

    "abcdefghij".trans(/&lt;[aeiou]> \w/ => ''); # «cdgh»

    "a123b123c".trans(['a'..'z'] => 'x', :complement); # «axxxbxxxc»
    "a123b123c".trans('23' => '', :delete); # «a1b1c»
    "aaa1123bb123c".trans('a'..'z' => 'A'..'Z', :squash); # «A1123B123C»
    "aaa1123bb123c".trans('a'..'z' => 'x', :complement, :squash); # «aaaxbbxc»

## 162.1.38 method indent

    proto method indent($)
    multi method indent(Int $steps where { $_ == 0 } )
    multi method indent(Int $steps where { $_ > 0  } )
    multi method indent($steps where { .isa(Whatever) || .isa(Int) &amp;&amp; $_ &lt; 0 )

Indents each line of the string by $steps. If $steps is negative, it outdents instead. If $steps is * , then the string is outdented to the margin:

    "  indented by 2 spaces\n    indented even more".indent(*)
         eq "indented by 2 spaces\n  indented even more"

## 162.1.39 method trim

    method trim(Str:D:) returns Str

Remove leading and trailing whitespace. It can be use both as a method on strings and as a function. When used as a method it will return the trimmed string. In order to do in-place trimming, once needs to write .=trim

    my $line = '   hello world    ';
    say '&lt;' ~ $line.trim ~ '>';        # &lt;hello world>
    say '&lt;' ~ trim($line) ~ '>';       # &lt;hello world>
    $line.trim;
    say '&lt;' ~ $line ~ '>';             # &lt;   hello world    >
    $line.=trim;
    say '&lt;' ~ $line ~ '>';             # &lt;hello world>

See also trim-trailing and trim-leading

## 162.1.40 method trim-trailing

Remove the whitespace characters from the end of a string. See also trim.

## 162.1.41 method trim-leading

Remove the whitespace characters from the beginning of a string. See also trim.

## 162.1.42 method NFC

    method NFC(Str:D:) returns NFC:D

Returns a codepoint string in NFC format (Unicode Normalization Form C / Composed).

## 162.1.43 method NFD

    method NFD(Str:D:) returns NFD:D

Returns a codepoint string in NFC format (Unicode Normalization Form D / Decomposed).

## 162.1.44 method NFKC

    method NFKC(Str:D:) returns NFKC:D

Returns a codepoint string in NFKC format (Unicode Normalization Form KC / Compatibility Composed).

## 162.1.45 method NFKD

    method NFKD(Str:D:) returns NFKD:D

Returns a codepoint string in NFC format (Unicode Normalization Form KD / Compatibility Decomposed).

## 162.1.46 method ACCEPTS

    multi method ACCEPTS(Str:D: $other)

Returns True if the string is the same as $other.

## 162.1.47 sub val

seems like the best place to document this

    multi sub val(Str:D $MAYBEVAL, :$val-or-fail)

Given a Str that may be parseable as a numeric value, it will attempt to construct the appropriate allomorph, returning one of IntStr, NumStr, RatStr or ComplexStr or a plain Str if a numeric value cannot be parsed. If the :val-or-fail adverb is provided it will return an X::Str::Numeric rather than the original string if it cannot parse the string as a number.

    say val("42").WHAT; # (IntStr)
    say val("42e0").WHAT; # (NumStr)
    say val("42.0").WHAT; # (RatStr)
    say val("42+0i").WHAT; # (ComplexStr)

# 163 role Stringy

String or object that can act as a string

    role Stringy { ... }

Common role for string types (such as Str).

# 164 class Sub

Subroutine

    class Sub is Routine { }

A type for subroutines. Subs are created with the sub keyword

    my $s = sub ($a, $b) { $a + $b };
    say $s.WHAT;        # Sub()
    say $s(2, 5);       # 7

# 165 class Submethod

Member function that is not inherited by subclasses

    class Submethod is Routine { ... }

A Submethod is a method that is not inherited to child classes. They are typically used for per-class initialization and tear-down tasks which are called explicitly per class in an inheritance tree, usually for enforcing a particular order. For example object construction with the BUILD submethod happens from the least-derived to most-derived, so that the most-derived (child) classes can depend on the parent already being initialized.

Submethods are of type Submethod, and are declared with the submethod declarator:

    class Area {
        has $.size;
        submethod BUILD(:$x, :$y, :$z) {
            $!size = $x * $y * $z;
        }
    }

# 165.1 Methods

TODO

# 166 class Supplier

Live

    class Supplier { ... }

This is a factory for live Supply objects, which provides the mechanism for emitting new values onto the supplies:

    my $supplier = Supplier.new;
    my $supply_1 = $supplier.Supply;
    $supply_1.tap(-> $v { say "One $v" });
    my $supply_2 = $supplier.Supply;
    $supply_2.tap(-> $v { say "Two $v" });
    $supplier.emit(42);

Will output:

    One 42
    Two 42

on demand supplies are created by the factory methods of the Supply class or by the supply keyword.

# 166.1 Methods

## 166.1.1 method new

    method new()

The Supplier constructor.

## 166.1.2 method Supply

    method Supply(Supplier:D:) returns Supply

This creates a new Supply object to which any values which are emitted on this supplier are passed. This is the factory for all live supplies.

## 166.1.3 method emit

    method emit(Supplier:D: Mu \value)

Sends the given value to all of the taps on all of the supplies created by Supply on this Supplier.

## 166.1.4 method done

    method done(Supplier:D:)

Calls the done callback on all the taps that have one.

    my $supplier = Supplier.new;
    my $supply   = $supplier.Supply;
    $supply.tap(-> $v { say $v }, done => { say "no more answers" });
    $supplier.emit(42);
    $supplier.done;

Will output:

    42
    no more answers

## 166.1.5 method quit

    multi method quit(Supplier:D: Exception $ex)
    multi method quit(Supplier:D: Str() $message)

Calls the quit callback on all the taps that have one, passing the exception to them. If called with a Str the exception will be an X::AdHoc with the supplied message.

This is meant for shutting down a supply with an error.

# 167 class Supply

Asynchronous data stream with multiple subscribers

    class Supply { ... }

A supply is a thread-safe, asynchronous data stream like a Channel, but it can have multiple subscribers (taps) that all get the same values flowing through the supply.

It is a thread-safe implementation of the Observer Pattern, and central to supporting reactive programming in Perl 6.

There are two types of Supplies: live and on demand. When tapping into a live supply, the tap will only see values that are flowing through the supply after the tap has been created. Such supplies are normally infinite in nature, such as mouse movements. Closing such a tap does not stop mouse events from occurring, it just means that the values will go by unseen. All tappers see the same flow of values.

A tap on an on demand supply will initiate the production of values, and tapping the supply again may result in a new set of values. For example, Supply.interval produces a fresh timer with the appropriate interval each time it is tapped. If the tap is closed, the timer simply stops emitting values to that tap.

A live Supply is obtained from the Supplier factory method Supply. New values are emitted by calling emit on the Supplier object.

    my $supplier = Supplier.new;
    my $supply = $supplier.Supply;
    $supply.tap(-> $v { say "$v" });
    $supplier.emit(42); # Will cause the tap to output "42"

The live method returns True on live supplies. Factory methods such as interval, from-list will return on demand supplies.

Further examples can be found in the concurrency page.

# 167.1 Methods that return Taps

## 167.1.1 method tap

    method tap(Supply:D: &amp;emit = -> $ { },
            :&amp;done,
            :&amp;quit={ die $_ },
            :&amp;closing,
        ) returns Tap:D

Creates a new tap (a kind of subscription if you will), in addition to all existing taps. The first positional argument is a piece of code that will be called when a new value becomes available through the emit call.

The &done callback is called when the done method on the supply is called, indicating the end of life of the channel. For a live supply the done method will be called on the parent Supplier.

The &quit callback is called when the quit method on the supply is called, indicating an erroneous termination of the supply. For a live supply the done method will be called on the parent Supplier

Method tap returns an object of type Tap, on which you can call the close method to cancel the subscription.

    my $s = Supply.from-list(0 .. 5);
    my $t = $s.tap(-> $v { say $v }, done => { say "no more ticks" });

Produces:

    0
    1
    2
    3
    4
    5
    no more ticks

## 167.1.2 method act

    method act(Supply:D: &amp;act) returns Tap:D

Creates a tap on the given supply with the given code. Differently from tap, the given code is guaranteed to be only executed by one thread at a time.

# 167.2 Utility methods

## 167.2.1 method Channel

    method Channel(Supply:D:) returns Channel:D

Returns a Channel object that will receive all future values from the supply, and will be closed when the Supply is done, and quit (shut down with error) when the supply is quit.

## 167.2.2 method Promise

    method Promise(Supply:D:) returns Promise:D

Returns a Promise that will be kept when the Supply is done. If the Supply also emits any values, then the Promise will be kept with the final value. Otherwise, it will be kept with Nil. If the Supply ends with a quit instead of a done, then the Promise will be broken with that exception.

    my $supplier = Supplier.new;
    my $s = $supplier.Supply;
    my $p = $s.Promise;
    $p.then(-> $v { say "got $v.result()" });
    $supplier.emit('cha');         # not output yet
    $supplier.done();              # got cha

The Promise method is most useful when dealing with supplies that will tend to produce just one value, when only the final value is of interest, or when only completion (successful or not) is relevant.

## 167.2.3 method live

    method live(Supply:D:) returns Bool:D

Returns True if the supply is "live", that is, values are emitted to taps as soon as they arrive. Always returns True in the default Supply (but for example on the supply returned from Supply.from-list it's False).

    say Supplier.new.Supply.live;    # True

## 167.2.4 method schedule-on

    method schedule-on(Supply:D: $scheduler)

Runs the emit, done and quit callbacks on the specified scheduler.

This is useful for GUI toolkits that require certain actions to be run from the GUI thread.

# 167.3 Methods that wait until the supply is done

## 167.3.1 method wait

    method wait(Supply:D:)

Waits until the supply is done (in which case it returns True) or quit (in which case it will throw the exception that was passed to quit).

    my $s = Supplier.new;
    start {
      sleep 1;
      say "One second: running.";
      sleep 1;
      $s.emit(42);
      $s.done;
    }
    $s.Supply.wait;
    say "Two seconds: done";

## 167.3.2 method list

    method list(Supply:D:) returns List:D

Waits until the supply is done, then returns a list of all values emitted since the list call.

## 167.3.3 method grab

    method grab(Supply:D: &amp;process ) returns Supply:D

Waits until the given supply is done. It will then call the given process closure passing all of the values seen, Then creates a supply to which all values returned from the process closure.

## 167.3.4 method reverse

    method reverse(Supply:D:) returns Supply:D

Waits until the given supply is done, then creates a supply to which all values seen are emitted in reverse order.

## 167.3.5 method sort

    method sort(Supply:D: &amp;by?) returns Supply:D

Waits until the given supply is done, then creates a supply to which all values seen are emitted in sorted order. Optionally accepts a comparator Block.

# 167.4 Methods that return another Supply

## 167.4.1 method from-list

    method from-list(Supply:U: *@values) returns Supply:D

Creates an on-demand supply from the values passed to this method.

    my $s = Supply.from-list(1, 2, 3);
    $s.tap(&amp;say);           # 1\n2\n3\n

## 167.4.2 method share

    method share(Supply:D:) returns Supply:D

Creates a live supply from an on-demand supply, thus making it possible to share the values of the on-demand supply on multiple taps, instead of each tap seeing its own copy of all values from the on-demand supply.

    # this says in turn: "first 1" "first 2" "second 2" "first 3" "second 3"
    my $s = Supply.interval(1).share;
    $s.tap: { "first $_".say };
    sleep 1.1;
    $s.tap: { "second $_".say };
    sleep 2

## 167.4.3 method flat

    method flat(Supply:D:) returns Supply:D

Creates a supply on which all of the values seen in the given supply are flattened before being emitted again.

## 167.4.4 method do

    method do(Supply:D: &amp;do) returns Supply:D

Creates a supply to which all values seen in the given supply, are emitted again. The given code, executed for its side-effects only, is guaranteed to be only executed by one thread at a time.

## 167.4.5 method interval

    method interval(Supply:U: $interval, $delay = 0) returns Supply:D

Creates a supply that emits a value every $interval seconds, starting $delay seconds from the call. The value is an integer, starting from 0 at the interval tock, and is incremented by one for each value emitted.

## 167.4.6 method grep

    method grep(Supply:D: Mu $test) returns Supply:D

Creates a new supply that only emits those values from the original supply that smart-match against $test.

    my $supplier = Supplier.new;
    my $all      = $supplier.Supply;
    my $ints     = $all.grep(Int);
    $ints.tap(&amp;say);
    $supplier.emit($_) for 1, 'a string', 3.14159;   # prints only 1

## 167.4.7 method map

    method map(Supply:D: &amp;mapper) returns Supply:D

Returns a new supply that maps each value of the given supply through &mapper and emits it to the new supply.

    my $supplier = Supplier.new;
    my $all      = $supplier.Supply;
    my $double   = $all.map(-> $value { $value * 2 });
    $double.tap(&amp;say);
    $supplier.emit(4);           # 8

## 167.4.8 method batch

    method batch(Supply:D: :$elems, :$seconds) returns Supply:D

Creates a new supply that batches the values of the given supply by either the number of elements in the batch (using :elems) or the maximum number of seconds (using the :seconds) or both. Any remaining values are emitted in a final batch when the supply is done.

## 167.4.9 method elems

    method elems(Supply:D: $seconds?) returns Supply:D

Creates a new supply in which changes to the number of values seen are emitted. It optionally also takes an interval (in seconds) if you only want to be updated every so many seconds.

## 167.4.10 method head

    method head(Supply:D: Int(Cool) $number = 1) returns Supply:D

Creates a "head" supply with the same semantics as List.head.

## 167.4.11 method tail

    method tail(Supply:D: Int(Cool) $number = 1) returns Supply:D

Creates a "tail" supply with the same semantics as List.tail.

## 167.4.12 method rotor

    method rotor(Supply:D: @cycle) returns Supply:D

Creates a "rotoring" supply with the same semantics as List.rotor.

## 167.4.13 method delayed

    method delayed(Supply:D: $seconds) returns Supply:D

Creates a new supply in which all values flowing through the given supply are emitted, but with the given delay in seconds.

## 167.4.14 method throttle

    method throttle(Supply:D:
      $limit,                 # values / time or simultaneous processing
      $seconds or $callable,  # time-unit / code to process simultaneously
      $delay = 0,             # initial delay before starting, in seconds
      :$control,              # supply to emit control messages on (optional)
      :$status,               # supply to tap status messages from (optional)
      :$bleed,                # supply to bleed messages to (optional)
      :$vent-at,              # bleed when so many buffered (optional)
      :$scheduler,            # scheduler to use, default $*SCHEDULER
      ) returns Supply:D

Produces a Supply from a given Supply, but makes sure the number of messages passed through, is limited.

It has two modes of operation: per time-unit or by maximum number of execution of a block of code: this is determined by the second positional parameter.

The first positional parameter specifies the limit that should be applied.

If the second positional parameter is a Callable, then the limit indicates the maximum number of parallel processes executing the Callable, which is given the value that was received. The emitted values in this case will be the Promises that were obtained from starting the Callable.

If the second positional parameter is a numeric value, it is interpreted as the time-unit (in seconds). If you specify .1 as the value, then it makes sure you don't exceed the limit for every tenth of a second.

If the limit is exceeded, then incoming messages are buffered until there is room to pass on / execute the Callable again.

The third positional parameter is optional: it indicates the number of seconds the throttle will wait before passing on any values.

The :control named parameter optionally specifies a Supply that you can use to control the throttle while it is in operation. Messages that can be sent, are strings in the form of "key:value". Please see below for the types of messages that you can send to control the throttle.

The :status named parameter optionally specifies a Supply that will receive any status messages. If specified, it will at least send one status message after the original Supply is exhausted. See status message below.

The :bleed named parameter optionally specifies a Supply that will receive any values that were either explicitly bled (with the bleed control message), or automatically bled (if there's a vent-at active).

The :vent-at named parameter indicates the number of values that may be buffered before any additional value will be routed to the :bleed Supply. Defaults to 0 if not specified (causing no automatic bleeding to happen). Only makes sense if a :bleed Supply has also been specified.

The :scheduler named parameter indicates the scheduler to be used. Defaults to $*SCHEDULER.

### 167.4.14.1 control messages

These messages can be sent to the :control Supply. A control message consists of a string of the form "key: value", e.g. "limit: 4".

- limit

Change the number of messages (as initially given in the first positional) to the value given.

- bleed

Route the given number of buffered messages to the :bleed Supply.

- vent-at

Change the maximum number of buffered values before automatic bleeding takes place. If the value is lower than before, will cause immediate rerouting of buffered values to match the new maximum.

- status

Send a status message to the :status Supply with the given id.

### 167.4.14.2 status message

The status return message is a hash with the following keys:

- allowed

The current number of messages / callables that is still allowed to be passed / executed.

- bled

The number of messages routed to the :bleed Supply.

- buffered

The number of messages currently buffered because of overflow.

- emitted

The number of messages emitted (passed through).

- id

The id of this status message (a monotonically increasing number). Handy if you want to log status messages.

- limit

The current limit that is being applied.

- vent-at

The maximum number of messages that may be buffered before they're automatically re-routed to the :bleed Supply.

### 167.4.14.3 Examples

Have a simple piece of code announce when it starts running asynchronously, wait a random amount of time, then announce when it is done. Do this 6 times, but don't let more than 3 of them run simultaneously.

    my $s = Supply.from-list(^6);  # set up supply
    my $t = $s.throttle: 3,        # only allow 3 at a time
    {                              # code block to run
        say "running $_";          # announce we've started
        sleep rand;                # wait some random time
        say "done $_"              # announce we're done
    }                              # don't need ; because } at end of line
    $t.wait;                       # wait for the supply to be done
    =============
    running 0
    running 1
    running 2
    done 2
    running 3
    done 1
    running 4
    done 4
    running 5
    done 0
    done 3
    done 5

## 167.4.15 method stable

    method stable(Supply:D: $seconds, :$scheduler) returns Supply:D

Creates a new supply that only passes on a value flowing through the given supply if it wasn't superseded by another value in the given time (in seconds). Optionally uses another scheduler than the default scheduler, using the :scheduler parameter.

## 167.4.16 method reduce

    method reduce(Supply:D: &amp;with ) returns Supply:D

Creates a "reducing" supply with the same semantics as List.reduce.

## 167.4.17 method lines

    method lines(Supply:D: :$chomp = True ) returns Supply:D

Creates a supply that will emit the characters coming in line by line from a supply that's usually created by some asynchronous I/O operation. The optional :chomp parameter indicates whether to remove line separators: the default is True.

## 167.4.18 method words

    method words(Supply:D:) returns Supply:D

Creates a supply that will emit the characters coming in word for word from a supply that's usually created by some asynchronous I/O operation.

## 167.4.19 method unique

    method unique(Supply:D: :$as({$_}), :$with(&amp;[===]), :$expires) returns Supply:D

Creates a supply that only provides unique values, as defined by the optional :as and :with parameters (same as with List.unique). The optional :expires parameter how long to wait (in seconds) before "resetting" and not considering a value to have been seen, even if it's the same as an old value.

## 167.4.20 method squish

    method squish(Supply:D: :$as({$_}), :$with(&amp;[===]), :$expires) returns Supply:D

Creates a supply that only provides unique values, as defined by the optional :as and :with parameters (same as with List.squish). The optional :expires parameter how long to wait (in seconds) before "resetting" and not considering a value to have been seen, even if it's the same as an old value.

## 167.4.21 method max

    method max(Supply:D: &amp;by = &amp;infix:&lt;cmp>) returns Supply:D

Creates a supply that only emits values from the given supply if they are larger than any value seen before. In other words, from a continuously ascending supply it will emit all the values. From a continuously descending supply it will only emit the first value. The optional parameter specifies the comparator, just as with Any.max.

## 167.4.22 method min

    method min(Supply:D: &amp;by = &amp;infix:&lt;cmp>) returns Supply:D

Creates a supply that only emits values from the given supply if they are smaller than any value seen before. In other words, from a continuously descending supply it will emit all the values. From a continuously ascending supply it will only emit the first value. The optional parameter specifies the comparator, just as with Any.max.

## 167.4.23 method minmax

    method minmax(Supply:D: &amp;by = &amp;infix:&lt;cmp>) returns Supply:D

Creates a supply that emits a Range every time a new minimum or maximum values is seen from the given supply. The optional parameter specifies the comparator, just as with Any.max.

## 167.4.24 method start

    method start(Supply:D: &amp;startee) returns Supply:D

Creates a supply of supplies. For each value in the original supply, the code object is scheduled on another thread, and returns a supply either of a single value (if the code succeeds), or one that quits without a value (if the code fails).

This is useful for asynchronously starting work that you don't block on.

Use migrate to join the values into a single supply again.

## 167.4.25 method migrate

    method migrate(Supply:D:) returns Supply:D

Creates a supply that acts like the last supply emitted to the given supply of supplies (usually created with start.

# 167.5 Methods that combine supplies

## 167.5.1 method merge

    method merge(Supply @*supplies) returns Supply:D

Creates a supply to which any value seen from the given supplies, is emitted. The resulting supply is done Only when all given supplies are done. Can also be called as a class method.

## 167.5.2 method zip

    method zip(Supply @*supplies, :&amp;with = &amp;[,]) returns Supply:D

Creates a supply that emits combined values as soon as there is a new value seen on all of the supplies. By default, Lists are created, but this can be changed by specifying your own combiner with the :with parameter. The resulting supply is done as soon as any of the given supplies are done. Can also be called as a class method.

## 167.5.3 method zip-latest

    method zip-latest(Supply @*supplies, :&amp;with = &amp;[,], :$initial) returns Supply:D

Creates a supply that emits combined values as soon as there is a new value seen on any of the supplies. By default, Lists are created, but this can be changed by specifying your own combiner with the :with parameter. The optional :initial parameter can be used to indicate the initial state of the combined values. By default, all supplies have to have at least one value emitted on them before the first combined values is emitted on the resulting supply. The resulting supply is done as soon as any of the given supplies are done. Can also be called as a class method.

# 167.6 I/O features exposed as supplies

## 167.6.1 sub signal

    sub signal(@*signals, :$scheduler);

Creates a supply for the Signal enums (such as SIGINT) specified, and an optional :scheduler parameter. Any signals received, will be emitted on the supply. For example:

    signal(SIGINT).tap( { say "Thank you for your attention"; exit 0 } );

would catch Control-C, thank you, and then exit. The list of supported signals can be found by checking Signal::.keys (as you would any enum).

## 167.6.2 method IO::Notification.watch-path

    method IO::Notification.watch-path($path) returns Supply:D

Creates a supply to which the OS will emit values to indicate changes on the file system for the given path. Also has a shortcut with the watch method on an IO object, like this:

    IO::Notification.watch-path(".").act( { say "$^file changed" } );
    ".".IO.watch.act(                     { say "$^file changed" } );   # same

# 168 class Tap

Subscription to a Supply

    class Tap { ... }

A Tap is a subscription to a Supply.

    my $s = Supplier.new;
    my $tap = $s.Supply.tap(
        -> $v { say "the value is $v" },
        done    => { say "Supply is done" },
        closing => { say "Tap closed" },
        quit    => -> $ex { say "Supply finished with error $ex" },
    );

    # later
    $tap.close;

# 168.1 Methods

## 168.1.1 method emit

    method emit(Tap:D:) returns Callable:D

Returns the callback that is called for emitted events.

## 168.1.2 method done

    method done(Tap:D:)

Returns the callback that is called on successfully shutting down a channel, if any.

## 168.1.3 method quit

    method quit(Tap:D:)

Returns the callback that is called on shutting down a channel with error, if any.

## 168.1.4 method closing

    method closing(Tap:D:)

Returns the callback that is called on closing the tap.

## 168.1.5 method supply

    method supply(Tap:D:)

Returns the supply to which the tap belongs.

## 168.1.6 method close

    method close(Tap:D:)

Closes the tap.

# 169 class Thread

Concurrent execution of code (low-level)

    class Thread { ... }

A thread is a sequence of instructions that can (potentially) run in parallel to others. Class Thread provides a bit of abstraction over threads provided by the underlying virtual machines (which in turn might or might not be operating system threads).

Since threads are fairly low-level, most applications should use other primitives, like start, which also runs in parallel and returns a Promise.

    use v6;
     my @threads = (^10).map: {
         Thread.start(
             name => "Sleepsorter $_",
             sub {
                 my $rand = (^10).pick;
                 sleep $rand;
                 say $rand;
             },
         );
     }

     .finish for @threads;

The current thread is available in the dynamic variable $*THREAD.

# 169.1 Methods

## 169.1.1 method new

    method new(:&amp;code!, Bool :$app_lifetime = False, Str $name = '&lt;anon>') returns Thread:D

Creates and returns a new Thread, without starting it yet. &code is the code that will be run in a separate thread.

$name is a user-specified string that identifies the thread.

If $app_lifetime is set to True, then the thread is killed when the main thread of the process terminates. If set to False, the process will only terminate when the thread has finished.

## 169.1.2 method start

    method start(Thread:U: &amp;code, Bool :$app_lifetime = False, Str $name = '&lt;anon>') returns Thread:D

Creates, runs and returns a new Thread. Note that it can (and often does) return before the thread's code has finished running.

## 169.1.3 method run

    method run(Thread:D:)

Runs the thread, and returns the invocant. It is an error to run a thread that has already been started.

## 169.1.4 method id

    method id(Thread:D:) returns Int:D

Returns a numeric, unique thread identifier.

## 169.1.5 method finish

    method finish(Thread:D)

Waits for the thread to finish. This is called join in other programming systems.

## 169.1.6 method join

    method join(Thread:D)

Waits for the thread to finish.

## 169.1.7 method yield

    method yield(Thread:U)

Tells the scheduler to prefer another thread for now.

    Thread.yield;

## 169.1.8 method app_lifetime

    method app_lifetime(Thread:D:) returns Bool:D

Returns False unless the named parameter :app_lifetime is specifically set to True during object creation. If the method returns False it means that the the process will only terminate when the thread has finished while True means that the thread will be killed when the main thread of the process terminates.

    my $t1 = Thread.new(code => { for 1..5 -> $v { say $v }});
    my $t2 = Thread.new(code => { for 1..5 -> $v { say $v }}, :app_lifetime);

    say $t1.app_lifetime;                 # False
    say $t2.app_lifetime;                 # True

## 169.1.9 method name

    method name(Thread:D:) returns Str:D

Returns the user defined string, which can optionally be set during object creation in order to identify the Thread, or '<anon>' if no such string was specified.

    my $t1 = Thread.new(code => { for 1..5 -> $v { say $v }});
    my $t2 = Thread.new(code => { for 1..5 -> $v { say $v }}, name => 'my thread');

    say $t1.name;                 # &lt;anon>
    say $t2.name;                 # my thread

## 169.1.10 method Str

    method Str(Thread:D:) returns Str:D

Returns a string which contains the invocants thread id and name.

    my $t = Thread.new(code => { for 1..5 -> $v { say $v }}, name => 'calc thread');
    say $t.Str;                           # Thread&lt;3>(calc thread)

# 170 class ThreadPoolScheduler

Scheduler that distributes work among a pool of threads

    class ThreadPoolScheduler does Scheduler { ... }

The ThreadPoolScheduler has a range of number of threads that it maintains, and it distributes work among those threads. When the upper limit of threads isn't reached yet, and there is work pending, it spawns new threads to handle the work.

# 170.1 Methods

## 170.1.1 new

    method new(Int :$initial_threads = 0, Int :$max_threads=16)

Creates a new ThreadPoolScheduler object with the given range of threads to maintain.

# 171 class Uni

A string of Unicode codepoints

    class Uni does Positional[uint32] does Stringy

Unlike Str, which is made of Grapheme clusters, Uni is string strictly made of Unicode codepoints. That is, base characters and combining characters are separate elements of a Uni instance.

Uni presents itself with a list-like interface of integer Codepoints.

Typical usage of Uni is through one of its subclasses, NFC, NFD, NFKD and NFKC, which represent strings in one of the Unicode Normalization Forms of the same name.

# 171.1 Methods

## 171.1.1 method new

    method new(*@codes) returns Uni:D

Creates a new Uni instance from the given codepoint numbers.

## 171.1.2 method NFC

    method NFC(Uni:D:) returns NFC:D

Returns a NFC (Normal Form Composed)-converted version of the invocant.

## 171.1.3 method NFD

    method NFD(Uni:D:) returns NFD:D

Returns a NFD (Normal Form Decomposed)-converted version of the invocant.

## 171.1.4 method NFKC

    method NFKC(Uni:D:) returns NFKC:D

Returns a NFKC (Normal Form Compatibility Composed)-converted version of the invocant.

## 171.1.5 method NFKD

    method NFKD(Uni:D:) returns NFKD:D

Returns a NFD (Normal Form Compatibility Decomposed)-converted version of the invocant.

## 171.1.6 method codes

    method codes(Uni:D:) returns Int:D

Returns the number of codepoints in the invocant.

## 171.1.7 method elems

    method elems(Uni:D:) returns Int:D

Returns the number of codepoints in the invocant.

# 172 class Variable

Object representation of a variable for use in traits

    class Variable { ... }

Variables have a wealth of compile-time information, but at run time, accesses to a variable usually act on the value stored inside the variable, not the variable itself.

Class Variable holds the compile-time information that traits can use to introspect and manipulate variables.

# 172.1 Routines

## 172.1.1 method name

    method name(Variable:D: str)

Returns the name of the variable, including the sigil.

## 172.1.2 trait is default

    multi sub trait_mod:&lt;is>(Variable:D, :$default!)

Sets the default value with which a variable is initialized, and to which it is reset when Nil is assigned to it. Trait arguments are evaluated at compile time. Closures won't do what you expect. They are stored as is and need to be called by hand.

    my Int $x is default(42);
    say $x;     # 42
    $x = 5;
    say $x;     # 5
    # explicit reset:
    $x = Nil;
    say $x;     # 42

## 172.1.3 trait is dynamic

    multi sub trait_mod:&lt;is>(Variable:D, :$dynamic)

Marks a variable as dynamic, that is, accessible from inner dynamic scopes without being in an inner lexical scope.

        sub introspect() {
             say  <b>$CALLER::x</b> ;
         }
         my $x  <b>is dynamic</b>  = 23;
         introspect;         # 23
         {
             # not dynamic
             my $x;
             introspect()    # dies with an exception of  <a href="#_type_X::Caller::NotDynamic.pod6">type X::Caller::NotDynamic</a>
         }

# 173 class Version

Module version descriptor

    class Version { }

Version objects identify version of software components (and potentially other entities). Perl 6 uses them internally for versioning modules.

A version consists of several parts, which are visually represented by joining them with a dot. A version part is usually an integer, a string like alpha, or a Whatever-star *. The latter is used to indicate that any version part is acceptable in another version that is compared to the current one.

    say v1.0.1 ~~ v1.*;     # True

Version literals can only contain numeric and Whatever parts. They start with a lower-case v, and are followed by at least one part. Multiple parts are separate with a dot .. A trailing + indicates that higher versions are OK in comparisons:

    say v1.2 ~~ v1.0;       # False
    say v1.2 ~~ v1.0+;      # True

In comparisons, early parts take precedence over later parts.

    say v1.2 cmp v2.1;      # Increase

# 173.1 Methods

## 173.1.1 method new

    method new(Str:d $s)

Creates a Version from a string $s. The string is combed for the numeric, alphabetic, and wildcard components of the version object. Any characters other than alphanumerics and asterisks are assumed to be equivalent to a dot. A dot is also assumed between any adjacent numeric and alphabetic characters.

## 173.1.2 method parts

    method parts(Version:D:) returns List:D

Returns the list of parts that make up this Version object

    my $v1 = v1.0.1;
    my $v2 = v1.0.1+;
    say $v1.parts;                                    # (1 0 1)
    say $v2.parts;                                    # (1 0 1)

## 173.1.3 method plus

    method plus(Version:D:) returns Bool:D

Returns True if comparisons against this version allow larger versions too.

    my $v1 = v1.0.1;
    my $v2 = v1.0.1+;
    say $v1.plus;                                     # False
    say $v2.plus;                                     # True

## 173.1.4 method Str

    method Str(Version:D:) returns Str:D

Returns a string representation of the invocant.

    my $v1 = v1.0.1;
    my $v2 = Version.new('1.0.1');
    say $v1.Str;                                      # 1.0.1
    say $v2.Str;                                      # 1.0.1

## 173.1.5 method gist

    method gist(Version:D:) returns Str:D

Returns a string representation of the invocant, just like Str, prepended with a lower-case v.

    my $v1 = v1.0.1;
    my $v2 = Version.new('1.0.1');
    say $v1.gist;                                      # v1.0.1
    say $v2.gist;                                      # v1.0.1

# 174 class Whatever

Placeholder for an unspecified value/argument

    class Whatever { }

Whatever is a class whose objects don't really do much; it gets its semantic from other routines that accept Whatever-objects as markers to do something special. The * literal in term position creates a Whatever object.

Much of *'s charm comes from Whatever-currying. When * is used in term position in combination with most operators, the compiler will transform the expression into a closure of type WhateverCode.

    my $c = * + 2;          # same as   -> $x { $x + 2 };
    say $c(4);              # 6

Multiple * in one expression generate closures with as many arguments:

    my $c = * + *;          # same as   -> $x, $y { $x + $y }

Using * in complex expressions will also generate closures:

    my $c = 4 * * + 5;      # same as   -> $x { 4 * $x + 5 }

Calling a method on * also creates a closure:

    &lt;a b c>.map: *.uc;      # same as    &lt;a b c>.map: -> $char { $char.uc }

As mentioned before, not all operators and syntactic constructs curry * (or Whatever-stars) to WhateverCode. In the following cases, * will remain a Whatever object.

Exception | Example | What it does
--- | --- | ---
comma | 1, *, 2 | generates a List with a * element
range operators | 1..* | Range.new(:from(1), :to(*));
series operator | 1 ... * | infinite list
smart-matching | 1 ~~ * | returns True
assignment | $x = * | assign * to $x
binding | $x := * | binds * to $x
list repetition | 1 xx * | generates infinite list

The range operators are handled specially. They do not curry with Whatever-stars, but they do curry with WhateverCode

    say (1..*).WHAT;        # Range
    say (1..*-1).WHAT;      # WhateverCode

This allow all these constructs to work:

    .say for 1..*;          # infinite loop
    my @a = 1..4;
    say @a[0..*];           # 1 2 3 4
    say @a[0..*-2];         # 1 2 3

Because Whatever-currying is a purely syntactic compiler transform, you will get no runtime currying of stored Whatever-stars into WhateverCodes.

    my $x = *;
    $x + 2;                 # not a closure, dies because
                            # it can't coerce $x to Numeric

The use cases for stored Whatever-stars are involve those curry-exception cases mentioned above. For example, if you want an infinite series by default.

    my $max    = potential-upper-limit() // *;
    my $series = known-lower-limit() ... $max;

A stored * will also result in the generation of a WhateverCode in the specific case of smart match. Note that this is not actually the stored * which is being curried, but rather the * on the LHS.

    my $constraint = find-constraint() // *;
    my $maybe-always-matcher = * ~~ $constraint;

If this hypothetical find-constraint were to have found no constraint, $maybe-always-matcher would return to True for anything.

    $maybe-always-matcher(555);      # True
    $maybe-always-matcher(Any);      # True

# 174.1 Methods

## 174.1.1 method ACCEPTS

    multi method ACCEPTS(Whatever:D: Mu $other)

Returns True.

# 175 class WhateverCode

Code object constructed by Whatever-currying

    class WhateverCode is Code { }

WhateverCode objects are the result of Whatever-currying. See the Whatever documentation for details.

When you wish to control how a method or function interprets any Whatever stars, you may use multi dispatch with Whatever and WhateverCode parameters to do so, as in the following example:

    class Cycle {
          has $.pos;
          has @.vals;
    }

    multi sub get_val(Cycle $c, Int $idx) {
          $c.vals[$idx % $c.vals.elems]
    }

    # Define what to do with a stand-alone * as the second argument
    multi sub get_val(Cycle $c, Whatever $idx) {
        get_val($c, $c.pos);
    }

    # Define what to do with a * in an expression
    multi sub get_val(Cycle $c, WhateverCode $idx) {
        get_val($c, $idx($c.pos));
    }

    my Cycle $c .= new(:pos(2), :vals(0..^10));

    say get_val($c, 3);   # 3
    say get_val($c, *);   # 2
    say get_val($c, *-1); # 1

Since WhateverCode objects are Callable you may use introspection to create as fancy a behavior as you wish. Continuing the following example we may add handling for two Whatever stars:

    # Define what to do with two * in an expression
    multi sub get_val(Cycle $c, WhateverCode $idx where { .arity == 2 }) {
        get_val($c, $idx($c.pos, $c.vals.elems));
    }

    say get_val($c, * + * div 2); # 2 + 10/2 = 7

Note, though, that subexpressions may impose their own Whatever star rules:

    my @a = (0, 1, 2);
    say get_val($c, @a[*-1]) # 2, because the star belongs to the Array class

This can make the ownership of Whatever stars become confusing rather quickly, so be careful not to overdo it.

# 176 class X::AdHoc

Error with a custom error message

    class X::AdHoc is Exception { ... }

X::AdHoc is the type into which objects are wrapped if they are thrown as exceptions, but don't inherit from Exception.

Its benefit over returning non-Exception objects is that it gives access to all the methods from class Exception, like backtrace and rethrow.

You can obtain the original object with the payload method.

    try {
        die [404, 'File not found']; # throw non-exception object
    }
    say "Got HTTP code ",
        $!.payload[0],          # 404
        " and backtrace ",
        $!.backtrace;

Note that young code will often be prototyped using X::AdHoc and then later be revised to use more specific subtypes of Exception. As such it is usually best not to explicitly rely on receiving an X::AdHoc -- in many cases using the string returned by the .message method, which all Exceptions must have, is preferable.

# 176.1 Methods

## 176.1.1 method payload

    method payload(X::AdHoc:D)

Returns the original object which was passed to die.

# 177 class X::Anon::Augment

Compilation error due to augmenting an anonymous package

    class X::Anon::Augment does X::Comp { }

Compile time error thrown when trying to augment an anonymous package.

For example

    use MONKEY-TYPING;
    augment class { }

Dies with

    ===SORRY!===
    Cannot augment anonymous class

# 177.1 Methods

## 177.1.1 method package-kind

    method package-kind returns Str:D

Returns the kind of package (module, class, grammar, ...) that the code tried to augment.

# 178 class X::Anon::Multi

Compilation error due to declaring an anonymous multi

    class X::Anon::Multi does X::Comp { }

Compile time error thrown when an anonymous multi is being declared.

For example

    multi method () { }

dies with

    ===SORRY!===
    Cannot put multi on anonymous method

# 178.1 Methods

## 178.1.1 method multiness

    method multiness() returns Str:D

Returns a string describing the multiness that the original code used, for example "multi" or "proto".

## 178.1.2 method routine-type

    method routine-type() returns Str:D

Returns a string describing the type of routine that was declared, for example "sub" or "method".

# 179 class X::Assignment::RO

Exception thrown when trying to assign to something read-only

    class X::Assignment::RO is Exception { ... }

Code like

    sub f() { 42 };
    f() = 'new value';  # throws an X::Assignment::RO

throws an exception of type X::Assignment::RO.

# 179.1 Methods

## 179.1.1 method typename

    method typename(X::Assignment::RO:D:) returns Str

Returns the type name of the value on the left-hand side

# 180 class X::Attribute::NoPackage

Compilation error due to declaring an attribute outside of a package

    class X::Attribute::NoPackage does X::Comp { }

Compile time error thrown when an attribute is declared where it does not make sense (for example in the mainline).

For example

    has $.x;

Dies with

    ===SORRY!===
    You cannot declare attribute '$.x' here; maybe you'd like a class or a role?

# 180.1 Methods

## 180.1.1 method name

    method name() returns Str:D

Returns the name of the attribute

# 181 class X::Attribute::Package

Compilation error due to declaring an attribute in an ineligible package

    class X::Attribute::Package does X::Comp { }

Compile time error, thrown when the compiler encounters an attribute declaration inside a package that does not support attributes.

For example

    module A { has $.x }

dies with

    ===SORRY!===
    A module cannot have attributes, but you tried to declare '$.x'

# 181.1 Methods

## 181.1.1 method name

    method name() returns Str:D

Returns the name of the attribute that triggered this error.

## 181.1.2 method package-kind

    method package-kind() returns Str:D

Returns the kind of package (package, module) that doesn't support attributes.

# 182 class X::Attribute::Undeclared

Compilation error due to an undeclared attribute

    class X::Attribute::Undeclared is X::Undeclared { }

Thrown when code refers to an attribute that has not been declared.

For example the code

    class A { method m { $!notthere } }

Produces the error

    Attribute $!notthere not declared in class A

# 182.1 Methods

## 182.1.1 method package-kind

Returns the kind of package the attribute was used in (for example class, grammar)

## 182.1.2 method package-name

Returns the name of the package in which the offensive attribute reference was performed.

# 183 class X::Augment::NoSuchType

Compilation error due to augmenting a non-existing type

    class X::Augment::NoSuchType does X::Comp { }

Thrown when trying to augment a type which doesn't exist.

For example

    use MONKEY-TYPING;
    augment class NoSuch { }

dies with

    ===SORRY!===
    You tried to augment class NoSuch, but it does not exist

# 183.1 Methods

## 183.1.1 method package-kind

    method package-kind() returns Str:D

Returns the kind of package (class, grammar) that is being tried to augment

## 183.1.2 method package

Returns the name that was tried to augment, but which doesn't exist.

# 184 class X::Bind

Error due to binding to something that is not a variable or container

    class X::Bind is Exception { ... }

If you write code like this:

    floor(1.1) := 42;

it dies with an X::Bind exception:

    Cannot use bind operator with this left-hand side

# 185 class X::Bind::NativeType

Compilation error due to binding to a natively typed variable

    class X::Bind::NativeType does X::Comp { }

Compile-time error thrown when trying to bind to a natively typed variable.

Since native variables explicitly don't have the concept of a container at run time. Thus it does not make sense to support both binding and assignment, and Perl 6 supports only assignment (which makes more sense, because native types are value types). So use assignment for natively typed variables.

For example the code

    my int $x := 3;

dies with

    Cannot bind to natively typed variable '$x'; use assignment instead

and can be fixed by writing it as

    my int $x = 3;

# 185.1 Methods

## 185.1.1 method name

    method name() returns Str:D

Returns the name of the variable.

# 186 class X::Bind::Slice

Error due to binding to a slice

    class X::Bind::Slice is Exception { ... }

When you try to bind to an array or hash slice:

    my @a; @a[0, 1] := [42];    # Cannot bind to Array slice
    my %h; %h&lt;a b> := {};       # Cannot bind to Hash slice

you get an exception of type ::Bind::Slice

# 186.1 Methods

## 186.1.1 method type

    method type(X::Bind::Slice:D:)

returns the type object of the thing that you tried to slice-bind, for example Array, List or Hash.

# 187 class X::Caller::NotDynamic

Error while trying to access a non dynamic variable through CALLER

    class X::Caller::NotDynamic is Exception { }

Thrown when trying to access a non dynamic variable through CALLER

A typical error message is

    Cannot access '$x' through CALLER, because it is not declared as dynamic

# 187.1 Methods

## 187.1.1 method symbol

Returns the name of the symbol that was passed to CALLER.

# 188 class X::Channel::ReceiveOnClosed

Error due to calling

    class X::Channel::ReceiveOnClosed { ... }

This exception is thrown when a calling receive on a Channel that has been closed:

    my $s = Channel.new;
    $s.close;
    $s.receive;     # Cannot receive a message on a closed channel

# 188.1 Methods

## 188.1.1 method channel

    method Channel(:D:) return Channel:D

Returns the Channel object on which the receive method was called.

# 189 class X::Channel::SendOnClosed

Error due to calling

    class X::Channel::SendOnClosed { ... }

This exception is thrown when a calling send on a Channel that has been closed:

    my $s = Channel.new;
    $s.close;
    $s.send(42);    # Cannot send a message on a closed channel

# 189.1 Methods

## 189.1.1 method channel

    method Channel(:D:) return Channel:D

Returns the Channel object on which the send method was called.

# 190 role X::Comp

Common role for compile-time errors

    role X::Comp is Exception { }

Common role for compile-time errors.

Note that since the backtrace of a compile time error generally shows routines from the compiler, not from user-space programs, the Backtrace returned from the backtrace method is not very informative. Instead the exception carries its own filename, line and column attributes and public accessors.

If an error occurs while creating an object (like a class or routine) at compile time, generally the exception associated with it does not hold a reference to the object (for example a class would not be fully composed, and thus not usable). In those cases the name of the would-be-created object is included in the error message instead.

# 190.1 Methods

## 190.1.1 method filename

The filename in which the compilation error occurred

## 190.1.2 method line

The line number in which the compilation error occurred.

## 190.1.3 method column

The column number of location where the compilation error occurred. (Rakudo does not implement that yet).

# 191 class X::Composition::NotComposable

Compilation error due to composing an ineligible type

    class X::Composition::NotComposable is Exception { }

Thrown when trying to compose a type into a target type, but the composer type cannot be used for composition (roles and enums are generally OK).

For example

    class A { }
    class B does A { }

dies with

    ===SORRY!===
    ␤A is not composable, so B cannot compose it

because does is reserved for role composition, and A is not a role, nor something that knows how to turn into a role.

The fix is to either make A a role, or use inheritance (class B is A { }) instead.

# 191.1 Methods

## 191.1.1 method target-name

    method target-name() returns Str:D

Returns the name of the type that should be composed, but failed.

## 191.1.2 method composer

    method composer() returns Mu

Returns the type that should be composed into the target, but which isn't a role.

# 192 class X::Constructor::Positional

Error due to passing positional arguments to a default constructor

    class X::Constructor::Positional is Exception { }

Thrown from Mu.new when positional arguments are passed to it.

For example

    class A { }
    A.new(2, 3)

dies with

    Default constructor only takes named arguments

# 193 class X::ControlFlow

Error due to calling a loop control command in an ineligible scope

    class X::ControlFlow is Exception { }

Thrown when a control flow construct (such as next or redo) is called outside the dynamic scope of an enclosing construct that is supposed to catch them.

For example

    last

dies with

    last without loop construct

# 193.1 Methods

## 193.1.1 method illegal

    method illegal returns Str:D

Returns the name of the control flow command that was called.

## 193.1.2 method enclosing

    method enclosing returns Str:D

Returns the name of the missing enclosing construct.

# 194 class X::ControlFlow::Return

Error due to calling return outside a routine

    class X::ControlFlow::Return is X::ControlFlow { }

Thrown when a return is called from outside a routine.

    return

dies with

    Attempt to return outside of any Routine

# 195 class X::DateTime::TimezoneClash

Error due to using both timezone offset and :timezone

    class X::DateTime::TimezoneClash does X::Temporal is Exception { }

This exception is thrown when code tries to create a DateTime object specifying both a timezone offset and the named argument :timezone.

    say DateTime.new('2015-12-24T12:23:00+0200');                   # works
    say DateTime.new('2015-12-24T12:23:00', timezone => 7200);      # works
    say DateTime.new('2015-12-24T12:23:00+0200', timezone => 7200); # exception

# 195.1 Methods

## 195.1.1 message

Returns 'DateTime.new(Str): :timezone argument not allowed with a timestamp offset'

# 196 class X::Declaration::Scope

Compilation error due to a declaration with an ineligible scope

    class X::Declaration::Scope does X::Comp { }

Compile time error thrown when a declaration does not harmonize with the declared scope.

For example

    has sub f() { }

dies with

    ===SORRY!===
    Cannot use 'has' with sub declaration

# 196.1 Methods

## 196.1.1 method scope

    method scope() returns Str:D

Returns a string representation of the scope, usually the same keyword that is used for the declaration ("my", "our", "has", ...);

## 196.1.2 method declaration

    method declaration() returns Str:D

Describes the symbol that has been declared in a wrong scope.

# 197 class X::Declaration::Scope::Multi

Compilation error due to declaring a multi with an ineligible scope

    class X::Declaration::Scope::Multi is X::Declaration::Scope { }

Thrown when a multi is declared with an incompatible scope.

For example our multi sub foo() { } dies with

    ===SORRY!===
    Cannot use 'our' with individual multi candidates. Please declare an our-scoped proto instead

# 198 class X::Does::TypeObject

Error due to mixing into a type object

    class X::Does::TypeObject is Exception { ... }

When you try to add one or more roles to a type object with does after it has been composed, an error of type X::Does::TypeObject is thrown:

    Mu does Numeric;    # Cannot use 'does' operator with a type object.

The correct way to apply roles to a type is at declaration time:

    class GrassmannNumber does Numeric { ... }
    role AlgebraDebugger does IO { ... }
    grammar IntegralParser does AlgebraParser { ... }

Roles may only be runtime-mixed into defined object instances:

    GrassmanNumber.new does AlgebraDebugger;

(This restriction may be worked around by using augment or supersede, or with dark Metamodel magics, but this will likely result in a significant performance penalty.)

# 198.1 Methods

## 198.1.1 method type

    method type(X::Codes::TypeObject:D:) returns Mu:U

Returns the type object into which the code tried to mix in a role.

# 199 class X::Eval::NoSuchLang

Error due to specifying an unknown language for EVAL

    class X::Eval::NoSuchLang is Exception { }

Error thrown when EVAL($str, :$lang) specifies a language that the compiler does not know how to handle.

For example

    EVAL 'boo', lang => bar;

dies with

    No compiler available for language 'bar'

# 199.1 Methods

## 199.1.1 method lang

    method lang()

Returns the language that /routine/EVAL did not know how to handle.

# 200 class X::Export::NameClash

Compilation error due to exporting the same symbol twice

    class X::Export::NameClash does X::Comp { }

Compile time error thrown when a symbol is exported twice.

For example

    sub f() is export { };
    {
        sub f() is export { }
    }

dies with

    ===SORRY!===
    A symbol '&amp;f' has already been exported

# 200.1 Methods

## 200.1.1 method symbol

Returns the symbol that is exported twice.

# 201 role X::IO

IO related error

    role X::IO does X::OS {}

Common role for IO related errors.

This role does not provide any additional methods.

# 202 class X::IO::Chdir

Error while trying to change the working directory

    class X::IO::Chdir does X::IO is Exception { }

Error class when a chdir call failed.

A typical error message is

    Failed to change the working directory to '/home/other': permission denied

# 202.1 Methods

## 202.1.1 method path

Returns the path that was passed to the failed chdir call.

# 203 class X::IO::Chmod

Error while trying to change file permissions

    class X::IO::Chmod does X::IO is Exception

Error class for failed chmod calls.

A typical error message is

    Failed to set the mode of '/home/other' to '0o777': Permission denied

# 204 class X::IO::Copy

Error while trying to copy a file

    class X::IO::Copy does X::IO is Exception { }

Error class for failed file copy operations. A typical error message is

    Failed to copy 'source' to 'destination': permission denied

# 204.1 Methods

## 204.1.1 method from

Returns the source of the failed copy operation

## 204.1.2 method to

Returns the destination of the failed copy operation

# 205 class X::IO::Cwd

Error while trying to determine the current working directory

    class X::IO::Cwd does X::IO is Exception { }

Error class when the runtime fails to determine the current directory.

A typical error message is

    Failed to get the working directory: permission denied

# 206 class X::IO::Dir

Error while trying to get a directory's contents

    class X::IO::Dir does X::IO is Exception { }

Error class that is thrown when a /routine/dir call fails.

A typical error message is

    Failed to get the directory contents of '/tmp/': No such file or directory

# 206.1 Methods

## 206.1.1 method path

Returns the path that /routine/dir failed to read.

# 207 class X::IO::DoesNotExist

Error while doing file tests on a non existing path

    class X::IO::DoesNotExist does X::IO is Exception { }

Thrown when doing e.g. file test operations on a non existing path.

A typical error message is

    Failed to find 'euler-5.p6' while trying to do '.f'

# 207.1 Methods

## 207.1.1 method path

Returns the path that was passed to the failed call.

## 207.1.2 method trying

Returns a string describing the failed operation.

# 208 class X::IO::Link

Error while trying to create a link

    class X::IO::Link does X::IO is Exception

Error class for failed /routine/link operation.

A typical error message is

    Failed to create link called 'my-link' on target 'does-not exist': Failed to link file

# 208.1 Methods

## 208.1.1 method target

Returns the name of the link target, i.e. the existing file.

## 208.1.2 method name

Returns the name of the link that could not be created.

# 209 class X::IO::Mkdir

Error while trying to create a directory

    class X::IO::Mkdir does X::IO is Exception

Error class for failed mkdir operations.

A typical error message is

    Failed to create directory 'destination' with mode '0o755': File exists

# 209.1 Methods

## 209.1.1 method path

Returns the path that the mkdir operation failed to create.

## 209.1.2 method mode

Returns the permissions mask of the failed mkdir operation as an Int.

# 210 class X::IO::Move

Error while trying to move a file

    class X::IO::Move does X::IO is Exception { }

Error class for a failed file move operation. A typical error message is

    Failed to move '/tmp/alpha.p6' to 'test.p6': :createonly specified and destination exists

# 210.1 Methods

## 210.1.1 method from

Returns the source of the failed move operation

## 210.1.2 method to

Returns the destination of the failed move operation

# 211 class X::IO::Rename

Error while trying to rename a file or directory

    class X::IO::Rename does X::IO is Exception { }

Error class for failed file or directory rename operations. A typical error message is

    Failed to rename 'source' to 'destination': is a directory

# 211.1 Methods

## 211.1.1 method from

Returns the source of the failed rename operation

## 211.1.2 method to

Returns the destination of the failed rename operation

# 212 class X::IO::Rmdir

Error while trying to remove a directory

    my class X::IO::Rmdir does X::IO is Exception

Error class for failed /routine/rmdir operations.

A typical error message is

    Failed to remove the directory 'lib': Directory not empty

# 212.1 Methods

## 212.1.1 method path

Returns the path /routine/rmdir failed to remove

# 213 class X::IO::Symlink

Error while trying to create a symbolic link

    class X::IO::Symlink does X::IO is Exception

Error class for failed symlink creation.

A typical error message is

    Failed to create symlink called 'euler' on target '/home/myhome/euler-1.pl6': Failed to symlink file: file already exist

# 213.1 Methods

## 213.1.1 method name

Returns the path that symlink failed to create.

## 213.1.2 method target

Returns the path that symlink failed to create a link to.

# 214 class X::IO::Unlink

Error while trying to remove a file

    class X::IO::Unlink does X::IO is Exception

Error class for failed /routine/unlink operation.

A typical error message is

    Failed to remove the file 'secret': Permission defined

# 214.1 Methods

## 214.1.1 method path

Returns the path that /routine/unlink failed to delete.

# 215 class X::Inheritance::NotComposed

Error due to inheriting from a type that's not composed yet

    class X::Inheritance::NotComposed is Exception { ... }

When you try to inherit from a class that hasn't been composed, an exception of type X::Inheritance::NotComposed is thrown.

Usually this happens because it's not yet fully parsed, or that is stubbed:

    class A { ... };    # literal ... for stubbing
     class B is A { };   # dies with
                         # 'B' cannot inherit from 'A' because 'A'
                         # isn't compose yet (maybe it is stubbed)

The second common way to trigger this error is by trying to inherit from a class from within the class body.

    class Outer {
         class Inner is Outer {  # dies with
         }                       # 'Inner' cannot inherit from 'Outer' because
     }                           # 'Outer' isn't compose yet (maybe it is
                                 # stubbed)

# 215.1 Methods

## 215.1.1 method child-name

    method child-name(X::Inheritance::NotComposed:D:) returns Str:D

Returns the name of the type that tries to inherit.

## 215.1.2 method parent-name

    method parent-name(X::Inheritance::NotComposed:D:) returns Str:D

Returns the name of the parent type that the type tries to inherit from

# 216 class X::Inheritance::Unsupported

Compilation error due to inheriting from an ineligible type

    class X::Inheritance::Unsupported does X::Comp { }

Compile time error thrown when trying to inherit from a type that does not support inheritance (like a package or an enum).

For example

    enum A &lt;Ax Ay>;
    class B is A { };

dies with

    ===SORRY!===
    A does not support inheritance, so B cannot inherit from it

# 216.1 Methods

## 216.1.1 method child-typename

The name of the type that tries to inherit.

## 216.1.2 method parent

The type object that the child tried to inherit from.

# 217 class X::Method::InvalidQualifier

Error due to calling a qualified method from an ineligible class

    class X::Method::InvalidQualifier is Exception { }

Thrown when a method is call in the form $invocant.TheClass::method if <$invocant> does not conform to TheClass.

For example

    1.Str::split(/a/)

dies with

    dispatch to method split on Str because it is not inherited or done by Int

# 217.1 Methods

## 217.1.1 method method

    method method() returns Str:D

Returns the name of the (unqualified) method.

## 217.1.2 method invocant

Returns the invocant of the failed, qualified method call

## 217.1.3 method qualifier-type

Returns the type by which the method call was qualified.

# 218 X::Method::NotFound

Error due to calling a method that isn't there

    class X::Method::NotFound is Exception

Thrown when the user tries to call a method that isn't there.

For example 1.nosuch dies with

    No such method 'nosuch' for invocant of type 'Int'

# 218.1 Methods

## 218.1.1 method method

    method method() returns Str:D

Returns the method name that was invoked.

## 218.1.2 method typename

    method typename returns Str:D

Returns the name of the invocant type.

## 218.1.3 method private

    method private returns Bool:D

Returns True for private methods, and False for public methods.

# 219 class X::Method::Private::Permission

Compilation error due to calling a private method without permission

    class X::Method::Private::Permission does X::Comp { }

Compile time error thrown when the code contains a call to a private method that isn't defined in the current class, and when no appropriate trusts relation is defined that permits the private method call.

For example the code

    1!Int::foo

dies with

    ===SORRY!===
    Cannot call private method 'foo' on package Int because it does not trust GLOBAL

# 219.1 Methods

## 219.1.1 method method

    method method() returns Str:D

The name of the private method

## 219.1.2 method source-package

    method source-package() returns Mu:D

Returns the type object that (supposedly) contains the private method.

## 219.1.3 method calling-package

    method calling-package() returns Mu:D

Returns the package in which the calling code is, and which the source package does not trust.

# 220 class X::Method::Private::Unqualified

Compilation error due to an unqualified private method call

    class X::Method::Private::Unqualified does X::Comp { }

Compile time error thrown when a private method call on anything but self is not fully qualified.

For example

    1!priv

dies with

    Private method call to priv must be fully qualified with the package containing the method

# 220.1 Methods

## 220.1.1 method method

    method method() returns Str:D

Returns the name of the private method that triggered the error.

# 221 class X::Mixin::NotComposable

Error due to using an ineligible type as a mixin

    class X::Mixin::NotComposable is Exception { }

Thrown when a mixin with infix does or but is done with a composer that cannot be used for mixin.

For example

    class A { }
    1 but A

dies with

    Cannot mix in non-composable type A into object of type Int

The compile-time equivalent of this error is X::CompositionNotComposable

# 221.1 Methods

## 221.1.1 method target

    method target()

Returns the target of the failed mixin operation.

## 221.1.2 method rolish

    method rolish()

Returns the thing that could not act as a role for mixing it in

# 222 class X::NYI

Error due to use of an unimplemented feature

    class X::NYI is Exception { }

Error class for unimplemented features. NYI stands for Not Yet Implemented.

If a Perl 6 compiler is not yet feature complete, it may throw an X::NYI exception when a program uses a feature that it can detect is not yet implemented.

A full-featured Perl 6 compiler must not throw such exceptions, but still provide the X::NYI class for compatibility reasons.

A typical error message is

    HyperWhatever is not yet implemented. Sorry.

# 222.1 Methods

## 222.1.1 method features

Returns a Str describing the missing feature.

# 223 class X::NoDispatcher

Error due to calling a dispatch command in an ineligible scope

    class X::NoDispatcher is Exception { }

When a redispatcher like nextsame is called without being in the dynamic scope of a call where a redispatch is possible, an X::NoDispatcher is thrown.

For example

    nextsame

in the mainline dies with

    nextsame is not in the dynamic scope of a dispatcher

# 223.1 Methods

## 223.1.1 method redispatcher

    method redispatcher() returns Str:D

Returns the name of the redispatcher function that did not succeed.

# 224 class X::Numeric::Real

Error while trying to coerce a number to a Real type

    class X::Numeric::Real is Exception { }

Occurs when an attempt to coerce a Numeric to a Real, Num, Int or Rat fails (due to a number with a nonzero imaginary part, for instance).

For example

    say (1+2i).Int

fails with

    Can not convert 1+2i to Int: imaginary part not zero

# 224.1 Methods

## 224.1.1 method source

    method source() returns Numeric:D

Returns the number that failed to coerce to Real.

## 224.1.2 method target

    method target()

Returns the type to which the coercion was attempted.

## 224.1.3 method reason

    method reason() returns Str:D

Returns the reason that the conversion failed.

# 225 role X::OS

Error reported by the operating system

    role X::OS { has $.os-error }

Common role for all exceptions that are triggered by some error reported by the operating system (failed IO, system calls, fork, memory allocation).

# 225.1 Methods

## 225.1.1 method os-error

    method os-error() returns Str:D

Returns the error as reported by the operating system.

# 226 class X::Obsolete

Compilation error due to use of obsolete syntax

    class X::Obsolete does X::Comp { }

Syntax error thrown when obsolete (mostly Perl 5) syntax is detected.

For example

    m/abc/i

dies with

    ===SORRY!===
    Unsupported use of /i; in Perl 6 please use :i

# 226.1 Methods

## 226.1.1 method old

    method old() returns Str:D

Returns a textual description of the obsolete syntax construct

## 226.1.2 method replacement

    method replacement() returns Str:D

Describes what to use instead of the obsolete syntax.

## 226.1.3 method when

    method when() returns Str:D

Returns a string describing the state of the language (usually " in Perl 6").

# 227 class X::OutOfRange

Error due to indexing outside of an allowed range

    class X::OutOfRange is Exception { }

General error when something (for example an array index) is out of an allowed range.

For example

    say 42[2]

dies with

    Index out of range. Is: 2, should be in 0..0

since scalars generally act as a one-element list.

# 227.1 Methods

## 227.1.1 method what

    method what() returns Str:D

Verbal description of the thing that was out of range (e.g. "array index", "month").

## 227.1.2 method got

    method got()

Returns the object that was considered out of range (often an integer)

## 227.1.3 method range

    method range returns Range:D

Returns a Range object describing the permissible range for the object returned from .got.

## 227.1.4 method comment

    method comment returns Str

Returns an additional comment that is included in the error message.

# 228 class X::Package::Stubbed

Compilation error due to a stubbed package that is never defined

    class X::Package::Stubbed does X::Comp { }

Thrown at CHECK time when there are packages stubbed but not later defined.

For example

    class A { ... }     # literal ...
    class B { ... }     # literal ...

dies with

    ===SORRY!===
    The following packages were stubbed but not defined:
        A
        B

# 228.1 Methods

## 228.1.1 method packages

    method packages() returns Positional:D

Returns a list of packages that were stubbed but not defined.

# 229 class X::Parameter::Default

Compilation error due to an unallowed default value in a signature

    class X::Parameter::Default does X::Comp { }

Compile-time error thrown when a parameter in a signature has default value, but isn't allowed to have one. That is the case with slurpy parameters (because a slurpy always binds successfully, even to zero arguments) and with mandatory parameters.

Example:

    sub f($x! = 3) { }

Produces

    ===SORRY!===
    Cannot put default on required parameter $x

And

    sub f(*@ = 3) { }

produces

    Cannot put default on anonymous slurpy parameter

# 229.1 Methods

## 229.1.1 method how

Returns a string describing how the parameter is qualified that makes it disallow default values, for example "slurpy" or "mandatory".

## 229.1.2 method parameter

Returns the parameter name

# 230 X::Parameter::MultipleTypeConstraints

Compilation error due to a parameter with multiple type constraints

    class X::Parameter::MultipleTypeConstraints does X::Comp { }

Compile time error thrown when a parameter has multiple type constraints. This is not allowed in Perl 6.0.

Example:

    sub f(Cool Real $x) { }

produces

    Parameter $x may onle have one prefix type constraint

# 230.1 Methods

## 230.1.1 method parameter

Returns the name of the offensive parameter.

# 231 class X::Parameter::Placeholder

Compilation error due to an unallowed placeholder in a signature

    class X::Parameter::Placeholder does X::Comp

Thrown when a placeholder parameter is used inside a signature where a normal parameter is expected. The reason is often that a named parameter :$param was misspelled as $:param.

For example

    sub f($:param) { }

produces

    ===SORRY!===
    In signature parameter, placeholder variables like $:param are illegal
    you probably meant a named parameter: ':$param'

# 231.1 Methods

## 231.1.1 method parameter

The text of the offensive parameter declaration ($:param in the example above).

## 231.1.2 method right

Suggestion on how to write the parameter declaration instead (:$param in the example above).

# 232 class X::Parameter::Twigil

Compilation error due to an unallowed twigil in a signature

    class X::Parameter::Twigil does X::Comp

Thrown when a parameter in a signature has a twigil that it may not have. Only !, . and * as twigils are allowed.

Example:

    sub f($=foo) { }

produces

    ===SORRY!===
    In signature parameter $=foo, it is illegal to use the = twigil

# 232.1 Methods

## 232.1.1 method parameter

The name of the offensive parameter ($=foo in the example above)

## 232.1.2 method twigil

The illegally used twigil.

# 233 X::Parameter::WrongOrder

Compilation error due to passing parameters in the wrong order

    class X::Parameter::WrongOrder does X::Comp

Compile time error that is thrown when parameters in a signature in the wrong order (for example if an optional parameter comes before a mandatory parameter).

For example

    sub f($a?, $b) { }

produces

    Cannot put required parameter $b after optional parameters

# 233.1 Methods

## 233.1.1 method misplaced

Returns the kind of misplaced parameter (for example "mandatory", "positional").

## 233.1.2 method parameter

Returns the name of the (first) misplaced parameter

## 233.1.3 method after

Returns a string describing other parameters after which the current parameter was illegally placed (for example "variadic", "positional" or "optional").

# 234 class X::Phaser::Multiple

Compilation error due to multiple phasers of the same type

    class X::Phaser::Multiple does X::Comp

Thrown when multiple phasers of the same type occur in a block, but only one is allowed (for example CATCH or CONTROL).

Example

    CATCH { }; CATCH { }

Produces

    ===SORRY!===
    Only one CATCH block is allowed

# 234.1 Methods

## 234.1.1 method block

Returns the name of the phaser that occurred more than once.

# 235 class X::Phaser::PrePost

Error due to a false return value of a PRE/POST phaser

    class X::Phaser::PrePost is Exception { }

Thrown when the condition inside a PRE or POST phaser evaluate to a false value.

For example

    sub f($x) { PRE { $x ~~ Int } }
    f "foo";

Dies with

    Precondition '{ $x ~~ Int }' failed

# 235.1 Methods

## 235.1.1 method phaser

    method phaser() returns Str:D

Returns the name of the failed phaser, "PRE" or "POST".

## 235.1.2 method condition

    method condition() returns Str:D

Returns the part of the source code that describes the phaser condition.

# 236 class X::Placeholder::Block

Compilation error due to a placeholder in an ineligible block

    class X::Placeholder::Block does X::Comp

Thrown when a placeholder variable is used in a block that does not allow a signature (for example class A { $^foo }.

A typical error message is

    Placeholder variable $^foo may not be used here because the surrounding block takes no signature

# 236.1 Methods

## 236.1.1 method placeholder

Returns the name of the (first) illegally used placeholder.

# 237 X::Placeholder::Mainline

Compilation error due to a placeholder in the mainline

    class X::Placeholder::Mainline is X::Placeholder::Block

Thrown when a placeholder variable is used in the mainline, i.e. outside of any explicit block.

Example:

    $^x

Produces the error message

    Cannot use placeholder parameter $^x in the mainline

Note that this error can also occur when you think something is a block, but it really is a postcircumfix:<{ }>, for example

    my %h;
    say %h{ $^x };
    #     ^^^^^^^  not a block, so $^x is part of the mainline

# 238 role X::Pod

Pod related error

    role X::Pod { }

Common role for Pod related errors.

# 239 role X::Proc::Async

Exception thrown by

    role X::Proc::Async is Exception { ... }

All exceptions thrown by Proc::Async do this common role.

# 239.1 Methods

## 239.1.1 method proc

    method fproc(X::Proc::Async:D) returns Proc::Async

Returns the object that threw the exception.

# 240 class X::Proc::Async::AlreadyStarted

Error due to calling

    class X::Proc::Async::AlreadyStarted is Exception { ... }

When you call start twice on the same Proc::Async object, the second invocation will die with an X::Proc::Async::AlreadyStarted exception.

    my $proc = Proc::Async.new("echo");
    $proc.start;
    $proc.start;    # Process has already been started

# 241 class X::Proc::Async::CharsOrBytes

Error due to tapping the same

    class X::Proc::Async::CharsOrBytes is Exception { ... }

A Proc::Async object allows subscription to the output or error stream either for bytes (Blob) or for text data (Str), but not for both. If you do try both, it throws an exception of type X::Proc::Async::CharsOrBytes.

    my $proc = Proc::Async.new('echo');
    $proc.stdout.tap(&amp;print);
    $proc.stdout(:bin).tap(&amp;print); # dies with
                                    # Can only tap one of chars or bytes supply for stdout

# 241.1 Methods

## 241.1.1 method handle

    method handle(X::Proc::Async::CharsOrBytes:D:) returns Str:D

Returns the name of the handle that was accessed both for text and for binary data, stdout or stderr.

# 242 class X::Proc::Async::MustBeStarted

Error due to interacting with a

    class X::Proc::Async::MustBeStarted is Exception { ... }

Several methods from Proc::Async expect that the external program has been spawned (by calling .start on it), including say, write, print and close-stdin. If one of those methods is called before .start was called, they throw an exception of type X::Proc::Async::MustBeStarted.

    Proc::Async.new('echo', :w).say(42);
    # dies with    Process must be started first before calling 'say'

# 242.1 Methods

## 242.1.1 method method

    method method(X::Proc::Async::MustBeStarted:D) returns Str:D

Returns the name of the method that was illegally called before starting the external program.

# 243 class X::Proc::Async::OpenForWriting

Error due to writing to a read-only

    class X::Proc::Async::OpenForWriting is Exception { ... }

When a Proc::Async object is opened only for reading from the external program (no :w passed to open), and a write operation such as write, print and say is performed, an exception of type X::Proc::Async::OpenForWriting is thrown:

    my $proc = Proc::Async.new("echo");
    $proc.start;
    $proc.say(42)   # Process must be opened for writing with :w to call 'say'

# 243.1 Methods

## 243.1.1 method method

    method method(X::Proc::Async::OpenForWriting:D:)

Returns the method name that was called and which caused the exception.

# 244 class X::Proc::Async::TapBeforeSpawn

Error due to tapping a Proc::Async stream after spawning its process

    class X::Proc::Async::TapBeforeSpawn is Exception { ... }

If the stdout or stderr methods of Proc::Async are called after the program has been started, an exception of type X::Proc::Async::TapBeforeSpawn is thrown.

    my $proc = Proc::Async.new("echo");
    $proc.start;
    $proc.stdout.tap(&amp;print)        # To avoid data races, you must tap stdout before running the process

# 244.1 Methods

## 244.1.1 method handle

    method handle(X::Proc::Async::TapBeforeSpawn:D:) return Str:D

Returns the name of the handle (stdout or stderr) that was accessed after the program started.

# 245 class X::Promise::CauseOnlyValidOnBroken

Error due to asking why an unbroken promise has been broken.

    class X::Promise::CauseOnlyValidOnBroken is Exception { }

This exception is thrown when code expects a Promise to be broken, and asks why it has been broken, but the Promise has in fact, not yet been broken.

# 245.1 Methods

## 245.1.1 method promise

    method promise()

Returns the Promise that was asked about.

## 245.1.2 method status

    method status()

Returns the status the Promise had at that time.

# 246 class X::Promise::Vowed

Error due to directly trying to keep/break a vowed promise.

    class X::Promise::Vowed is Exception { }

This exception is thrown when code tries to keep/break an already vowed promise without going through the corresponding Vow object.

# 246.1 Methods

## 246.1.1 method promise

    method promise()

Returns the vowed Promise.

# 247 class X::Redeclaration

Compilation error due to declaring an already declared symbol

    class X::Redeclaration does X::Comp { }

Thrown when a symbol (variable, routine, type, parameter, ...) is redeclared. Note that redeclarations are generally fine in an inner scope, but if the redeclaration appears in the same scope as the original declaration, it usually indicates an error and is treated as one.

Examples

    my $x; my $x

    ===SORRY!===
    Redeclaration of symbol $x

    sub f() { }
    sub f() { }
    ===SORRY!===
    Redeclaration of routine f

But those are fine

    my $x;
    sub f() {
        my $x;          # not a redeclaration,
                        # because it's in an inner scope
        sub f() { };    # same
    }

# 247.1 Methods

## 247.1.1 method symbol

Returns the name of the symbol that was redeclared.

## 247.1.2 method what

Returns the kind of symbol that was redeclared. Usually symbol, but can also be routine, type etc.

## 247.1.3 method postfix

Returns a string that is attached to the end of the error message. It usually explains the particular problem in more detail, or suggests way to fix the problem.

# 248 class X::Role::Initialization

Error due to passing an initialization value to an ineligible role

    class X::Role::Initialization is Exception { }

Thrown when the SomeRole($init) syntax is used, but SomeRole does not have exactly one public attribute.

For example role R { }; "D2" but R(2)

throws the error

    Can only supply an initialization value for a role if it has a single
    public attribute, but this is not the case for 'R'

# 248.1 Methods

## 248.1.1 method role

    method role()

Returns the role that caused the error.

# 249 class X::Seq::Consumed

Error due to trying to reuse a consumed sequence

    class X::Seq::Consumed is Exception { }

This exception is thrown when a piece of code tries to reuse a Seq which has already been iterated.

# 250 class X::Sequence::Deduction

Error due to constructing a sequence from ineligible input

    class X::Sequence::Deduction is Exception { }

Exception type thrown when the ... sequence operator is being called without an explicit closure, and the sequence cannot be deduced.

# 251 class X::Signature::NameClash

Compilation error due to two named parameters with the same name

    my class X::Signature::NameClash does X::Comp { }

Compile time error thrown when two named parameters have the same name, potentially through aliases.

For example

    sub f(:$a, :a(:@b)) { }

dies with

    ===SORRY!===
    Name a used for more than one named parameter

# 251.1 Methods

## 251.1.1 method name

    method name() returns Str:D

Returns the name that was used for more than one parameter.

# 252 class X::Signature::Placeholder

Compilation error due to placeholders in a block with a signature

    class X::Signature::Placeholder does X::Comp

Compile time error thrown when a block has both an explicit signature and placeholder parameters.

For example

    sub f() { $^x }

dies with

    ===SORRY!===
    Placeholder variable '$^x' cannot override existing signature

# 252.1 Methods

## 252.1.1 method placeholder

    method placeholder() returns Str:D

Returns the name of a placeholder that was used in a block that already had a signature.

# 253 class X::Str::Numeric

Error while trying to coerce a string to a number

    class X::Str::Numeric is Exception { }

Error thrown (or wrapped in a Failure) when a conversion from string to a number fails.

For example

    say +"42 answers"

dies with

    Cannot convert string to number: trailing characters after number in '42⏏ answers' (indicated by ⏏)

# 253.1 Methods

## 253.1.1 method source

    method source() returns Str:D

Returns the string that was attempted to convert to a number

## 253.1.2 method pos

    method pos() returns Int:D

Gives the position into the string where the parsing failed.

## 253.1.3 method reason

    method reason() returns Int:D

Verbal description of the reason why the conversion failed.

# 254 class X::StubCode

Runtime error due to execution of stub code

    class X::StubCode is Exception { }

Thrown when a piece of stub code (created via !!! or ...) is executed.

# 254.1 Methods

## 254.1.1 method message

Returns the custom message provided to !!!, or a reasonable default if none was provided.

# 255 role X::Syntax

Syntax error thrown by the compiler

    role X::Syntax does X::Comp { }

Common role for syntax errors thrown by the compiler.

# 256 class X::Syntax::Augment::WithoutMonkeyTyping

Compilation error due to augmenting a type without `MONKEY-TYPING`

    class X::Syntax::Augment::WithoutMonkeyTyping does X::Syntax { }

Compile time error thrown when augment is used without use MONKEY-TYPING.

Since augment is considered a rather unsafe and impolite action, you have to pre-declare your intent with the use MONKEY-TYPING; pragma.

If you don't do that, for example

    augment class Int { };

you get the error

    ===SORRY!===
    augment not allowed without 'use MONKEY-TYPING'

# 257 class X::Syntax::Comment::Embedded

Compilation error due to a malformed inline comment

    class X::Syntax::Comment::Embedded does X::Syntax { }

Syntax error thrown when #` is encountered and it is not followed by an opening bracket.

For example

    #`

dies with

    ===SORRY!===
    Opening bracket is required for #` comment

# 258 class X::Syntax::Confused

Compilation error due to unrecognized syntax

    class X::Syntax::Confused does X::Syntax { }

The most general syntax error, if no more specific error message can be given.

For example

    1∞

dies with

    ===SORRY!===
    Confused

# 259 class X::Syntax::InfixInTermPosition

Compilation error due to an infix in term position

    class X::Syntax::InfixInTermPosition does X::Syntax { }

Syntax error thrown when the parser expects a term, but finds an infix operator instead.

For example

    1, => 2

dies with

    ===SORRY!===
    Preceding context expects a term, but found infix => instead

# 259.1 Methods

## 259.1.1 method infix

    method infix() returns Str:D

Returns the symbol of the infix that was found in term position.

# 260 class X::Syntax::Malformed

Compilation error due to a malformed construct (usually a declarator)

    class X::Syntax::Malformed does X::Syntax { ... }

The Perl 6 compiler throws errors of type X::Syntax::Malformed when it knows what kind of declaration it is parsing, and encounters a syntax error, but can't give a more specific error message.

    my Int a;   # throws an X::Syntax::Malformed

produces

    ===SORRY!===
    Malformed my
    at -e:1
    ------> my Int ⏏a

# 260.1 Methods

## 260.1.1 method what

    method what(X::Syntax::Malformed:D:) returns Str:D:

Returns a description of the thing that was being parsed.

# 261 class X::Syntax::Missing

Compilation error due to a missing piece of syntax

    class X::Syntax::Missing does X::Syntax { }

Syntax error thrown when the previous piece of syntax requires the existence of another piece of syntax, and that second piece is missing.

For example

    for 1, 2, 3

dies with

    ===SORRY!===
    Missing block

because a for that is not a statement modifier must be followed by a block.

# 261.1 Methods

## 261.1.1 method what

    method what() returns Str:D

Returns a string description of the missing syntax element.

# 262 class X::Syntax::NegatedPair

Compilation error due to passing an argument to a negated colonpair

    class X::Syntax::NegatedPair does X::Syntax { }

Thrown if a colonpair illegally has a value, for example :!a(1). This is an error because the ! negation implies that the value is False.

A typical error message from this class is Argument not allowed on negated pair with key 'a'.

# 262.1 Methods

## 262.1.1 method key

Returns the key of the pair that caused the error.

# 263 class X::Syntax::NoSelf

Compilation error due to implicitly using a `self` that is not there

    class X::Syntax::NoSelf does X::Syntax { }

Compile time error thrown when $.foo style calls are used where no invocant is available.

For example the code

    $.meth

in the mainline throws the error

    ===SORRY!===
    Variable $.meth used where no 'self' is available

because $.meth is short for $(self.meth), and there is no self available in mainline.

# 263.1 Methods

## 263.1.1 method variable

Returns the variable/method call that caused the error.

# 264 class X::Syntax::Number::RadixOutOfRange

Compilation error due to an unallowed radix in a number literal

    class X::Syntax::Number::RadixOutOfRange does X::Syntax { }

Syntax error that is thrown when the radix of a radix number is not allowed, like :1<1> or :42<ouch> .

# 264.1 Methods

## 264.1.1 method radix

    method radix() returns Int:D

The offensive radix.

# 265 class X::Syntax::P5

Compilation error due to use of Perl 5-only syntax

    class X::Syntax::P5 does X::Syntax { }

Syntax error thrown when some piece of code is clearly Perl 5, not Perl 6.

For example

    for my $a (1, 2) { }

dies with

    ===SORRY!===
    This appears to be Perl 5 code

# 266 class X::Syntax::Regex::Adverb

Compilation error due to an unrecognized regex adverb

    class X::Syntax::Regex::Adverb does X::Syntax { }

Syntax error thrown when an unrecognized or illegal regex adverb is encountered.

For example rx:g/a/ dies with

    ===SORRY!===
    Adverb g not allowed on rx

because :g belongs to a match operation, not a regex itself.

# 266.1 Methods

## 266.1.1 method adverb

    method adverb() returns Str:D

Returns the illegally used adverb

## 266.1.2 method construct

    method construct() returns Str:D

Returns the name of the construct that adverb was used on (m, ms, rx, s, ss).

# 267 class X::Syntax::Regex::SolitaryQuantifier

Compilation error due to a regex quantifier without preceding atom

    class X::Syntax::Regex::SolitaryQuantifier does X::Syntax { }

Syntax error when a stand alone quantifier (without an preceding atom to quantify) is encountered in a regular expression.

For example

    / * /

dies with

    ===SORRY!=== Error while compiling
    Quantifier quantifies nothing

# 268 class X::Syntax::Reserved

Compilation error due to use of syntax reserved for future use

    class X::Syntax::Reserved does X::Syntax { }

Syntax error thrown when a syntax is used which is reserved for future expansion.

For example

    my @a();

dies with

    ===SORRY!===
    The () shape syntax in array declarations is reserved

# 268.1 Methods

## 268.1.1 method reserved

    method reserved() returns Str:D

Returns a text description of the reserved syntax.

## 268.1.2 method instead

    method instead() returns Str

Describes what to use instead of the reserved syntax (if anything).

# 269 class X::Syntax::Self::WithoutObject

Compilation error due to invoking `self` in an ineligible scope

    class X::Syntax::Self::WithoutObject does X::Syntax { }

Syntax error thrown when self is referenced in a place where no invocant is available.

For example

    self

in the mainline dies with

    ===SORRY!===
    'self' used where no object is available

# 270 class X::Syntax::Signature::InvocantMarker

Compilation error due to a misplaced invocant marker in a signature

    class X::Syntax::Signature::InvocantMarker does X::Syntax { }

Syntax error when the invocant in a signature is anywhere else than after the first parameter.

For example

    :($a, $b: $c)

dies with

    ===SORRY!===
    Can only use : as invocant marker in a signature after the first parameter

See also: Signature.

# 271 class X::Syntax::Term::MissingInitializer

Compilation error due to declaring a term without initialization

    class X::Syntax::Term::MissingInitializer does X::Syntax { }

Syntax error when a term (a backslash variable) is declared without initialization assignment.

For example

    my \foo

dies with

    ===SORRY!===
    Term definition requires an initializer

Valid code would be

    my \foo = 42;

# 272 class X::Syntax::UnlessElse

Compilation error due to an `unless` clause followed by `else`

    class X::Syntax::UnlessElse does X::Syntax { }

Syntax error thrown when an unless clause is followed by an else clause.

For example

    unless 1 { } else { }

dies with

    "unless" does not take "else", please rewrite using "if"

# 273 class X::Syntax::Variable::Match

Compilation error due to declaring a match variable

    class X::Syntax::Variable::Match does X::Syntax { }

Syntax error thrown when a match variable like $<thing> was declared.

For example

    my $&lt;thing>;

dies with

    ===SORRY!===
    Cannot declare a match variable

# 274 class X::Syntax::Variable::Numeric

Compilation error due to declaring a numeric symbol

    class X::Syntax::Variable::Numeric does X::Syntax { }

Syntax error thrown when trying to declare numeric symbols.

For example

    my @101;

dies with

    ===SORRY!===
    Cannot declare a numeric variable

# 274.1 Methods

## 274.1.1 method what

    method what returns Str:D

Returns a verbal description of the kind of symbol that was declared (variable, parameter, attribute).

# 275 class X::Syntax::Variable::Twigil

Compilation error due to an unallowed twigil in a declaration

    class X::Syntax::Variable::Twigil does X::Syntax { }

Syntax error thrown when a variable with a twigil is used in an incompatible declaration.

For example

    my $!foo

dies with

    ===SORRY!===
    Cannot use ! twigil on my variable

# 275.1 Methods

## 275.1.1 method twigil

    method twigil() returns Str:D

Returns the twigil that was illegally used

## 275.1.2 method scope

    method scope() returns Str:D

Returns the scope that did not harmonize with the twigil.

# 276 role X::Temporal

Error related to DateTime or Date

    role X::Temporal is Exception { }

A common exception type for all errors related to DateTime or Date.

# 277 class X::Temporal::InvalidFormat

Error due to using an invalid format when creating a DateTime or Date

    class X::Temporal::InvalidFormat does X::Temporal is Exception { }

This exception is thrown when code tries to create a DateTime or Date object using an invalid format.

    my $dt = Date.new("12/25/2015"); # 'invalid Date string '12/25/2015'; use yyyy-mm-dd instead'

# 277.1 Methods

## 277.1.1 method invalid-str

Returns the invalid format string (12/25/2015 in the example above)

## 277.1.2 method target

Returns the target type (Date in the example above)

## 277.1.3 method format

Returns valid format strings for the target type in question, (yyyy-mm-dd in the example above)

# 278 class X::TypeCheck

Error due to a failed type check

    class X::TypeCheck is Exception { }

Error class thrown when a type check fails.

# 278.1 Methods

## 278.1.1 method operation

    method operation() returns Str:D

Returns a string description of the operation that failed, for example "assignment", "binding", "return".

## 278.1.2 method got

    method got()

Returns the object that failed to type check

## 278.1.3 method expected

    method expected()

Returns the type object against which the check failed.

# 279 class X::TypeCheck::Assignment

Error due to a failed type check during assignment

    class X::TypeCheck::Assignment is X::TypeCheck { }

Error class thrown when the type check of an assignment fails.

For example

    my Int $x = "foo"

dies with

    Type check failed in assignment to '$x'; expected 'Int' but got 'Str'

though compilers are allowed to detect obvious cases like this example and complain at compile time with a different error.

# 280 class X::TypeCheck::Binding

Error due to a failed type check during binding

    class X::TypeCheck::Binding is X::TypeCheck { }

Thrown when the type check of a binding operation fails.

For example

    my Int $x := "foo"'

dies with

    Type check failed in binding; expected 'Int' but got 'Str'

Note that the compiler is free to detect obvious errors at compile time, and complain with a different error at compile time.

# 281 class X::TypeCheck::Return

Error due to a failed typecheck during `return`

    class X::TypeCheck::Return is X::TypeCheck { }

Thrown when a return type check fails.

For example

    sub f() returns Int { "foo" }
    f();

Dies with

    Type check failed for return value; expected 'Int' but got 'Str'

# 282 class X::TypeCheck::Splice

Compilation error due to a macro trying to splice a non-AST value

    class X::TypeCheck::Splice is X::TypeCheck does X::Comp { }

Compile time error thrown when a Macro or an unquote/hole in a quasi quote does not return an AST.

For example

    macro a { 'foo' }
    say a

dies with

    ===SORRY!===
    Type check failed in macro application; expected AST but got Str

To fix, instead write

    macro a {
        quasi { 'foo' }
    }
    say a;              # foo

# 282.1 Methods

## 282.1.1 method action

    method action() returns Str:D

Returns a verbal description of the action that triggered the error, "macro application" or "unquote evaluation".

# 283 class X::Undeclared

Compilation error due to an undeclared symbol

    class X::Undeclared does X::Comp

Thrown when the compiler encounters a symbol that has not been declared, but needs to be.

Example

    $x

    ===SORRY!===
    Variable $x is not declared

# 283.1 Methods

## 283.1.1 method symbol

Returns the name of the undeclared symbol

## 283.1.2 method what

Returns the kind of symbol that was not declared (for example variable, type, routine).

Since The symbol wasn't declared, the compiler sometimes has to guess (or rather disambiguate) what kind of symbol it encounter that wasn't declared. For example if you write

    say a

Then the disambiguation defaults to reporting a missing subroutine, even though declaring a constant a = 'a' would also make the error go away.

# 284 class int

Integer (native storage; machine precision)

    class int is Int is repr('P6int') { }

TODO