Skip to content

Instantly share code, notes, and snippets.

@gfldex
Created December 30, 2015 00:34
Show Gist options
  • Save gfldex/6c1f8d975e2514ae4ce0 to your computer and use it in GitHub Desktop.
Save gfldex/6c1f8d975e2514ae4ce0 to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>... <title>Untitled</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <style type="text/css"> body { margin-left: 4em; margin-right: 4em; } div.pod-content { padding-left: 20em; } div.marginale { float: right; margin-right: -4em; width: 18em; font-size: 66%; text-align: left; } h1.title { font-size: 200%; } h1 { font-size: 160%; } h2 { font-size: 140%; } h3 { font-size: 120%; } h4 { font-size: 100%; } h5 { font-size: 100%; } h6 { font-size: 100%; } h7 { font-size: 100%; } pre { padding-left: 2em; } ul.toc { list-style-type: none; padding-left: 0; margin-left: 0 } ul.toc ul { list-style-type: none; } ul.toc ul { margin-left: 0; padding-left: 1em; } ul.toc li { margin-left: 0; padding-left: 0em; } ul.toc li.toc-level-1 { padding-left: 1em; } ul.toc li.toc-level-2 { padding-left: 1em; } ul.toc li.toc-level-3 { padding-left: 1em; } ul.toc li.toc-level-4 { padding-left: 1em; } ul.toc li.toc-level-5 { padding-left: 1em; } ul.toc li.toc-level-6 { padding-left: 1em; } ul.toc li.toc-level-7 { padding-left: 1em; } ul.toc li.toc-level-8 { padding-left: 1em; } ul.toc li.toc-level-9 { padding-left: 1em; } ul.toc li.toc-level-10{ padding-left: 1em; } #toc { width: 20em; margin-left: -22em; float: left; position: fixed; top: 0; overflow: scroll; height: 100%; padding: 0; white-space: nowrap; } </style> <link href="pod-to-bigpage.css" rel="stylesheet" type="text/css" /> </head><body>
<div class="pod-content">
<img style="float: right; margin: 0 0 1em 1em" src="/images/camelia.png" alt="" id="home_logo"/> Welcome to the official documentation of the <a href="https://perl6.org">Perl 6</a> programming language! Besides online browsing and searching, you can also <!-- <a>download</a> an offline HTML or PDF copy, and --> <a href="https://github.com/perl6/doc">contribute</a> by reporting mistakes or sending patches. <hr> <dl> <dt><a href="/language.html">Language Reference & Tutorials</a></dt> <dd> A collection of documents describing, in detail, the various conceptual parts of the language. <!-- If you're new to Perl 6, language>intro is a good place to start. --> </dd> <dt><a href="/type.html">Type Reference</a></dt> <dd> Index of built-in classes and roles. </dd> <dt><a href="/routine.html">Routine Reference</a></dt> <dd> Index of built-in subroutines and methods. </dd> <!-- <dt><a href="/module.html">Module Reference</a></dt> <dd> Index of modules that are part of the official core distribution. </dd> --> </dl> <hr> <p>The Perl 6 homepage offers <a href="https://perl6.org/documentation/">a comprehensive list of Perl 6 documentation</a>, including tutorials, HowTos and <a href="/language/faq">FAQs (Frequently Asked Questions)</a>.</p> <p> You may also be interested in the Perl 6 <a href="https://design.perl6.org">design documents</a>, 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 <a href="http://perl.org/">Perl 5</a> language can be found on the <a href="http://perldoc.perl.org/">Perl 5 documentation website</a>. </p> <a name="t2"><h1 class="title">2 5to6-nutshell</h1></a> <p class="subtitle">Perl 5 to Perl 6, in a nutshell: How do I do what I used to do?</p></a> <p>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 <i>new</i> Perl 6 features and idioms won't be).</p>
<p>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 <a href="">#Automated Translation</a> might be more convenient).</p>
<p>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.</p>
<a name="t2..1"$class><h2>2..1 CPAN</h2></a>
<p>See <a href="">https://modules.perl6.org/</a> .</p>
<p>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.</p>
<p>There are multiple projects aiming to make it possible to <span class="code">use </span> Perl 5 modules directly from Perl 6 code:</p>
<p> <a href="https://github.com/rakudo-p5/v5/">v5</a> 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.</p>
<p> <a href="https://github.com/niner/Inline-Perl5/">Inline::Perl5</a> Uses an embedded instance of the <span class="code">perl </span> interpreter to run Perl 5 code called from your Perl 6 script.</p>
<p>Of these, Inline::Perl5 is currently the furthest along and the most promising.</p>
<a name="t2..2"$class><h2>2..2 Syntax</h2></a>
<a name="t2..2.1"$class><h3>2..2.1 <span class="code">-> </span> Method calls</h3></a>
<p>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:</p>
<pre class="code">$person->name # Perl 5
$person.name # Perl 6</pre>
<p>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 <span class="code">~ </span> operator, if you were wondering.)</p>
<p>To call a method whose name is not known until runtime:</p>
<pre class="code">$object->$methodname(@args); # Perl 5
$object."$methodname"(@args); # Perl 6</pre>
<p>If you leave out the quotes, then Perl 6 expects <span class="code">$methodname </span> to contain a <span class="code">Method </span> object, rather than the simple string name of the method.</p>
<a name="t2..2.2"$class><h3>2..2.2 Whitespace</h3></a>
<p>Perl 5 allows a surprising amount of flexibility in the use of whitespace, even with strict mode and warnings turned on:</p>
<pre class="code"># unidiomatic but valid Perl 5
say"Hello ".ucfirst ($people
[$ i]
->
name)."!"if$greeted[$i]&lt;1;</pre>
<p>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.</p>
<p>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:</p>
<ul><li><p> <i>No space allowed before the opening parenthesis of an argument list.</i> </p>
<pre class="code">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</pre>
</li></ul> <ul><li><p> <i>Space is <b>required</b> immediately after keywords</i> </p>
<pre class="code">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</pre>
</li></ul> <ul><li><p> <i>No space allowed after a prefix operator, or before a postfix/postcircumfix operator (including array/hash subscripts).</i> </p>
<pre class="code">$seen {$_} ++; # Perl 5
%seen{$_}++; # Perl 6</pre>
</li></ul> <ul><li><p> <i>No space allowed around the method call operator.</i> </p>
<pre class="code">$customer -> name; # Perl 5
$customer.name; # Perl 6</pre>
</li></ul> <ul><li><p> <i>Space required before an infix operator if it would conflict with an existing postfix/postcircumfix operator.</i> </p>
<pre class="code">$n&lt;1; # Perl 5 (in Perl 6 this would conflict with postcircumfix &lt; >)
$n &lt; 1; # Perl 6</pre>
</li></ul> <p>However, note that you can use <a href="https://design.perl6.org/S02.html#Unspaces">unspace</a> to add whitespace in Perl 6 code in places where it is otherwise not allowed:</p>
<pre class="code"># 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");</pre>
<p>See also <a href="https://design.perl6.org/S03.html#Minimal_whitespace_DWIMmery">S03#Minimal whitespace DWIMmery</a> and <a href="https://design.perl6.org/S04.html#Statement_parsing">S04#Statement parsing</a> in the Perl 6 design docs.</p>
<a name="t2..2.3"$class><h3>2..2.3 Sigils</h3></a>
<p>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.</p>
<p>(See also <a href="">#Dereferencing</a> ).</p>
<a name="t2..2.3.1"$class><h4>2..2.3.1 <span class="code">$ </span> Scalar</h4></a>
<p>The <span class="code">$ </span> sigil is now always used with "scalar" variables (e.g. <span class="code">$name </span> ), and no longer for <a href="#[]_Array_indexing/slicing">array indexing</a> and <a href="#{}_Hash_indexing/slicing">Hash indexing</a> . That is, you can still use <span class="code">$x[1] </span> and <span class="code">$x{"foo"} </span> , 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"}.</p>
<a name="t2..2.3.2"$class><h4>2..2.3.2 <span class="code">@ </span> Array</h4></a>
<p>The <span class="code">@ </span> sigil is now always used with "array" variables (e.g. <span class="code">@months </span> , <span class="code">@months[2] </span> , <span class="code">@months[2, 4] </span> ), and no longer for <a href="#{}_Hash_indexing/slicing">value-slicing hashes</a> .</p>
<a name="t2..2.3.3"$class><h4>2..2.3.3 <span class="code">% </span> Hash</h4></a>
<p>The <span class="code">% </span> sigil is now always used with "hash" variables (e.g. <span class="code">%calories </span> , <span class="code">%calories&lt;apple> </span> , <span class="code">%calories&lt;pear plum> </span> ), and no longer for <a href="#[]_Array_indexing/slicing">key/value-slicing arrays</a> .</p>
<a name="t2..2.3.4"$class><h4>2..2.3.4 <span class="code">&amp; </span> Sub</h4></a>
<p>The <span class="code">&amp; </span> 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":</p>
<pre class="code">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</pre>
<p>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 <span class="code">undef &amp;foo; </span> , and the closest equivalent to Perl 5's <span class="code">defined &amp;foo </span> would be <span class="code">defined &amp;::("foo") </span> (which uses the "dynamic symbol lookup" syntax). However, you can declare a mutable named subroutine with <span class="code">my &amp;foo; </span> and then change its meaning at runtime by assigning to <span class="code">&amp;foo </span> .</p>
<p>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:</p>
<ul><li><p> <span class="code">&amp;foo(...) </span> <i>for circumventing a function prototype</i> </p>
<p>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:</p>
<pre class="code"># 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;</pre>
</li></ul> <ul><li><p> <span class="code">&amp;foo; </span> <i>and</i> <span class="code">goto &amp;foo; </span> <i>for re-using the caller's argument list / replacing the caller in the call stack</i> </p>
<pre class="code">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.</pre>
</li></ul> <a name="t2..2.3.5"$class><h4>2..2.3.5 <span class="code">* </span> Glob</h4></a>
TODO: Research what exact use-cases still need typeglobs in Perl 5
today, and refactor this section to list them (with translations).
<p>In Perl 5, the <span class="code">* </span> sigil referred to the GLOB structure that Perl uses to store non-lexical variables, file handles, subs, and formats.</p>
<p>(This should not be confused with the Perl 5 built-in <span class="code">glob() </span> function, which reads filenames from a directory).</p>
<p>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.</p>
<pre class="code"># 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);</pre>
<p>You should refactor your Perl 5 code to remove the need for the GLOB, before translating into Perl 6.</p>
<pre class="code"># 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);</pre>
<p>And here's just one possible Perl 6 translation:</p>
<pre class="code"># 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);</pre>
<a name="t2..2.4"$class><h3>2..2.4 [] Array indexing/slicing</h3></a>
<p>Index and slice operations on arrays no longer inflect the variable's <a href="#@_Array">sigil</a> , and adverbs can be used to control the type of slice:</p>
<ul><li><p> <i>Indexing</i> </p>
<pre class="code">say $months[2]; # Perl 5
say @months[2]; # Perl 6 - @ instead of $</pre>
</li></ul> <ul><li><p> <i>Value-slicing</i> </p>
<pre class="code">say join ',', @months[6, 8..11]; # Perl 5 and Perl 6</pre>
</li></ul> <ul><li><p> <i>Key/value-slicing</i> </p>
<pre class="code">say join ',', %months[6, 8..11]; # Perl 5
say join ',', @months[6, 8..11]:kv; # Perl 6 - @ instead of %; use :kv adverb</pre>
</li></ul> <p>Also note that the subscripting brackets are now a normal postcircumfix operator rather than a special syntactic form, and thus <a href="#exists">checking for existence of elements</a> and <a href="#delete">unsetting elements</a> is done with adverbs.</p>
<a name="t2..2.5"$class><h3>2..2.5 {} Hash indexing/slicing</h3></a>
<p>Index and slice operations on hashes no longer inflect the variable's <a href="#%_Hash">sigil</a> , 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 <span class="code">qw// </span> quoting construct):</p>
<ul><li><p> <i>Indexing</i> </p>
<pre class="code">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</pre>
</li></ul> <ul><li><p> <i>Value-slicing</i> </p>
<pre class="code">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</pre>
</li></ul> <ul><li><p> <i>Key/value-slicing</i> </p>
<pre class="code">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)</pre>
</li></ul> <p>Also note that the subscripting curly braces are now a normal postcircumfix operator rather than a special syntactic form, and thus <a href="#exists">checking for existence of keys</a> and <a href="#delete">removing keys</a> is done with adverbs.</p>
<a name="t2..2.6"$class><h3>2..2.6 Reference creation</h3></a>
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.
<p>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 <span class="code">\ </span> operator.</p>
<p>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 <span class="code">&amp; </span> sigil. References to existing named variables are generated by <span class="code">item </span> context.</p>
<pre class="code">my $aref = [ 1, 2, 9 ]; # Both Perl 5&amp;6
my $href = { A => 98, Q => 99 }; # Both Perl 5&amp;6
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</pre>
<a name="t2..2.7"$class><h3>2..2.7 Dereferencing</h3></a>
<p>In Perl 5, the syntax for dereferencing an entire reference is the type-sigil and curly braces, with the reference inside the curly braces.</p>
<p>In Perl 6, the curly braces are changed to parentheses.</p>
<pre class="code"># 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 );</pre>
<p>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.</p>
<p>In Perl 5, the arrow operator, <span class="code">-> </span> , 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 <span class="code">. </span> for those tasks.</p>
<pre class="code"># 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);</pre>
<p>In recent versions of Perl 5 (5.20 and later), a new feature allows the use of the arrow op for dereferencing. See <a href="">http://search.cpan.org/~shay/perl-5.20.1/pod/perl5200delta.pod#Experimental_Postfix_Dereferencing</a> That new feature corresponds Perl 6 <span class="code">.list </span> and <span class="code">.hash </span> methods:</p>
<pre class="code"># 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];</pre>
<p>The "Zen" slice does the same thing:</p>
<pre class="code"># Perl 6
my @a = $arrayref[];
my %h = $hashref{};</pre>
<p>See S32/Containers</p>
<a name="t2..3"$class><h2>2..3 Operators</h2></a>
<p>See S03-operators for full details on all operators.</p>
<p>Unchanged:</p>
<ul><li><p> <span class="code">, </span> List Separator</p>
</li></ul> <ul><li><p> <span class="code">+ </span> Numeric Addition</p>
</li></ul> <ul><li><p> <span class="code">- </span> Numeric Subtraction</p>
</li></ul> <ul><li><p> <span class="code">* </span> Numeric Multiplication</p>
</li></ul> <ul><li><p> <span class="code">/ </span> Numeric Division</p>
</li></ul> <ul><li><p> <span class="code">% </span> Numeric Modulus</p>
</li></ul> <ul><li><p> <span class="code">** </span> Numeric Exponentiation</p>
</li></ul> <ul><li><p> <span class="code">++ </span> Numeric Increment</p>
</li></ul> <ul><li><p> <span class="code">-- </span> Numeric Decrement</p>
</li></ul> <ul><li><p> <span class="code">! &amp;&amp; || ^ </span> Booleans, high-precedence</p>
</li></ul> <ul><li><p> <span class="code">not and or xor </span> Booleans, low-precedence</p>
</li></ul> <ul><li><p> <span class="code">== != &lt; > &lt;= >= </span> Numeric comparisons</p>
</li></ul> <ul><li><p> <span class="code">eq ne lt gt le ge </span> String comparisons</p>
</li></ul> <a name="t2..3.1"$class><h3>2..3.1 <span class="code">&lt;=> cmp </span> Three-way comparisons</h3></a>
<p>In Perl 5, these operators returned -1, 0, or 1. In Perl 6, they return <span class="code">Order::Less </span> , <span class="code">Order::Same </span> , or <span class="code">Order::More </span> .</p>
<p> <span class="code">cmp </span> is now named <span class="code">leg </span> ; it forces string context for the comparison.</p>
<p> <span class="code">&lt;=> </span> still forces numeric context.</p>
<p> <span class="code">cmp </span> in Perl 6 does either <span class="code">&lt;=> </span> or <span class="code">leg </span> , depending on the existing type of its arguments.</p>
<a name="t2..3.2"$class><h3>2..3.2 <span class="code">~~ </span> Smart-match operator</h3></a>
<p>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 <a href="https://design.perl6.org/S03.html#Smart_matching">S03/Smart matching</a> </p>
<a name="t2..3.3"$class><h3>2..3.3 <span class="code">&amp; | ^ </span> String Bitwise ops</h3></a>
<a name="t2..3.4"$class><h3>2..3.4 <span class="code">&amp; | ^ </span> Numeric Bitwise ops</h3></a>
<a name="t2..3.5"$class><h3>2..3.5 <span class="code">&amp; | ^ </span> Boolean ops</h3></a>
<p>In Perl 5, <span class="code">&amp; | ^ </span> were invoked according to the contents of its arguments. For example, <span class="code">31 | 33 </span> returns a different result than <span class="code">"31" | "33" </span> .</p>
<p>In Perl 6, those single-character ops have been removed, and replaced by two-character ops which coerce their arguments to the needed context.</p>
<pre class="code"># 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)</pre>
<a name="t2..3.6"$class><h3>2..3.6 <span class="code">&lt;&lt; >> </span> Numeric shift left|right ops</h3></a>
<p>Replaced by <span class="code">+&lt; </span> and <span class="code">+> </span> .</p>
<pre class="code">say 42 &lt;&lt; 3; # Perl 5
say 42 +&lt; 3; # Perl 6</pre>
<a name="t2..3.7"$class><h3>2..3.7 <span class="code">=> </span> Fat comma</h3></a>
<p>In Perl 5, <span class="code">=> </span> acted just like a comma, but also quoted its left-hand side.</p>
<p>In Perl 6, <span class="code">=> </span> is the Pair operator, which is quite different in principle, but works the same in many situations.</p>
<p>If you were using <span class="code">=> </span> in hash initialization, or in passing arguments to a sub that expects a hashref, then the usage is likely identical.</p>
<pre class="code"># 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</pre>
<p>If you were using <span class="code">=> </span> 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 <span class="code">=> </span> 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.</p>
<pre class="code"># 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</pre>
<a name="t2..3.8"$class><h3>2..3.8 <span class="code">? : </span> Ternary operator</h3></a>
<p>Now spelled with two question marks instead of one question mark, and two exclamation points instead of one colon.</p>
<pre class="code">my $result = ( $score > 60 ) ? 'Pass' : 'Fail'; # Perl 5
my $result = ( $score > 60 ) ?? 'Pass' !! 'Fail'; # Perl 6</pre>
<a name="t2..3.9"$class><h3>2..3.9 <span class="code">. </span> (Dot op) Concatenation</h3></a>
<p>Replaced by the tilde.</p>
<p>Mnemonic: think of "stitching" together the two strings with needle and thread.</p>
<pre class="code">$food = 'grape' . 'fruit'; # Perl 5
$food = 'grape' ~ 'fruit'; # Perl 6</pre>
<a name="t2..3.10"$class><h3>2..3.10 <span class="code">x </span> List Repeat op or String Repeat op</h3></a>
<p>In Perl 5, <span class="code">x </span> was the Repetition operator.</p>
<p>In scalar context, <span class="code">x </span> would repeat a string. In Perl 6, <span class="code">x </span> repeats strings in any context.</p>
<p>In list context, <span class="code">x </span> would repeat a list—but only if the left argument is parenthesized! In Perl 6, the new <span class="code">xx </span> op repeats lists in any context.</p>
<p>Mnemonic: x is short and xx is long, so xx is the one used for lists.</p>
<pre class="code"># 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</pre>
<a name="t2..3.11"$class><h3>2..3.11 <span class="code">.. </span> <span class="code">... </span> Two Dots or Three Dots, Range op or Flipflop op</h3></a>
<p>In Perl 5, <span class="code">.. </span> was one of two completely different operators, depending on context.</p>
<p>In list context, <span class="code">.. </span> is the familiar range operator. Range has many new wrinkles in Perl 6, but ranges from Perl 5 code should not <b>require</b> translation.</p>
<p>In scalar context, <span class="code">.. </span> and <span class="code">... </span> were the little-known Flipflop operators. They have been replaced by <span class="code">ff </span> and <span class="code">fff </span> .</p>
<a name="t2..3.12"$class><h3>2..3.12 String interpolation</h3></a>
<p>In Perl 5, <span class="code">"${foo}s" </span> deliminates a variable name from regular text next to it. In Perl 6, simply extend the curly braces to include the sigil too: <span class="code">"{$foo}s" </span> </p>
<a name="t2..4"$class><h2>2..4 Compound Statements</h2></a>
<a name="t2..4.1"$class><h3>2..4.1 Conditionals</h3></a>
<a name="t2..4.1.1"$class><h4>2..4.1.1 <span class="code">if </span> <span class="code">elsif </span> <span class="code">else </span> <span class="code">unless </span> </h4></a>
<p>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:</p>
<pre class="code">if (my $x = dostuff()) {...} # Perl 5
if dostuff() -> $x {...} # Perl 6</pre>
<p>(You can still use the <span class="code">my </span> form in Perl 6, but it will scope to the outer block, not the inner.)</p>
<p>The <span class="code">unless </span> conditional only allows for a single block in Perl 6; it does not allow for an <span class="code">elsif </span> or <span class="code">else </span> clause.</p>
<a name="t2..4.1.2"$class><h4>2..4.1.2 <span class="code">given </span> - <span class="code">when </span> </h4></a>
<p>The <span class="code">given </span> - <span class="code">when </span> construct is like a chain of <span class="code">if </span> - <span class="code">elsif </span> - <span class="code">else </span> statements or like the <span class="code">switch </span> - <span class="code">case </span> construct in e.g. C. It has the general structure:</p>
<pre class="code">given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}</pre>
<p>In its simplest form, the construct is as follows:</p>
<pre class="code">given $value {
when "a match" {
do-something();
}
when "another match" {
do-something-else();
}
default {
do-default-thing();
}
}</pre>
<p>This is simple in the sense that a scalar value is matched in the <span class="code">when </span> 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.</p>
<p>See also the warnings on the smart-match op above.</p>
<a name="t2..4.2"$class><h3>2..4.2 Loops</h3></a>
<a name="t2..4.2.1"$class><h4>2..4.2.1 <span class="code">while </span> <span class="code">until </span> </h4></a>
<p>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:</p>
<pre class="code">while (my $x = dostuff()) {...} # Perl 5
while dostuff() -> $x {...} # Perl 6</pre>
<p>(You can still use the <span class="code">my </span> form in Perl 6, but it will scope to the outer block, not the inner.)</p>
<p>Note that reading line-by-line from a filehandle has changed.</p>
<p>In Perl 5, it was done in a <span class="code">while </span> loop using the diamond operator. Using <span class="code">for </span> instead of <span class="code">while </span> was a common bug, because the <span class="code">for </span> causes the whole file to be sucked in at once, swamping the program's memory usage.</p>
<p>In Perl 6, <span class="code">for </span> statement is <b>lazy</b> , so we read line-by-line in a <span class="code">for </span> loop using the <span class="code">.lines </span> method.</p>
<pre class="code">while (&lt;IN_FH>) { } # Perl 5
for $IN_FH.lines { } # Perl 6</pre>
<a name="t2..4.2.2"$class><h4>2..4.2.2 <span class="code">for </span> <span class="code">foreach </span> </h4></a>
<p>Note first this common misunderstanding about the <span class="code">for </span> and <span class="code">foreach </span> keywords. Many programmers think that they distinguish between the C-style three-expression form and the list-iterator form; they do not! In fact, they keywords are interchangeable; the Perl 5 compiler looks for the semi-colons within the parens to determine which type of loop to parse.</p>
<p>The C-style three-factor form now uses the <span class="code">loop </span> keyword, and is otherwise unchanged. The parens *are* still required.</p>
<pre class="code">for ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 5
loop ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 6</pre>
<p>The loop-iterator form of <span class="code">for </span> or <span class="code">foreach </span> is named <span class="code">for </span> in Perl 6. <span class="code">foreach </span> is no longer a keyword. Parens are optional.</p>
<p>The iteration variable, if any, has been moved from before the list, to after the list and an added arrow operator.</p>
<p>The iteration variable is now always lexical; <span class="code">my </span> is neither needed nor allowed.</p>
<p>In Perl 5, the iteration variable is a read-write alias to the current list element.</p>
<p>In Perl 6, that alias is read-only (for safety), unless you change <span class="code">-> </span> to <span class="code">&lt;-> </span> . When translating, inspect the use of the loop variable to decide if read-write is needed.</p>
<pre class="code">for my $car (@cars) {...} # Perl 5; read-write
for @cars -> $car {...} # Perl 6; read-only
for @cars &lt;-> $car {...} # Perl 6; read-write</pre>
<p>If the default topic <span class="code">$_ </span> is being used, but needs to be read-write, then just use <span class="code">&lt;-> </span> and explicitly specify <span class="code">$_ </span> .</p>
<pre class="code">for (@cars) {...} # Perl 5; default topic
for @cars {...} # Perl 6; $_ is read-only
for @cars &lt;-> $_ {...} # Perl 6; $_ is read-write</pre>
<a name="t2..4.3"$class><h3>2..4.3 Flow Control statements</h3></a>
<p>Unchanged:</p>
<ul><li><p> <span class="code">next </span> </p>
</li></ul> <ul><li><p> <span class="code">last </span> </p>
</li></ul> <ul><li><p> <span class="code">redo </span> </p>
</li></ul> <a name="t2..4.3.1"$class><h4>2..4.3.1 <span class="code">continue </span> </h4></a>
<p>There is no longer a <span class="code">continue </span> block. Instead, use a <span class="code">NEXT </span> block within the body of the loop.</p>
<pre class="code"># 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 ~= ':'
}
}</pre>
<a name="t2..5"$class><h2>2..5 Functions</h2></a>
NOTE FOR EDITORS: When adding functions, please place them in
alphabetical order.
<a name="t2..5.1"$class><h3>2..5.1 Built-ins with bare blocks</h3></a>
<p>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. <span class="code">map </span> , <span class="code">grep </span> , etc.</p>
<pre class="code">my @results = grep { $_ eq "bars" } @foo; # Perl 5
my @results = grep { $_ eq "bars" }, @foo; # Perl 6</pre>
<a name="t2..5.2"$class><h3>2..5.2 <span class="code">delete </span> </h3></a>
<p>Turned into an adverb of the <a href="#{}_Hash_indexing/slicing"> <span class="code">{} </span> hash subscripting</a> and <a href="#[]_Array_indexing/slicing"> <span class="code">[] </span> array subscripting</a> operators.</p>
<pre class="code">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</pre>
<a name="t2..5.3"$class><h3>2..5.3 <span class="code">exists </span> </h3></a>
<p>Turned into an adverb of the <a href="#{}_Hash_indexing/slicing"> <span class="code">{} </span> hash subscripting</a> and <a href="#[]_Array_indexing/slicing"> <span class="code">[] </span> array subscripting</a> operators.</p>
<pre class="code">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</pre>
<a name="t2..6"$class><h2>2..6 Regular Expressions ( Regex / Regexp )</h2></a>
<a name="t2..6.1"$class><h3>2..6.1 Change <span class="code">=~ </span> and <span class="code">!~ </span> to <span class="code">~~ </span> and <span class="code">!~~ </span> .</h3></a>
<p>In Perl 5, matches and substitutions are done against a variable using the <span class="code">=~ </span> regexp-binding op.</p>
<p>In Perl 6, the <span class="code">~~ </span> smartmatch op is used instead.</p>
<pre class="code">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</pre>
<p>Alternately, the new <span class="code">.match </span> and <span class="code">.subst </span> methods can be used. Note that <span class="code">.subst </span> is non-mutating. See <a href="https://design.perl6.org/S05.html#Substitution">S05/Substitution</a> .</p>
<a name="t2..6.2"$class><h3>2..6.2 Move modifiers</h3></a>
<p>Move any modifiers from the end of the regex to the beginning. This may require you to add the optional <span class="code">m </span> on a plain match like <span class="code">/abc/ </span> .</p>
<pre class="code">next if $line =~ /static/i ; # Perl 5
next if $line ~~ m:i/static/ ; # Perl 6</pre>
<a name="t2..6.3"$class><h3>2..6.3 Add :P5 or :Perl5 adverb</h3></a>
<p>If the actual regex is complex, you may want to use it as-is, by adding the <span class="code">P5 </span> modifier.</p>
<pre class="code">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</pre>
<a name="t2..6.4"$class><h3>2..6.4 Special matchers generally fall under the &lt;> syntax</h3></a>
<p>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 <span class="code">() </span> , the assertions will be surrounded by <span class="code">&lt;> </span> .</p>
<p>For character classes, this means that:</p>
<ul><li><p> <span class="code">[abc] </span> becomes <span class="code">&lt;[abc]> </span> </p>
</li></ul> <ul><li><p> <span class="code">[^abc] </span> becomes <span class="code">&lt;-[abc]> </span> </p>
</li></ul> <ul><li><p> <span class="code">[a-zA-Z] </span> becomes <span class="code">&lt;[a..zA..Z]> </span> </p>
</li></ul> <ul><li><p> <span class="code">[[:upper:]] </span> becomes <span class="code">&lt;:Upper> </span> </p>
</li></ul> <ul><li><p> <span class="code">[abc[:upper:]] </span> becomes <span class="code">&lt;[abc]+:Upper> </span> </p>
</li></ul> <p>For look-around assertions:</p>
<ul><li><p> <span class="code">(?=[abc]) </span> becomes <span class="code">&lt;?[abc]> </span> </p>
</li></ul> <ul><li><p> <span class="code">(?=ar?bitrary* pattern) </span> becomes <span class="code">&lt;before ar?bitrary* pattern> </span> </p>
</li></ul> <ul><li><p> <span class="code">(?!=[abc]) </span> becomes <span class="code">&lt;![abc]> </span> </p>
</li></ul> <ul><li><p> <span class="code">(?!=ar?bitrary* pattern) </span> becomes <span class="code">&lt;!before ar?bitrary* pattern> </span> </p>
</li></ul> <ul><li><p> <span class="code">(?&lt;=ar?bitrary* pattern) </span> becomes <span class="code">&lt;after ar?bitrary* pattern> </span> </p>
</li></ul> <ul><li><p> <span class="code">(?&lt;!ar?bitrary* pattern) </span> becomes <span class="code">&lt;!after ar?bitrary* pattern> </span> </p>
</li></ul> <p>(Unrelated to &lt;> syntax, the "lookaround" <span class="code">/foo\Kbar/ </span> becomes <span class="code">/foo &lt;( bar )> / </span> </p>
<ul><li><p> <span class="code">(?(?{condition))yes-pattern|no-pattern) </span> becomes <span class="code">[ &lt;?{condition}> yes-pattern | no-pattern ] </span> </p>
</li></ul> <a name="t2..6.5"$class><h3>2..6.5 Longest token matching (LTM) displaces alternation</h3></a>
<p>In Perl 6 regexen, <span class="code">| </span> does LTM, which decides which alternation wins an ambiguous match based off of a set of rules, rather than about which was written first.</p>
<p>The simplest way to deal with this is just to change any <span class="code">| </span> in your Perl 5 regex to a <span class="code">|| </span> .</p>
<p>TODO more rules. Use <a href="https://github.com/Util/Blue_Tiger/ "> <span class="code">translate_regex.pl </span> from Blue Tiger</a> in the meantime.</p>
<a name="t2..7"$class><h2>2..7 Pragmas</h2></a>
<a name="t2..7.5.1"$class><h4>2..7.5.1 <span class="code">strict </span> </h4></a>
<p>Strict mode is now on by default.</p>
<a name="t2..7.5.2"$class><h4>2..7.5.2 <span class="code">warnings </span> </h4></a>
<p>Warnings are now on by default.</p>
<p>(XXX <span class="code">no warnings </span> will work someday, but NYI?)</p>
<a name="t2..7.5.3"$class><h4>2..7.5.3 <span class="code">autodie </span> </h4></a>
<p>The functions which were altered by <span class="code">autodie </span> to throw exceptions on error, now throw exceptions by default unless you test the return value explicitly.</p>
<pre class="code"># 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</pre>
<a name="t2..7.5.4"$class><h4>2..7.5.4 <span class="code">base </span> </h4></a>
<a name="t2..7.5.5"$class><h4>2..7.5.5 <span class="code">parent </span> </h4></a>
<p>Both <span class="code">use base </span> and <span class="code">use parent </span> have been replaced in Perl 6 by the <span class="code">is </span> keyword, in the class declaration.</p>
<pre class="code"># Perl 5
package Cat;
use base qw(Animal);
# Perl 6
class Cat is Animal;</pre>
<a name="t2..7.5.6"$class><h4>2..7.5.6 <span class="code">bigint </span> <span class="code">bignum </span> <span class="code">bigrat </span> </h4></a>
<p>No longer relevant.</p>
<p> <span class="code">Int </span> is now arbitrary precision, as is the numerator of <span class="code">Rat </span> (the denominator is limited to <span class="code">2**64 </span> , after which it will automatically upgrade to <span class="code">Num </span> to preserve performance). If you want a <span class="code">Rat </span> with an arbitrary-precision denominator, <span class="code">FatRat </span> is available.</p>
<a name="t2..7.5.7"$class><h4>2..7.5.7 <span class="code">constant </span> </h4></a>
<p>In Perl 6, <span class="code">constant </span> is a declarator for variables, just like <span class="code">my </span> , except the variable is permanently locked to the result of its initialization expression (evaluated at compile time).</p>
<p>So, change the <span class="code">=> </span> to <span class="code">= </span> , and add a sigil.</p>
<pre class="code">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</pre>
<p>encoding - allows you to write your script in non-ascii or non-utf8 integer - Perl pragma to use integer arithmetic instead of floating point lib - manipulate @INC at compile time</p>
<a name="t2..7.5.8"$class><h4>2..7.5.8 <span class="code">mro </span> </h4></a>
<p>No longer relevant.</p>
<p>In Perl 6, method calls now always use the C3 method resolution order.</p>
<a name="t2..7.5.9"$class><h4>2..7.5.9 <span class="code">utf8 </span> </h4></a>
<p>No longer relevant.</p>
<p>In Perl 6, source code is expected to be in utf8 encoding.</p>
<a name="t2..7.5.10"$class><h4>2..7.5.10 <span class="code">vars </span> </h4></a>
<p>Discouraged in Perl 5. See <a href="">http://perldoc.perl.org/vars.html</a> .</p>
<p>You should refactor your Perl 5 code to remove the need for <span class="code">use vars </span> , before translating into Perl 6.</p>
<a name="t2..8"$class><h2>2..8 Command-line flags</h2></a>
<p>See <a href="https://design.perl6.org/S19.html#Command_Line_Elements">S19/commandline</a> </p>
<p>Unchanged:</p>
<p>-c -e -h -I -n -p -S -T -v -V</p>
<a name="t2..8.5.1"$class><h4>2..8.5.1 <span class="code">-a </span> </h4></a>
<p>Unchanged in the Spec, but not yet implemented in Rakudo.</p>
<p>For now, change your code to use <span class="code">.split </span> manually.</p>
<a name="t2..8.5.2"$class><h4>2..8.5.2 <span class="code">-F </span> </h4></a>
<p>Unchanged in the Spec, but not yet implemented in Rakudo.</p>
<p>For now, change your code to use <span class="code">.split </span> manually.</p>
<a name="t2..8.5.3"$class><h4>2..8.5.3 <span class="code">-l </span> </h4></a>
<p>This is now the default behavior.</p>
<a name="t2..8.5.4"$class><h4>2..8.5.4 <span class="code">-M </span> <span class="code">-m </span> </h4></a>
<p>Only <span class="code">-M </span> remains. And, as you can no longer use the "no Module" syntax, the use of <span class="code">- </span> with <span class="code">-M </span> to "no" a module is no longer available.</p>
<a name="t2..8.5.5"$class><h4>2..8.5.5 <span class="code">-E </span> </h4></a>
<p>Since all features are already enabled, just use lowercase <span class="code">-e </span> .</p>
<a name="t2..8.5.6"$class><h4>2..8.5.6 <span class="code">-d </span> , <span class="code">-dt </span> , <span class="code">-d:foo </span> , <span class="code">-D </span> , etc.</h4></a>
<p>Replaced with the <span class="code">++BUG </span> metasyntactic option.</p>
<a name="t2..8.5.7"$class><h4>2..8.5.7 -s</h4></a>
<p>Switch parsing is now done by the parameter list of the <span class="code">MAIN </span> subroutine.</p>
<pre class="code"># 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</pre>
<ul><li><p> <span class="code">-t </span> </p>
</li></ul> <p>Taint warnings are not yet specified.</p>
<ul><li><p> <span class="code">-P </span> <span class="code">-u </span> <span class="code">-U </span> <span class="code">-W </span> <span class="code">-X </span> </p>
</li></ul> <p>Removed. See S19.</p>
<ul><li><p> <span class="code">-w </span> </p>
</li></ul> <p>This is now the default behavior.</p>
<a name="t2..9"$class><h2>2..9 File-related operations</h2></a>
<a name="t2..9.1"$class><h3>2..9.1 Reading the lines of a text file into an array</h3></a>
<p>In Perl 5, a common idiom for reading the lines of a text file goes something like this:</p>
<pre class="code">open my $fh, "&lt;", "file" or die "$!";
my @lines = &lt;$fh>;
close $fh;</pre>
<p>In Perl 6, this has been simplified to</p>
<pre class="code">my @lines = "file".IO.lines;</pre>
<p>Do <i>not</i> 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.:</p>
<pre class="code"># 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</pre>
<a name="t2..10"$class><h2>2..10 Environment variables</h2></a>
<a name="t2..10.1"$class><h3>2..10.1 Perl module library path</h3></a>
<p>In Perl5 one of the environment variables to specify extra search paths for Perl modules is <span class="code">PERL5LIB </span> .</p>
<pre class="code">$ PERL5LIB="/some/module/lib" perl program.pl</pre>
<p>In Perl 6 this is similar, one merely needs to change a number! As you probably guessed, you just need to use <span class="code">PERL6LIB </span> :</p>
<pre class="code">$ PERL6LIB="/some/module/lib" perl6 program.p6</pre>
<p>As with Perl5, if you don't specify <span class="code">PERL6LIB </span> , you need to specify the library path within the program via the <span class="code">use lib </span> pragma:</p>
<pre class="code">use lib '/some/module/lib'</pre>
<p>Note that <span class="code">PERL6LIB </span> is more of a developer convenience in Perl 6 (as opposed to the equivalent usage of <span class="code">PERL5LIB </span> 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.</p>
<a name="t2..11"$class><h2>2..11 Misc.</h2></a>
<a name="t2..11.1"$class><h3>2..11.1 <span class="code">dump </span> </h3></a>
<p>Gone.</p>
<p>The Perl 6 design allows for automatic transparent saving-and-loading of compiled bytecode.</p>
<p>Rakudo supports this only for modules so far.</p>
<a name="t2..11.2"$class><h3>2..11.2 Importing specific functions from a module</h3></a>
<p>In Perl 5 it is possible to selectively import functions from a given module like so:</p>
<pre class="code">use ModuleName qw{foo bar baz};</pre>
<p>In Perl 6 one specifies the functions which are to be exported by using the <span class="code">is export </span> role on the relevant subs and <i>all</i> subs with this role are then exported. Hence, the following module <span class="code">Bar </span> exports the subs <span class="code">foo </span> and <span class="code">bar </span> but not <span class="code">baz </span> :</p>
<pre class="code">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" }</pre>
<p>To use this module, simply <span class="code">use Bar </span> and the functions <span class="code">foo </span> and <span class="code">bar </span> will be available</p>
<pre class="code">use Bar;
foo(1); #=> "foo 1"
bar(2); #=> "bar 2"</pre>
<p>If one tries to use <span class="code">baz </span> an "Undeclared routine" error is raised at compile time.</p>
<p>So, how does one recreate the Perl 5 behaviour of being able to selectively import functions? For this one needs to define an <span class="code">EXPORT </span> sub inside the module which specifies the functions to be exported and (in the current implementation of Rakudo (2015.03)) remove the <span class="code">module Bar </span> statement. (Please note that not having the <span class="code">module </span> statement isn't consistent with Synopsis 11, however it works.)</p>
<p>The module <span class="code">Bar </span> now is merely a file called <span class="code">Bar.pm </span> with the following contents:</p>
<pre class="code">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" }</pre>
<p>Note that the subs are no longer explicitly exported via the <span class="code">is export </span> role. We are defining an <span class="code">EXPORT </span> 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 <span class="code">@import-list </span> is set by the <span class="code">use </span> statement in the calling code thus allowing us to selectively import the subs made available by the module.</p>
<p>So, to import only the <span class="code">foo </span> routine, we do the following in the calling code:</p>
<pre class="code">use Bar &lt;foo>;
foo(1); #=> "foo 1"</pre>
<p>Here we see that even though <span class="code">bar </span> 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:</p>
<pre class="code">use Bar &lt;foo>;
foo(1);
bar(5); #!> "Undeclared routine: bar used at line 3"</pre>
<p>however, this will work</p>
<pre class="code">use Bar &lt;foo bar>;
foo(1); #=> "foo 1"
bar(5); #=> "bar 5"</pre>
<p>Note also that <span class="code">baz </span> remains unimportable even if specified in the <span class="code">use </span> statement:</p>
<pre class="code">use Bar &lt;foo bar baz>;
baz(3); #!> "Undeclared routine: baz used at line 2"</pre>
<p>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 <span class="code">is export </span> role, Perl 6 automatically creates the <span class="code">EXPORT </span> sub in the correct manner for you, so one should consider very carefully whether or not writing one's own <span class="code">EXPORT </span> routine is worthwhile.</p>
<a name="t2..12"$class><h2>2..12 Core modules</h2></a>
<a name="t2..12.2.1"$class><h4>2..12.2.1 <span class="code">Data::Dumper </span> </h4></a>
<p>In Perl 5, the <a href="https://metacpan.org/pod/Data::Dumper">Data::Dumper</a> module was used for serialization, and for debugging views of program data structures by the programmer.</p>
<p>In Perl 6, these tasks are accomplished with the <span class="code">.perl </span> method, which every object has.</p>
<pre class="code"># 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.</pre>
<p>In Perl 5, Data::Dumper has a more complex optional calling convention, which allows for naming the VARs.</p>
<p>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.</p>
<pre class="code"># 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!"]]</pre>
<a name="t2..12.2.2"$class><h4>2..12.2.2 <span class="code">Getopt::Long </span> </h4></a>
<p>Switch parsing is now done by the parameter list of the <span class="code">MAIN </span> subroutine.</p>
<pre class="code"># 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]</pre>
<p>Note that Perl 6 auto-generates a full usage message on error in command-line parsing.</p>
<a name="t2..13"$class><h2>2..13 Automated Translation</h2></a>
<p>A quick way to find the Perl 6 version of a Perl 5 construct, is to run it through an automated translator.</p>
<p> <b>NOTE:</b> None of these translators are yet complete.</p>
<a name="t2..13.1"$class><h3>2..13.1 Blue Tiger</h3></a>
<p>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.</p>
<p> <a href="">https://github.com/Util/Blue_Tiger/</a> </p>
<a name="t2..13.2"$class><h3>2..13.2 Perlito</h3></a>
<p>Online Translator!</p>
<p>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.</p>
<p> <a href="">http://www.perlito.org/perlito/perlito5to6.html</a> </p>
<a name="t2..13.3"$class><h3>2..13.3 MAD</h3></a>
<p>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.</p>
<p>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.</p>
<p>Please consult #perl6 to find out the best release of Perl 5 to use for your MAD science experiments.</p>
<a name="t2..13.4"$class><h3>2..13.4 Perl-ToPerl6</h3></a>
<p>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.</p>
<a name="t2..14"$class><h2>2..14 Other sources of translation knowledge</h2></a>
<ul><li><p> <a href="">https://perlgeek.de/en/article/5-to-6</a> </p>
</li></ul> <ul><li><p> <a href="">https://github.com/Util/Blue_Tiger/</a> </p>
</li></ul> <ul><li><p> <a href="">https://perl6advent.wordpress.com/2011/12/23/day-23-idiomatic-perl-6/</a> </p>
</li></ul> <ul><li><p> <a href="">http://www.perlfoundation.org/perl6/index.cgi?perl_6_delta_tablet</a> </p>
</li></ul> <p>### Guidelines for contributions:</p>
<p>Headers should contain the text that a Perl 5 user might search for, since those headings will be in the Table of Contents generated for the top of the document.</p>
<p>We use POD =item instead of =head3 or =head4 for unchanged bits that need not appear in the TOC.</p>
<p>This article does not describe the additions to syntax, nor details of possible improvements. For example, <span class="code">0 + $string </span> still works, even though we would write it as <span class="code">+$string </span> now. (Blue Tiger will offer a Perl Modernization guide, with step-by-step procedures for translation, along with details of new idioms and "better ways to do it")</p>
<p>Example code and links to other documents should be favored over long explanations of details better found elsewhere.</p>
<p>Finally, if a real user asks a P5->P6 question not answered here, please add it to the document, even if we don't have a good answer yet. That will be better than losing the information about a real need.</p>
<a name="t3"><h1 class="title">3 5to6-perlfunc</h1></a> <p class="subtitle">Perl 5 to Perl 6 guide - functions</p></a> <a name="t3.1"$class><h1>3.1 DESCRIPTION</h1></a>
<p>A (hopefully) comprehensive list of Perl 5 builtin functions with their Perl 6 equivalents with notes on variations between them where necessary.</p>
<a name="t3.2"$class><h1>3.2 NOTE</h1></a>
<p>I will <i>not</i> 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.</p>
<p>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 <span class="code">function(@args) </span> are now also method calls of the form <span class="code">@args.function </span> (In rare cases, there is <i>only</i> a method call). This should be obvious in the following text, but it probably behooves you to get into that frame of mind now.</p>
<p>Also, unless otherwise stated, the use of the term "function" here will mean a function in the style of <span class="code">func(@args) </span> , while "method" will refer to a function in the style of <span class="code">@args.func </span> .</p>
<a name="t3.3"$class><h1>3.3 SOURCES</h1></a>
<p>I'm taking my information from <a href="">https://doc.perl6.org</a> , supplemented by the design documents at <a href="">https://design.perl6.org/</a> and input from the denizens of #perl6 on irc.freenode.org</p>
<a name="t3.4"$class><h1>3.4 Alphabetical Listing of Perl Functions</h1></a>
<a name="t3.4.1"$class><h2>3.4.1 Filetests</h2></a>
<ul><li><p>-X FILEHANDLE</p>
</li></ul> <ul><li><p>-X EXPR</p>
</li></ul> <ul><li><p>-X DIRHANDLE</p>
</li></ul> <ul><li><p>-X</p>
</li></ul> <p>Perl 6 gives you a couple of options when it comes to file tests. You can do a smart match ( <span class="code">~~ </span> ) or you can call a method.</p>
<p>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 <span class="code">.IO </span> to the filename. For instance, here is how to check if a file is readable using smart match:</p>
<pre class="code">C&lt;'/path/to/file'.IO ~~ :r></pre>
<p>You can, of course, use an already opened filehandle. Here, using the file handle <span class="code">$fh </span> , is an example, using the method syntax for the file test:</p>
<pre class="code">C&lt;$fh.r></pre>
<p>Most of the former filetests have colon equivalents for use with smart match:</p>
<pre class="code">:e Exists
:d Directory
:f File
:l Symbolic link
:r Readable
:w Writable
:x Executable
:s Size
:z Zero size</pre>
<p>All of these tests can be used as methods (without the colon).</p>
<p>Three tests, however, <i>only</i> have method equivalents:</p>
<pre class="code">C&lt;-M $fh> => C&lt;$fh.modified>
C&lt;-A $fh> => C&lt;$fh.accessed>
C&lt;-C $fh> => C&lt;$fh.changed></pre>
<p>The remaining filetests in Perl 5 do not appear to be implemented in Perl 6.</p>
<p>The documentation for this can be found at <a href="">https://doc.perl6.org/type/IO::FileTestable#File_Test_operators</a> .</p>
<p>There is more information on reading and writing files at <a href="">https://doc.perl6.org/language/io</a> . Also, the section on <span class="code">open() </span> below may be helpful.</p>
<a name="t3.4.2"$class><h2>3.4.2 abs</h2></a>
<ul><li><p>abs VALUE</p>
</li></ul> <p>Works as a function ( <span class="code">abs($x) </span> ), but also as a method. One gotcha, however - method calls bind more tightly than <span class="code">- </span> , so, for example, <span class="code">-15.abs </span> evaluates as <span class="code">-(15.abs) </span> giving you <span class="code">-15 </span> . In this example, you would have to do something like <span class="code">(-15).abs </span> .</p>
<p> <span class="code">abs </span> also operates on <span class="code">$_ </span> in the absence of a value, but not as a function, and as a method you need to call it as <span class="code">.abs </span> rather than simply <span class="code">abs </span> .</p>
<a name="t3.4.3"$class><h2>3.4.3 accept</h2></a>
<ul><li><p>accept NEWSOCKET,GENERICSOCKET</p>
</li></ul> <p> <span class="code">accept </span> is a method you can call on a server, e. g. <span class="code">$server.accept() </span> . Instead of returning a packed address, it returns a socket, most likely an IO::Socket object of some sort.</p>
<a name="t3.4.4"$class><h2>3.4.4 alarm</h2></a>
<ul><li><p>alarm SECONDS</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] <span class="code">alarm() </span> is no more. It has been suggested that a replacement may be somewhere in the new Concurrency features, such as <span class="code">Promise.in </span> , but some digging may be needed to find a true analog.</p>
<a name="t3.4.5"$class><h2>3.4.5 atan2</h2></a>
<ul><li><p>atan2 Y,X</p>
</li></ul> <p>Available as a function as well as being able to be used as a method. For instance, these are equivalent:</p>
<pre class="code">C&lt;atan2(100)>
C&lt;100.atan2></pre>
<a name="t3.4.6"$class><h2>3.4.6 bind</h2></a>
<ul><li><p>bind SOCKET,NAME</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] No sign of a socket-related <span class="code">bind() </span> in Perl 6. At a guess, whatever socket binding is needed happens when you create a new socket object.</p>
<a name="t3.4.7"$class><h2>3.4.7 binmode</h2></a>
<ul><li><p>binmode FILEHANDLE</p>
</li></ul> <p>Instead of this, you would use <span class="code">:bin </span> as the file mode when opening the socket. E. g. <span class="code">my $fh = open("path/to/file", :bin); </span> </p>
<a name="t3.4.8"$class><h2>3.4.8 bless</h2></a>
<ul><li><p>bless REF,CLASSNAME</p>
</li></ul> <p>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 <span class="code">new </span> for creating objects rather than <span class="code">bless </span> , although there may be some situations in which the latter may still be useful.</p>
<a name="t3.4.9"$class><h2>3.4.9 break</h2></a>
<ul><li><p>break</p>
</li></ul> <p>Not in Perl 6. For breaking out of <span class="code">given </span> blocks, you should probably take a look at <span class="code">proceed </span> and <span class="code">succeed </span> ( <a href="">https://doc.perl6.org/language/control#proceed_and_succeed</a> ).</p>
<a name="t3.4.10"$class><h2>3.4.10 caller</h2></a>
<ul><li><p>caller EXPR</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] What <span class="code">caller </span> does in Perl 5 is taken on by <span class="code">callframe </span> . However, a simple call to <span class="code">callframe </span> 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 <span class="code">caller </span> in Perl 5, are in <span class="code">callframe.annotations </span> . You get them by using <span class="code">callframe().annotations.&lt;file line> </span> or, individually, with <span class="code">callframe().annotations.&lt;file> </span> and <span class="code"> callframe().annotations.&lt;line> </span> . There does not seem to be a simple way of getting the package name out of <span class="code">callframe </span> however.</p>
<a name="t3.4.11"$class><h2>3.4.11 chdir</h2></a>
<ul><li><p>chdir EXPR</p>
</li></ul> <p>Seems to work as it does in Perl 5.</p>
<a name="t3.4.12"$class><h2>3.4.12 chmod</h2></a>
<ul><li><p>chmod LIST</p>
</li></ul> <p>Functions as under Perl 5, with the difference that octal numbers are represented differently ( <span class="code">0o755 </span> rather than <span class="code">0755 </span> ). You may also use it as a method, e. g. <span class="code">$fh.chmod(0o755) </span> .</p>
<a name="t3.4.13"$class><h2>3.4.13 chomp</h2></a>
<ul><li><p>chomp VARIABLE</p>
</li></ul> <p>The behavior of <span class="code">chomp </span> is different than in Perl 5. It leaves the target unaffected and <i>returns</i> the target with a final logical newline removed. I. e. <span class="code">$x = "howdy\n";$y = chomp($x); </span> results in <span class="code">$x </span> containing "howdy\n" and <span class="code">$y </span> containing "howdy". Also works as a method, i. e. <span class="code">$y = $x.chomp </span> .</p>
<a name="t3.4.14"$class><h2>3.4.14 chop</h2></a>
<ul><li><p>chop VARIABLE</p>
</li></ul> <p>As with <span class="code">chomp </span> , in Perl 6, this returns the chopped string, rather than chopping in place. I. e. <span class="code">$x = "howdy";$y = chop($x); </span> results in <span class="code">$x </span> being "howdy" and <span class="code">$y </span> being "howd". Also works as a method: <span class="code">$y = $x.chop </span> </p>
<a name="t3.4.15"$class><h2>3.4.15 chown</h2></a>
<ul><li><p>chown LIST</p>
</li></ul> <p> <span class="code">chown </span> is not in Perl 6.</p>
<a name="t3.4.16"$class><h2>3.4.16 chr</h2></a>
<ul><li><p>chr NUMBER</p>
</li></ul> <p>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:</p>
<pre class="code">C&lt;chr(65); # "A">
C&lt;65.chr; # "A"></pre>
<a name="t3.4.17"$class><h2>3.4.17 chroot</h2></a>
<ul><li><p>chroot FILENAME</p>
</li></ul> <p>Apparently this is not in Perl 6.</p>
<a name="t3.4.18"$class><h2>3.4.18 close</h2></a>
<ul><li><p>close FILEHANDLE</p>
</li></ul> <p>As in Perl 5, closes a filehandle. Returns a boolean value. Both <span class="code">close $fh </span> and <span class="code">$fh.close </span> will work.</p>
<a name="t3.4.19"$class><h2>3.4.19 closedir</h2></a>
<ul><li><p>closedir DIRHANDLE</p>
</li></ul> <p>Currently, there is no <span class="code">closedir </span> function. When it is implemented, it may well be a method in the IO::Dir class.</p>
<a name="t3.4.20"$class><h2>3.4.20 connect</h2></a>
<ul><li><p>connect SOCKET,NAME</p>
</li></ul> <p>Not clearly documented, but it appears that <span class="code">connect </span> will be a method you would call on some variety of IO::Socket object.</p>
<a name="t3.4.21"$class><h2>3.4.21 continue</h2></a>
<ul><li><p>continue BLOCK</p>
</li></ul> <ul><li><p>continue</p>
</li></ul> <p>Instead of a <span class="code">continue </span> block, you should use a <span class="code">NEXT </span> block. The closest analog to a bare <span class="code">continue; </span> in Perl 5 appears to be <span class="code">proceed </span> / <span class="code">succeed </span> .</p>
<a name="t3.4.22"$class><h2>3.4.22 cos</h2></a>
<ul><li><p>cos EXPR</p>
</li></ul> <p>Works as in Perl 5, but can be also used as a method, i. e. <span class="code">(1/60000).cos </span> .</p>
<a name="t3.4.23"$class><h2>3.4.23 crypt</h2></a>
<ul><li><p>crypt PLAINTEXT,SALT</p>
</li></ul> <p>This appears not to have made it into Perl 6.</p>
<a name="t3.4.24"$class><h2>3.4.24 dbm functions</h2></a>
<ul><li><p>dbmclose HASH</p>
</li></ul> <ul><li><p>dbmopen HASH,DBNAME,MASK</p>
</li></ul> <p>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).</p>
<a name="t3.4.25"$class><h2>3.4.25 defined</h2></a>
<ul><li><p>defined EXPR</p>
</li></ul> <p>Probably does what you expect, but technically it returns <span class="code">False </span> on the type object, and <span class="code">True </span> otherwise. This may make more sense when you realize that <span class="code">$num.perl </span> is the type <span class="code">Any </span> if you haven't assigned anything to it, and the assigned value if you have. Can, of course be used as a method: <span class="code">$num.defined </span> </p>
<a name="t3.4.26"$class><h2>3.4.26 delete</h2></a>
<ul><li><p>delete EXPR</p>
</li></ul> <p>Perl 6 replaces this with the new adverb syntax, specifically the <span class="code">:delete </span> adverb. E. g. <span class="code">my $deleted_value = %hash{$key}:delete; </span> and <span class="code">my $deleted_value = @array[$i]:delete; </span> .</p>
<a name="t3.4.27"$class><h2>3.4.27 die</h2></a>
<ul><li><p>die LIST</p>
</li></ul> <p>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 <a href="">https://doc.perl6.org/language/exceptions</a> .</p>
<a name="t3.4.28"$class><h2>3.4.28 do</h2></a>
<ul><li><p>do BLOCK</p>
</li></ul> <p>Similar to the Perl 5 version. Note that there must be a space between the <span class="code">do </span> and the block.</p>
<ul><li><p>do EXPR</p>
</li></ul> <p>Has been replaced in Perl 6 by <span class="code">EVALFILE </span> .</p>
<a name="t3.4.29"$class><h2>3.4.29 dump</h2></a>
<ul><li><p>dump LABEL</p>
</li></ul> <p>According to S29, <span class="code">dump </span> has been... dumped.</p>
<a name="t3.4.30"$class><h2>3.4.30 each</h2></a>
<ul><li><p>each HASH</p>
</li></ul> <p>There is no exact equivalent. The closest is probably &lt;%hash.kv> which returns a list of keys and values. Ergo: <span class="code">for %hash.kv - </span> $k, $v { #do stuff with $k and $v }></p>
<p>Incidentally, what we have there with the <span class="code">-> </span> 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. <a href="">https://design.perl6.org/S04.html#The_for_statement</a> may be of some help here, as well as the design document at <a href="">https://design.perl6.org/S06.html#%22Pointy_blocks%22</a> . There is also some information at <a href="">https://en.wikibooks.org/wiki/Perl_6_Programming/- Blocks_and_Closures#Pointy_Blocks</a> </p>
<a name="t3.4.31"$class><h2>3.4.31 eof</h2></a>
<ul><li><p>eof FILEHANDLE</p>
</li></ul> <p>In Perl 6, this is not usable as a function, but only as a method. I. e. <span class="code">$filehandle.eof </span> . Returns <span class="code">True </span> if at end of file.</p>
<a name="t3.4.32"$class><h2>3.4.32 eval</h2></a>
<ul><li><p>eval EXPR</p>
</li></ul> <ul><li><p>eval EXPR</p>
</li></ul> <p>Replaced by <span class="code">EVAL </span> . Note that <span class="code">EVAL </span> does not do any exception handling!</p>
<a name="t3.4.33"$class><h2>3.4.33 evalbytes</h2></a>
<ul><li><p>evalbytes EXPR</p>
</li></ul> <p>No longer seems to exist.</p>
<a name="t3.4.34"$class><h2>3.4.34 exec</h2></a>
<ul><li><p>exec LIST</p>
</li></ul> <p>Nothing in Perl 6 exactly replicates the Perl 5 <span class="code">exec </span> . <span class="code">shell </span> and <span class="code">run </span> are similar to Perl 5's <span class="code">system </span> , but <span class="code">exec </span> 's behavior of not returning after executing a system command would have to be emulated by something like <span class="code">shell($command);exit(); </span> or possibly <span class="code">exit shell($command); </span> </p>
<a name="t3.4.35"$class><h2>3.4.35 exists</h2></a>
<ul><li><p>exists EXPR</p>
</li></ul> <p>In Perl 6, this is not a function, but an adverb:</p>
<pre class="code">C&lt;%hash{$key}:exists;>
C&lt;@array[$i]:exists;></pre>
<a name="t3.4.36"$class><h2>3.4.36 exit</h2></a>
<ul><li><p>exit EXPR</p>
</li></ul> <p>Appears to do the same thing as in Perl 5.</p>
<a name="t3.4.37"$class><h2>3.4.37 exp</h2></a>
<ul><li><p>exp EXPR</p>
</li></ul> <p>Same as in Perl 5, but can also be used as a method: <span class="code">5.exp </span> ;</p>
<a name="t3.4.38"$class><h2>3.4.38 fc</h2></a>
<ul><li><p>fc EXPR</p>
</li></ul> <p>Looks like it does the same thing as in Perl 5.</p>
<a name="t3.4.39"$class><h2>3.4.39 fcntl</h2></a>
<ul><li><p>fcntl FILEHANDLE,FUNCTION,SCALAR</p>
</li></ul> <p>Appears not to be in Perl 6.</p>
<a name="t3.4.40"$class><h2>3.4.40 __FILE__</h2></a>
<ul><li><p>__FILE__</p>
</li></ul> <p>Replaced by <span class="code">$?FILE </span> .</p>
<a name="t3.4.41"$class><h2>3.4.41 fileno</h2></a>
<ul><li><p>fileno FILEHANDLE</p>
</li></ul> <p>S32 indicates that this should be available as a method, but appears currently unimplemented.</p>
<a name="t3.4.42"$class><h2>3.4.42 flock</h2></a>
<ul><li><p>flock FILEHANDLE,OPERATION</p>
</li></ul> <p>Currently unimplemented.</p>
<a name="t3.4.43"$class><h2>3.4.43 fork</h2></a>
<ul><li><p>fork</p>
</li></ul> <p>Not implemented as a built in function, but available through the <span class="code">NativeCall </span> interface. E. g. <span class="code">use NativeCall; sub fork returns int32 is native { * }; say fork; </span> .</p>
<a name="t3.4.44"$class><h2>3.4.44 formats</h2></a>
<ul><li><p>format</p>
</li></ul> <ul><li><p>formline PICTURE,LIST</p>
</li></ul> <p>Perl 6 does not have built-in formats.</p>
<a name="t3.4.45"$class><h2>3.4.45 getc</h2></a>
<ul><li><p>getc FILEHANDLE</p>
</li></ul> <p>Reads a single character from the input stream as in Perl 5. May now also be used as a method: <span class="code">$filehandle.getc </span> </p>
<a name="t3.4.46"$class><h2>3.4.46 getlogin</h2></a>
<ul><li><p>getlogin</p>
</li></ul> <p>S29 lists it, but it does not seem to be implemented yet.</p>
<a name="t3.4.47"$class><h2>3.4.47 getpeername</h2></a>
<ul><li><p>getpeername SOCKET</p>
</li></ul> <p>S29 lists it, but the implementation does not seem clear or, for that matter, implemented.</p>
<a name="t3.4.48"$class><h2>3.4.48 getpgrp</h2></a>
<ul><li><p>getpgrp PID</p>
</li></ul> <p>Does not appear to be implemented.</p>
<a name="t3.4.49"$class><h2>3.4.49 getpriority</h2></a>
<ul><li><p>getpriority WHICH,WHO</p>
</li></ul> <p>Does not appear to be implemented.</p>
<a name="t3.4.50"$class><h2>3.4.50 get and set functions</h2></a>
<ul><li><p>getpwnam NAME</p>
</li></ul> <ul><li><p>getgrnam NAME</p>
</li></ul> <ul><li><p>gethostbyname NAME</p>
</li></ul> <ul><li><p>getnetbyname NAME</p>
</li></ul> <ul><li><p>getprotobyname NAME</p>
</li></ul> <ul><li><p>getpwuid UID</p>
</li></ul> <ul><li><p>getgrgid GID</p>
</li></ul> <ul><li><p>getservbyname NAME,PROTO</p>
</li></ul> <ul><li><p>gethostbyaddr ADDR,ADDRTYPE</p>
</li></ul> <ul><li><p>getnetbyaddr ADDR,ADDRTYPE</p>
</li></ul> <ul><li><p>getprotobynumber NUMBER</p>
</li></ul> <ul><li><p>getservbyport PORT,PROTO</p>
</li></ul> <ul><li><p>getpwent</p>
</li></ul> <ul><li><p>getgrent</p>
</li></ul> <ul><li><p>gethostent</p>
</li></ul> <ul><li><p>getnetent</p>
</li></ul> <ul><li><p>getprotoent</p>
</li></ul> <ul><li><p>getservent</p>
</li></ul> <ul><li><p>setpwent</p>
</li></ul> <ul><li><p>setgrent</p>
</li></ul> <ul><li><p>sethostent STAYOPEN</p>
</li></ul> <ul><li><p>setnetent STAYOPEN</p>
</li></ul> <ul><li><p>setprotoent STAYOPEN</p>
</li></ul> <ul><li><p>setservent STAYOPEN</p>
</li></ul> <ul><li><p>endpwent</p>
</li></ul> <ul><li><p>endgrent</p>
</li></ul> <ul><li><p>endhostent</p>
</li></ul> <ul><li><p>endnetent</p>
</li></ul> <ul><li><p>endprotoent</p>
</li></ul> <ul><li><p>endservent</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] Apparently this range of functions are to be handled by roles like User, Group, etc.</p>
<a name="t3.4.51"$class><h2>3.4.51 getsock*</h2></a>
<ul><li><p>getsockname SOCKET</p>
</li></ul> <ul><li><p>getsockopt SOCKET,LEVEL,OPTNAME</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] These are likely implemented by some kind of IO::Socket object, but details are unclear.</p>
<a name="t3.4.52"$class><h2>3.4.52 glob</h2></a>
<ul><li><p>glob EXPR</p>
</li></ul> <p>Used in an example in S32, but apparently unimplemented.</p>
<a name="t3.4.53"$class><h2>3.4.53 gmtime</h2></a>
<ul><li><p>gmtime EXPR</p>
</li></ul> <p>Like the various parts of <span class="code">localtime </span> , <span class="code">gmtime </span> 's functionality appears to in the <span class="code">DateTime </span> object. To get a UTC version of a <span class="code">DateTime </span> object for the current time, for instance, use <span class="code">my $gmtime = DateTime.now.utc </span> .</p>
<a name="t3.4.54"$class><h2>3.4.54 goto</h2></a>
<ul><li><p>goto LABEL</p>
</li></ul> <ul><li><p>goto EXPR</p>
</li></ul> <ul><li><p>goto &amp;NAME</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] Described in S04, but not yet fully documented.</p>
<a name="t3.4.55"$class><h2>3.4.55 grep</h2></a>
<ul><li><p>grep BLOCK LIST</p>
</li></ul> <ul><li><p>grep EXPR,LIST</p>
</li></ul> <p>Still in Perl 6, with the caveat that the block form now requires a comma after the block. I.e. <span class="code">@foo = grep { $_ = "bars" }, @baz </span> . Can also be used as a method: <span class="code">@foo = @bar.grep(/^f/) </span> </p>
<a name="t3.4.56"$class><h2>3.4.56 hex</h2></a>
<ul><li><p>hex EXPR</p>
</li></ul> <p>Replaced by the adverbial form <span class="code">:16 </span> . E. g. <span class="code">:16("aF") </span> returns 175.</p>
<p>Alternately, the same result can be achieved by using the <span class="code">.base </span> method: <span class="code">0xaF.base(10) </span> </p>
<p>It just so happens that <span class="code">.Str </span> defaults to base 10, so if you just <span class="code">say 0xaF </span> , that will also print 175, but that may not be immediately obvious, so may not be the best way to go for this.</p>
<a name="t3.4.57"$class><h2>3.4.57 import</h2></a>
<ul><li><p>import LIST</p>
</li></ul> <p>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 <a href="">- https://doc.perl6.org/language/5to6#Importing_specific_functions_from- _a_module</a> .</p>
<a name="t3.4.58"$class><h2>3.4.58 index</h2></a>
<ul><li><p>index STR,SUBSTR,POSITION</p>
</li></ul> <p>Works as in Perl 5. Can also now be used as a method: <span class="code">"howdy!".index("how"); # 0 </span> </p>
<a name="t3.4.59"$class><h2>3.4.59 int</h2></a>
<ul><li><p>int EXPR</p>
</li></ul> <p>There is a <span class="code">truncate </span> function in Perl 6 (also usable as a method) that does what Perl 5's <span class="code">int </span> 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 <span class="code">.Int </span> method on the number. <span class="code">3.9.Int; # 3 </span> and <span class="code">3.9.truncate </span> are equivalent.</p>
<a name="t3.4.60"$class><h2>3.4.60 ioctl</h2></a>
<ul><li><p>ioctl FILEHANDLE,FUNCTION,SCALAR</p>
</li></ul> <p>Currently unimplemented in Perl 6.</p>
<a name="t3.4.61"$class><h2>3.4.61 join</h2></a>
<ul><li><p>join EXPR,LIST</p>
</li></ul> <p>Works as in Perl 5, and also works as a method: <span class="code">@x.join(",") </span> </p>
<a name="t3.4.62"$class><h2>3.4.62 keys</h2></a>
<ul><li><p>keys HASH</p>
</li></ul> <p>Works as in Perl 5, and can also be used as a method: <span class="code">%hash.keys </span> </p>
<a name="t3.4.63"$class><h2>3.4.63 kill</h2></a>
<ul><li><p>kill SIGNAL, LIST</p>
</li></ul> <ul><li><p>kill SIGNAL</p>
</li></ul> <p>Now part of the <span class="code">Proc::ASync </span> class, but looks to work as in Perl 5.</p>
<a name="t3.4.64"$class><h2>3.4.64 last</h2></a>
<ul><li><p>last LABEL</p>
</li></ul> <ul><li><p>last EXPR</p>
</li></ul> <ul><li><p>last</p>
</li></ul> <p>Same as in Perl 5.</p>
<a name="t3.4.65"$class><h2>3.4.65 lc</h2></a>
<ul><li><p>lc EXPR</p>
</li></ul> <p>Works as in Perl 5, and also as a method: <span class="code">"UGH".lc </span> </p>
<a name="t3.4.66"$class><h2>3.4.66 lcfirst</h2></a>
<ul><li><p>lcfirst EXPR</p>
</li></ul> <p>Does not exist in Perl 6.</p>
<a name="t3.4.67"$class><h2>3.4.67 length</h2></a>
<ul><li><p>length EXPR</p>
</li></ul> <p>Replaced by <span class="code">chars </span> , typically used as a method ( <span class="code">$string.chars </span> ), but also works as a function.</p>
<a name="t3.4.68"$class><h2>3.4.68 __LINE__</h2></a>
<ul><li><p>__LINE__</p>
</li></ul> <p>Replaced by <span class="code">$?LINE </span> .</p>
<a name="t3.4.69"$class><h2>3.4.69 link</h2></a>
<ul><li><p>link OLDFILE,NEWFILE</p>
</li></ul> <p>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 <span class="code">link($original, $linked_file) </span> .</p>
<a name="t3.4.70"$class><h2>3.4.70 listen</h2></a>
<ul><li><p>listen SOCKET,QUEUESIZE</p>
</li></ul> <p>Not clearly documented, but it appears that <span class="code">listen </span> will be a method you would call on some variety of IO::Socket object.</p>
<a name="t3.4.71"$class><h2>3.4.71 local</h2></a>
<ul><li><p>local EXPR</p>
</li></ul> <p>The Perl 6 equivalent is <span class="code">temp </span> .</p>
<a name="t3.4.72"$class><h2>3.4.72 localtime</h2></a>
<ul><li><p>localtime EXPR</p>
</li></ul> <p>Most of the functionality of <span class="code">localtime </span> is found in <span class="code">DateTime </span> . The specific parts of <span class="code">localtime </span> can be found as follows:</p>
<pre class="code">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
</pre>
<p>Please note that ranges are not 0-based in Perl 6, as shown in the comments in the example.</p>
<p>There does not currently appear to be a way to get Perl 5's <span class="code">$isdst </span> . Also, the result of <span class="code">scalar(localtime) </span> that Perl 5 provides is not available. <span class="code">$d.Str </span> will give something along the lines of "2015-06-29T12:49:31-04:00".</p>
<a name="t3.4.73"$class><h2>3.4.73 lock</h2></a>
<ul><li><p>lock THING</p>
</li></ul> <p>In Perl 6, a method in the <span class="code">Lock </span> class.</p>
<a name="t3.4.74"$class><h2>3.4.74 log</h2></a>
<ul><li><p>log EXPR</p>
</li></ul> <p>Available in Perl 6. Also works as a method. I. e. <span class="code">log(2) </span> is equivalent to <span class="code">2.log </span> .</p>
<a name="t3.4.75"$class><h2>3.4.75 lstat</h2></a>
<ul><li><p>lstat FILEHANDLE</p>
</li></ul> <ul><li><p>lstat EXPR</p>
</li></ul> <ul><li><p>lstat DIRHANDLE</p>
</li></ul> <ul><li><p>lstat</p>
</li></ul> <p>Likely implemented somewhere in one of the <span class="code">IO </span> classes in Perl 6, but it is not clear where at this time.</p>
<a name="t3.4.76"$class><h2>3.4.76 m//</h2></a>
<ul><li><p>m//</p>
</li></ul> <p>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 <span class="code">=~ </span> is replaced by the smart match operator, <span class="code">~~ </span> . Similarly, <span class="code">!~ </span> is replaced by <span class="code">!~~ </span> . Options for regex operators are adverbs and are complicated. For details, see <a href="">https://doc.perl6.org/language/regexes#Adverbs</a> </p>
<a name="t3.4.77"$class><h2>3.4.77 map</h2></a>
<ul><li><p>map BLOCK LIST</p>
</li></ul> <ul><li><p>map EXPR,LIST</p>
</li></ul> <p>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: <span class="code">@new = @old.map: { $_ * 2 } </span> </p>
<a name="t3.4.78"$class><h2>3.4.78 mkdir</h2></a>
<ul><li><p>mkdir FILENAME,MASK</p>
</li></ul> <ul><li><p>mkdir FILENAME</p>
</li></ul> <p>Works as in Perl 5.</p>
<ul><li><p>mkdir</p>
</li></ul> <p>The zero argument (implicit <span class="code">$_ </span> ) version is not permitted in Perl 6.</p>
<a name="t3.4.79"$class><h2>3.4.79 msg*</h2></a>
<ul><li><p>msgctl ID,CMD,ARG</p>
</li></ul> <ul><li><p>msgget KEY,FLAGS</p>
</li></ul> <ul><li><p>msgrcv ID,VAR,SIZE,TYPE,FLAGS</p>
</li></ul> <ul><li><p>msgsnd ID,MSG,FLAGS</p>
</li></ul> <p>Not builtins in Perl 6. May appear in an external module at some point. Maybe.</p>
<a name="t3.4.80"$class><h2>3.4.80 my</h2></a>
<ul><li><p>my VARLIST</p>
</li></ul> <ul><li><p>my TYPE VARLIST</p>
</li></ul> <ul><li><p>my VARLIST : ATTRS</p>
</li></ul> <ul><li><p>my TYPE VARLIST : ATTRS</p>
</li></ul> <p>Works as in Perl 5.</p>
<a name="t3.4.81"$class><h2>3.4.81 next</h2></a>
<ul><li><p>next LABEL</p>
</li></ul> <ul><li><p>next EXPR</p>
</li></ul> <ul><li><p>next</p>
</li></ul> <p>The same in Perl 6.</p>
<a name="t3.4.82"$class><h2>3.4.82 no</h2></a>
<ul><li><p>no MODULE VERSION</p>
</li></ul> <ul><li><p>no MODULE LIST</p>
</li></ul> <ul><li><p>no MODULE</p>
</li></ul> <ul><li><p>no VERSION</p>
</li></ul> <p>In Perl 6, this is usable for pragmas such as <span class="code">strict </span> , 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.</p>
<a name="t3.4.83"$class><h2>3.4.83 oct</h2></a>
<ul><li><p>oct</p>
</li></ul> <p>Replaced by the adverbial form <span class="code">:8 </span> . E. g. <span class="code">:8("100") </span> returns 64.</p>
<a name="t3.4.84"$class><h2>3.4.84 open</h2></a>
<ul><li><p>open FILEHANDLE,EXPR</p>
</li></ul> <ul><li><p>open FILEHANDLE,MODE,EXPR</p>
</li></ul> <ul><li><p>open FILEHANDLE,MODE,EXPR,LIST</p>
</li></ul> <ul><li><p>open FILEHANDLE,MODE,REFERENCE</p>
</li></ul> <ul><li><p>open FILEHANDLE</p>
</li></ul> <p>The most obvious change from Perl 5 is the file mode syntax. To open a file for reading only, you would say <span class="code">open("file", :r) </span> . For write- only, read-write, and append, you would use <span class="code">:w </span> , <span class="code">:rw </span> , and <span class="code">:a </span> respectively. There are also options for encoding and how the filehandle deals with newlines. Details at <a href="">https://doc.perl6.org/routine/open</a> .</p>
<a name="t3.4.85"$class><h2>3.4.85 opendir</h2></a>
<ul><li><p>opendir DIRHANDLE,EXPR</p>
</li></ul> <p>Not a builtin function in Perl 6. You would use the IO::Path class:</p>
<pre class="code">C&lt;my $dir = IO::Path.new("directory")>
C&lt;my $dir = "directory".IO; # Same, but probably more direct></pre>
<a name="t3.4.86"$class><h2>3.4.86 ord</h2></a>
<ul><li><p>ord EXPR</p>
</li></ul> <p>Same as in Perl 5. May be used as a method: <span class="code">"howdy!".ord; # 104 </span> </p>
<a name="t3.4.87"$class><h2>3.4.87 our</h2></a>
<ul><li><p>our VARLIST</p>
</li></ul> <ul><li><p>our TYPE VARLIST</p>
</li></ul> <ul><li><p>our VARLIST : ATTRS</p>
</li></ul> <ul><li><p>our TYPE VARLIST : ATTRS</p>
</li></ul> <p>The same in Perl 6.</p>
<a name="t3.4.88"$class><h2>3.4.88 pack</h2></a>
<ul><li><p>pack TEMPLATE,LIST</p>
</li></ul> <p>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 <a href="">https://doc.perl6.org/routine/unpack</a> .</p>
<a name="t3.4.89"$class><h2>3.4.89 package</h2></a>
<ul><li><p>package NAMESPACE</p>
</li></ul> <ul><li><p>package NAMESPACE VERSION</p>
</li></ul> <ul><li><p>package NAMESPACE BLOCK</p>
</li></ul> <ul><li><p>package NAMESPACE VERSION BLOCK</p>
</li></ul> <p>S10 indicates that <span class="code">package </span> can be used in Perl 6, but only with a block. I. e. <span class="code">package Foo { ... } </span> means that the code within the block would be in package Foo. There is a special case where a declaration of the form <span class="code">package Foo; </span> 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 <span class="code">class </span> ), it's unlikely you will use <span class="code">package </span> directly in Perl 6.</p>
<a name="t3.4.90"$class><h2>3.4.90 __PACKAGE__</h2></a>
<ul><li><p>__PACKAGE__</p>
</li></ul> <p>Replaced by <span class="code">$?PACKAGE </span> .</p>
<a name="t3.4.91"$class><h2>3.4.91 pipe</h2></a>
<ul><li><p>pipe READHANDLE,WRITEHANDLE</p>
</li></ul> <p>Probably replaced by something in the <span class="code">IO::Pipe </span> class, but this is not clearly documented.</p>
<a name="t3.4.92"$class><h2>3.4.92 pop</h2></a>
<ul><li><p>pop ARRAY</p>
</li></ul> <p>Works in Perl 6, and can also be used as a method. I. e. <span class="code">my $x = pop @a; </span> and <span class="code">my $x = @a.pop; </span> are equivalent.</p>
<a name="t3.4.93"$class><h2>3.4.93 pos</h2></a>
<ul><li><p>pos SCALAR</p>
</li></ul> <p>Not available in Perl 6. The closest equivalent is the <span class="code">:c </span> adverb, which defaults to <span class="code">$/.to </span> if <span class="code">$/ </span> is true, and <span class="code">0 </span> if it isn't. For information on <span class="code">:c </span> , see <a href="">https://doc.perl6.org/language/regexes#Continue</a> .</p>
<a name="t3.4.94"$class><h2>3.4.94 print</h2></a>
<ul><li><p>print FILEHANDLE LIST</p>
</li></ul> <ul><li><p>print FILEHANDLE</p>
</li></ul> <ul><li><p>print LIST</p>
</li></ul> <ul><li><p>print</p>
</li></ul> <p> <span class="code">print </span> can be used as a function in Perl 6, defaulting to standard out. To use <span class="code">print </span> as a function with a filehandle <i>instead</i> of standard out, you need to put a colon after the filehandle. I. e. <span class="code">print $fh: "Howdy!" </span> . The use of the colon as an "invocant marker" here is discussed at <a href="">https://design.perl6.org/S03.html#line_4019</a> . Alternately, you can use a method call: <span class="code">$fh.print("howdy!") </span> </p>
<a name="t3.4.95"$class><h2>3.4.95 printf</h2></a>
<ul><li><p>printf FILEHANDLE</p>
</li></ul> <ul><li><p>printf FORMAT, LIST</p>
</li></ul> <ul><li><p>printf</p>
</li></ul> <p>Works in Perl 6. For the formats, see the documentation for <span class="code">sprintf </span> .</p>
<a name="t3.4.96"$class><h2>3.4.96 prototype</h2></a>
<ul><li><p>prototype FUNCTION</p>
</li></ul> <p>No available in Perl 6. The closest equivalent seems to be <span class="code">.signature </span> . E. g. <span class="code">say &amp;sprintf.signature </span> results in "(Cool $format, *@args)".</p>
<a name="t3.4.97"$class><h2>3.4.97 push</h2></a>
<ul><li><p>push ARRAY,LIST</p>
</li></ul> <p>Works as in Perl 5, as well as being available as a method: <span class="code">@a.push("foo"); </span> . <i>Note:</i> the flattening behaviour is different in Perl 6: <span class="code">@b.push: @a </span> will push <span class="code">@a </span> into <span class="code">@b </span> as a single element. See also the <a href="/type/Array#method_append">append method</a> .</p>
<a name="t3.4.98"$class><h2>3.4.98 quoting</h2></a>
<ul><li><p>q/STRING/</p>
</li></ul> <ul><li><p>qq/STRING/</p>
</li></ul> <ul><li><p>qw/STRING/</p>
</li></ul> <ul><li><p>qx/STRING/</p>
</li></ul> <p>These survive the transition to Perl 6. Some notes:</p>
<pre class="code">C&lt;q/.../> is still equivalent to using single quotes.
C&lt;qq/.../> is still equivalent to using double quotes.
C&lt;qw/.../> is more commonly rendered as C&lt;&lt; &lt;...> >> in Perl 6.</pre>
<p>There are some added quoting constructs and equivalents, as explained at <a href="">https://doc.perl6.org/language/quoting</a> .</p>
<ul><li><p>qr/STRING/</p>
</li></ul> <p>Has been replaced by <span class="code">rx/.../ </span> .</p>
<ul><li><p>quotemeta EXPR</p>
</li></ul> <p>No direct equivalent, i.e. nothing that just returns the string with all the ASCII non-word characters backslashed. In regexes, however, using <span class="code">$foo </span> will treat <span class="code">$foo </span> as a literal string, and using <span class="code">&lt;$foo> </span> will interpret the contents of <span class="code">$foo </span> 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 <a href="">https://design.perl6.org/S05.html#Extensible_metasyntax_(%3C...%3E)</a> </p>
<a name="t3.4.99"$class><h2>3.4.99 rand</h2></a>
<ul><li><p>rand EXPR</p>
</li></ul> <p> <span class="code">rand </span> 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 <span class="code">rand(100) </span> is equivalent to <span class="code">100.rand </span> in Perl 6. Additionally, you can get a random integer by using something like <span class="code">(^100).pick </span> . For <i>why</i> you are able to do that, see <a href="">https://doc.perl6.org/language/operators#prefix_%5E</a> and <a href="">https://doc.perl6.org/routine/pick</a> .</p>
<a name="t3.4.100"$class><h2>3.4.100 read</h2></a>
<ul><li><p>read FILEHANDLE,SCALAR,LENGTH,OFFSET</p>
</li></ul> <p> <span class="code">read </span> is found in <span class="code">IO::Handle </span> and <span class="code">IO::Socket </span> 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.</p>
<a name="t3.4.101"$class><h2>3.4.101 readdir</h2></a>
<ul><li><p>readdir DIRHANDLE</p>
</li></ul> <p>Not a builtin function. To iterate through the contents of a directory, take a look at <a href="">https://doc.perl6.org/type/IO::Path#routine_dir</a> .</p>
<a name="t3.4.102"$class><h2>3.4.102 readline</h2></a>
<ul><li><p>readline</p>
</li></ul> <p>Not available in Perl 6. You most likely want to use the <span class="code">.lines </span> method in some way. For more detailed information on reading from files, see <a href="">https://doc.perl6.org/language/io</a> .</p>
<a name="t3.4.103"$class><h2>3.4.103 readlink</h2></a>
<ul><li><p>readlink EXPR</p>
</li></ul> <p>Appears to be gone from Perl 6.</p>
<a name="t3.4.104"$class><h2>3.4.104 readpipe</h2></a>
<ul><li><p>readpipe EXPR</p>
</li></ul> <ul><li><p>readpipe</p>
</li></ul> <p>Doesn't appear to be working in Perl 6, but <span class="code">qx// </span> is functional, so it might be lurking around in some class that isn't obvious.</p>
<a name="t3.4.105"$class><h2>3.4.105 recv</h2></a>
<ul><li><p>recv SOCKET,SCALAR,LENGTH,FLAGS</p>
</li></ul> <p>Appears to be in IO::Socket. Not extensively documented at this time.</p>
<a name="t3.4.106"$class><h2>3.4.106 redo</h2></a>
<ul><li><p>redo LABEL</p>
</li></ul> <ul><li><p>redo EXPR</p>
</li></ul> <ul><li><p>redo</p>
</li></ul> <p>Unchanged in Perl 6.</p>
<a name="t3.4.107"$class><h2>3.4.107 ref</h2></a>
<ul><li><p>ref EXPR</p>
</li></ul> <p>Gone. To quote S29, "If you really want the type name, you can use <span class="code">$var.WHAT.perl </span> . If you really want P5 ref semantics, use <span class="code">Perl5::p5ref </span> ." Except that <span class="code">Perl5::p5ref </span> does not seem to currently exist...</p>
<a name="t3.4.108"$class><h2>3.4.108 rename</h2></a>
<ul><li><p>rename OLDNAME,NEWNAME</p>
</li></ul> <p>Still available in Perl 6.</p>
<a name="t3.4.109"$class><h2>3.4.109 requires</h2></a>
<ul><li><p>require VERSION</p>
</li></ul> <p>Seems that <span class="code">require </span> may work for modules in Perl 6, but unclear if it will work with version numbers.</p>
<a name="t3.4.110"$class><h2>3.4.110 reset</h2></a>
<ul><li><p>reset EXPR</p>
</li></ul> <p>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.</p>
<a name="t3.4.111"$class><h2>3.4.111 return</h2></a>
<ul><li><p>return EXPR</p>
</li></ul> <p>Appears to be available in Perl 6, although not clearly documented.</p>
<a name="t3.4.112"$class><h2>3.4.112 reverse</h2></a>
<ul><li><p>reverse LIST</p>
</li></ul> <p>In Perl 6, this only reverses the elements of a list. <span class="code">reverse(@a) </span> or <span class="code">@a.reverse </span> . To reverse the characters in a string, use the <span class="code">.flip </span> method.</p>
<a name="t3.4.113"$class><h2>3.4.113 rewinddir</h2></a>
<ul><li><p>rewinddir DIRHANDLE</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] There does not appear to be an obvious direct equivalent. It is possible that some incantation in <span class="code">IO::Path </span> may serve, but it's not clear what it would be.</p>
<a name="t3.4.114"$class><h2>3.4.114 rindex</h2></a>
<ul><li><p>rindex STR,SUBSTR,POSITION</p>
</li></ul> <p>Works as in Perl 5, and may also be used as a method. E. g. <span class="code">$x = "babaganush";say $x.rindex("a");say $x.rindex("a", 3); # 5, 3 </span> </p>
<a name="t3.4.115"$class><h2>3.4.115 rmdir</h2></a>
<ul><li><p>rmdir FILENAME</p>
</li></ul> <p>Works in Perl 6 and can also be used as a method. <span class="code">rmdir "Foo"; </span> and <span class="code">"Foo".IO.rmdir; </span> are equivalent.</p>
<a name="t3.4.116"$class><h2>3.4.116 s///</h2></a>
<ul><li><p>s///</p>
</li></ul> <p>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 <span class="code">=~ </span> is replaced by the smart match operator, <span class="code">~~ </span> . Similarly, <span class="code">!~ </span> is <span class="code">!~~ </span> . Options for regex operators are adverbs and are complicated. For details, see <a href="">https://doc.perl6.org/language/regexes#Adverbs</a> </p>
<a name="t3.4.117"$class><h2>3.4.117 say</h2></a>
<ul><li><p>say FILEHANDLE</p>
</li></ul> <ul><li><p>say LIST</p>
</li></ul> <ul><li><p>say</p>
</li></ul> <p> <span class="code">say </span> can be used as a function, defaulting to standard out. To use <span class="code">say </span> as a function with a filehandle <i>instead</i> of standard out, you need to put a colon after the filehandle. I. e. <span class="code">say $fh: "Howdy!" </span> . The use of the colon as an "invocant marker" here is discussed at <a href="">https://design.perl6.org/S03.html#line_4019</a> . Alternately, you can use a method call: <span class="code">$fh.say("howdy!") </span> </p>
<a name="t3.4.118"$class><h2>3.4.118 scalar</h2></a>
<ul><li><p>scalar EXPR</p>
</li></ul> <p>Gone. Apparently "very" gone.</p>
<a name="t3.4.119"$class><h2>3.4.119 seek</h2></a>
<ul><li><p>seek FILEHANDLE,POSITION,WHENCE</p>
</li></ul> <p>Not documented in a any real way yet, but listed under the <span class="code">IO::Handle </span> class.</p>
<a name="t3.4.120"$class><h2>3.4.120 seekdir</h2></a>
<ul><li><p>seekdir DIRHANDLE,POS</p>
</li></ul> <p>Not currently documented, but looks to be something that would be implemented in one of the <span class="code">IO </span> classes, likely <span class="code">IO::Path </span> .</p>
<a name="t3.4.121"$class><h2>3.4.121 select</h2></a>
<ul><li><p>select FILEHANDLE</p>
</li></ul> <p>"[S]elect as a global concept is dead." When I asked around about <span class="code">select </span> , I was told that $*OUT and such are overridable in dynamic scope, and that <span class="code">IO::Capture::Simple </span> (at <a href="">https://github.com/sergot/IO-Capture-Simple</a> ) may be of use for something you might be doing with the value of <span class="code">select </span> .</p>
<a name="t3.4.122"$class><h2>3.4.122 sem*</h2></a>
<ul><li><p>semctl ID,SEMNUM,CMD,ARG</p>
</li></ul> <ul><li><p>semget KEY,NSEMS,FLAGS</p>
</li></ul> <ul><li><p>semop KEY,OPSTRING</p>
</li></ul> <p>Gone from the core. May turn up in a module somewhere.</p>
<a name="t3.4.123"$class><h2>3.4.123 send</h2></a>
<ul><li><p>send SOCKET,MSG,FLAGS,TO</p>
</li></ul> <p>Can be found in the <span class="code">IO::Socket </span> class.</p>
<a name="t3.4.124"$class><h2>3.4.124 setpgrp</h2></a>
<ul><li><p>setpgrp PID,PGRP</p>
</li></ul> <p>No longer in core. Will probably wind up in a POSIX module.</p>
<a name="t3.4.125"$class><h2>3.4.125 setpriority</h2></a>
<ul><li><p>setpriority WHICH,WHO,PRIORITY</p>
</li></ul> <p>No longer in core. Will probably wind up in a POSIX module.</p>
<a name="t3.4.126"$class><h2>3.4.126 setsockopt</h2></a>
<ul><li><p>setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL</p>
</li></ul> <p>Not documented, but probably hiding in an <span class="code">IO </span> class somewhere.</p>
<a name="t3.4.127"$class><h2>3.4.127 shift</h2></a>
<ul><li><p>shift ARRAY</p>
</li></ul> <ul><li><p>shift EXPR</p>
</li></ul> <ul><li><p>shift</p>
</li></ul> <p>Works as a method as well as a function. <span class="code">shift @a </span> and <span class="code">@a.shift </span> are equivalent.</p>
<a name="t3.4.128"$class><h2>3.4.128 shm*</h2></a>
<ul><li><p>shmctl ID,CMD,ARG</p>
</li></ul> <ul><li><p>shmget KEY,SIZE,FLAGS</p>
</li></ul> <ul><li><p>shmread ID,VAR,POS,SIZE</p>
</li></ul> <ul><li><p>shmwrite ID,STRING,POS,SIZE</p>
</li></ul> <p>Gone from the core. May turn up in a module somewhere.</p>
<a name="t3.4.129"$class><h2>3.4.129 shutdown</h2></a>
<ul><li><p>shutdown SOCKET,HOW</p>
</li></ul> <p>Not documented, but likely moved into <span class="code">IO::Socket </span> .</p>
<a name="t3.4.130"$class><h2>3.4.130 sin</h2></a>
<ul><li><p>sin EXPR</p>
</li></ul> <p>Works as a function and also as a method. <span class="code">sin(2) </span> and <span class="code">2.sin </span> are equivalent.</p>
<a name="t3.4.131"$class><h2>3.4.131 sleep</h2></a>
<ul><li><p>sleep EXPR</p>
</li></ul> <p>Still works as in Perl 5. As of this writing, works as a method, but that is deprecated and will be removed soon.</p>
<a name="t3.4.132"$class><h2>3.4.132 sockets</h2></a>
<ul><li><p>socket SOCKET,DOMAIN,TYPE,PROTOCOL</p>
</li></ul> <ul><li><p>socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL</p>
</li></ul> <p>Not currently documented, but will likely wind up in <span class="code">IO::Socket </span> .</p>
<a name="t3.4.133"$class><h2>3.4.133 sort</h2></a>
<ul><li><p>sort SUBNAME LIST</p>
</li></ul> <p> <span class="code">sort </span> exists in Perl 6, but is somewhat different. <span class="code">$a </span> and <span class="code">$b </span> are no longer special (See <a href="">5to6-perlvar.pod</a> ) and sort routines no longer return positive integers, negative integers, or 0, but rather <span class="code">Order::Increase </span> , <span class="code">Order::Same </span> , or <span class="code">Order::Decrease </span> objects. See <a href="">https://doc.perl6.org/routine/sort</a> for details. May also be used as a method I. e. <span class="code">sort(@a) </span> is equivalent to <span class="code">@a.sort </span> .</p>
<a name="t3.4.134"$class><h2>3.4.134 splice</h2></a>
<ul><li><p>splice ARRAY,OFFSET,LENGTH</p>
</li></ul> <ul><li><p>splice ARRAY,OFFSET</p>
</li></ul> <ul><li><p>splice ARRAY</p>
</li></ul> <ul><li><p>splice EXPR,OFFSET,LENGTH,LIST</p>
</li></ul> <ul><li><p>splice EXPR,OFFSET,LENGTH</p>
</li></ul> <ul><li><p>splice EXPR,OFFSET</p>
</li></ul> <ul><li><p>splice EXPR</p>
</li></ul> <p>Available in Perl 6. Can also be used as a method. <span class="code">splice(@foo, 2,3, &lt;M N O P>); </span> is equivalent to <span class="code">@foo.splice(2, 3, &lt;M N O P>); </span> .</p>
<a name="t3.4.135"$class><h2>3.4.135 split</h2></a>
<ul><li><p>split /PATTERN/,EXPR,LIMIT</p>
</li></ul> <ul><li><p>split /PATTERN/,EXPR</p>
</li></ul> <ul><li><p>split /PATTERN/</p>
</li></ul> <p>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 <span class="code">// </span> 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 <span class="code">:all </span> , like this: <span class="code">split(';', "a;b;c", :all) # a ; b ; c </span> Empty chunks are not removed from the result list as they are in Perl 5. For that behavior, see <span class="code">comb </span> . Details on <span class="code">split </span> are at <a href="">https://doc.perl6.org/routine/split</a> . Unsurprisingly, <span class="code">split </span> also now works as a method: <span class="code">"a;b;c".split(';') </span> </p>
<ul><li><p>split</p>
</li></ul> <p>The zero argument version must now be called with an explicit empty string, as described above.</p>
<a name="t3.4.136"$class><h2>3.4.136 sprintf</h2></a>
<ul><li><p>sprintf FORMAT, LIST</p>
</li></ul> <p>Works as in Perl 5. The formats currently available are:</p>
<pre class="code">% 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)</pre>
<p>Compatibility:</p>
<pre class="code">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</pre>
<p>Perl 5 (non-)compatibility:</p>
<pre class="code">n produces a runtime exception
p produces a runtime exception</pre>
<p>There are modifiers for integers, but they're mainly no-ops, as the semantics aren't settled:</p>
<pre class="code">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)</pre>
<a name="t3.4.137"$class><h2>3.4.137 sqrt</h2></a>
<ul><li><p>sqrt EXPR</p>
</li></ul> <p>Works as a function and a method. <span class="code">sqrt(4) </span> and <span class="code">4.sqrt </span> are equivalent.</p>
<a name="t3.4.138"$class><h2>3.4.138 srand</h2></a>
<ul><li><p>srand EXPR</p>
</li></ul> <p>Available in Perl 6.</p>
<a name="t3.4.139"$class><h2>3.4.139 stat</h2></a>
<ul><li><p>stat EXPR</p>
</li></ul> <ul><li><p>stat DIRHANDLE</p>
</li></ul> <ul><li><p>stat</p>
</li></ul> <p>Likely implemented somewhere in <span class="code">IO </span> , but it is not clear where at this time.</p>
<a name="t3.4.140"$class><h2>3.4.140 state</h2></a>
<ul><li><p>state VARLIST</p>
</li></ul> <ul><li><p>state TYPE VARLIST</p>
</li></ul> <ul><li><p>state VARLIST : ATTRS</p>
</li></ul> <ul><li><p>state TYPE VARLIST : ATTRS</p>
</li></ul> <p>Available in Perl 6, but currently not documented.</p>
<a name="t3.4.141"$class><h2>3.4.141 study</h2></a>
<ul><li><p>study SCALAR</p>
</li></ul> <ul><li><p>study</p>
</li></ul> <p> <span class="code">study </span> is no more.</p>
<a name="t3.4.142"$class><h2>3.4.142 sub</h2></a>
<ul><li><p>sub NAME BLOCK</p>
</li></ul> <ul><li><p>sub NAME (PROTO) BLOCK</p>
</li></ul> <ul><li><p>sub NAME : ATTRS BLOCK</p>
</li></ul> <ul><li><p>sub NAME (PROTO) : ATTRS BLOCK</p>
</li></ul> <p>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), <span class="code">@_ </span> 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 <a href="">https://doc.perl6.org/language/functions</a> .</p>
<a name="t3.4.143"$class><h2>3.4.143 __SUB__</h2></a>
<ul><li><p>__SUB__</p>
</li></ul> <p>Replaced by <span class="code">&amp;?ROUTINE </span> .</p>
<a name="t3.4.144"$class><h2>3.4.144 substr</h2></a>
<ul><li><p>substr EXPR,OFFSET,LENGTH,REPLACEMENT</p>
</li></ul> <ul><li><p>substr EXPR,OFFSET,LENGTH</p>
</li></ul> <ul><li><p>substr EXPR,OFFSET</p>
</li></ul> <p>Can be used as a function or a method. <span class="code">substr("hola!", 1, 3) </span> and <span class="code">"hola!.substr(1, 3) </span> both return "ola".</p>
<a name="t3.4.145"$class><h2>3.4.145 symlink</h2></a>
<ul><li><p>symlink OLDFILE,NEWFILE</p>
</li></ul> <p>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 <span class="code">link($original, $linked_file) </span> .</p>
<a name="t3.4.146"$class><h2>3.4.146 syscall</h2></a>
<ul><li><p>syscall NUMBER, LIST</p>
</li></ul> <p>Not a builtin in Perl 6. Most likely out in a module somewhere, but it's currently unclear where.</p>
<a name="t3.4.147"$class><h2>3.4.147 sys*</h2></a>
<ul><li><p>sysopen FILEHANDLE,FILENAME,MODE</p>
</li></ul> <ul><li><p>sysopen FILEHANDLE,FILENAME,MODE,PERMS</p>
</li></ul> <ul><li><p>sysread FILEHANDLE,SCALAR,LENGTH,OFFSET</p>
</li></ul> <ul><li><p>sysread FILEHANDLE,SCALAR,LENGTH</p>
</li></ul> <ul><li><p>sysseek FILEHANDLE,POSITION,WHENCE</p>
</li></ul> <p>As with the non-sys versions of these functions, are probably lurking in the <span class="code">IO </span> classes somewhere.</p>
<a name="t3.4.148"$class><h2>3.4.148 system</h2></a>
<ul><li><p>system LIST</p>
</li></ul> <ul><li><p>system PROGRAM LIST</p>
</li></ul> <p>For this, you probably want <span class="code">run </span> ( <a href="">https://doc.perl6.org/routine/run</a> ) or <span class="code">shell </span> ( <a href="">https://doc.perl6.org/routine/shell</a> ).</p>
<a name="t3.4.149"$class><h2>3.4.149 syswrite</h2></a>
<ul><li><p>syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET</p>
</li></ul> <ul><li><p>syswrite FILEHANDLE,SCALAR,LENGTH</p>
</li></ul> <ul><li><p>syswrite FILEHANDLE,SCALAR</p>
</li></ul> <p>As with <span class="code">sysopen </span> and friends, this has moved into the <span class="code">IO </span> classes.</p>
<a name="t3.4.150"$class><h2>3.4.150 tell</h2></a>
<ul><li><p>tell FILEHANDLE</p>
</li></ul> <p>In <span class="code">IO::Handle </span> , but not yet documented, beyond a mention.</p>
<a name="t3.4.151"$class><h2>3.4.151 telldir</h2></a>
<ul><li><p>telldir DIRHANDLE</p>
</li></ul> <p>Possibly in <span class="code">IO::Path </span> , but not yet documented.</p>
<a name="t3.4.152"$class><h2>3.4.152 tie</h2></a>
<ul><li><p>tie VARIABLE,CLASSNAME,LIST</p>
</li></ul> <ul><li><p>tied VARIABLE</p>
</li></ul> <p>[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.</p>
<a name="t3.4.153"$class><h2>3.4.153 time</h2></a>
<ul><li><p>time</p>
</li></ul> <p>"Returns an Int representing the current time." Although <i>how</i> it represents the current time isn't in the documentation currently, it appears to still be seconds since epoch, as in Perl 5.</p>
<a name="t3.4.154"$class><h2>3.4.154 times</h2></a>
<ul><li><p>times</p>
</li></ul> <p>Not available in Perl 6.</p>
<a name="t3.4.155"$class><h2>3.4.155 tr///</h2></a>
<ul><li><p>tr///</p>
</li></ul> <p>Not well documented in this form, 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. In Perl 6, <span class="code">tr/// </span> has a method version, which is better documented, called <span class="code">.trans </span> . <span class="code">.trans </span> uses a list of pairs, as follows: <span class="code">$x.trans(['a'..'c'] => ['A'..'C'], ['d'..'q'] => ['D'..'Q'], ['r'..'z'] => ['R'..'Z']); </span> A much more extensive description of the uses of <span class="code">.trans </span> can be found at <a href="">https://design.perl6.org/S05.html#Transliteration</a> . The <span class="code">y/// </span> equivalent has been done away with.</p>
<a name="t3.4.156"$class><h2>3.4.156 truncate</h2></a>
<ul><li><p>truncate FILEHANDLE,LENGTH</p>
</li></ul> <ul><li><p>truncate EXPR,LENGTH</p>
</li></ul> <p>Most likely somewhere in <span class="code">IO::Handle </span> , but not currently documented.</p>
<a name="t3.4.157"$class><h2>3.4.157 uc</h2></a>
<ul><li><p>uc EXPR</p>
</li></ul> <p>Works as a function and a method. <span class="code">uc("ha") </span> and <span class="code">"ha".uc </span> both return "HA".</p>
<a name="t3.4.158"$class><h2>3.4.158 ucfirst</h2></a>
<ul><li><p>ucfirst EXPR</p>
</li></ul> <ul><li><p>ucfirst</p>
</li></ul> <p>Perl 6 has done away with <span class="code">ucfirst </span> . The title case function <span class="code">tc </span> probably does what you need here. <a href="">https://doc.perl6.org/routine/tc</a> </p>
<a name="t3.4.159"$class><h2>3.4.159 umask</h2></a>
<ul><li><p>umask EXPR</p>
</li></ul> <p>Is an <span class="code">IO </span> method. <span class="code">IO.umask </span> returns the umask.</p>
<a name="t3.4.160"$class><h2>3.4.160 undef</h2></a>
<ul><li><p>undef EXPR</p>
</li></ul> <p>There is no <span class="code">undef </span> in Perl 6. You can't undefine a function, and the closest equivalent value is probably <span class="code">Nil </span> , but you'll likely have no use for that. If you were using something like <span class="code">(undef, $file, $line) = caller; </span> , you would just get the filename and line number directly in Perl 6 instead of discarding the first result of <span class="code">caller </span> . <span class="code">caller </span> has been replaced by <span class="code">callframe </span> in Perl 6, so the equivalent statement would be <span class="code">($file, $line) = callframe.annotations&lt;file line>; </span> </p>
<a name="t3.4.161"$class><h2>3.4.161 unlink</h2></a>
<ul><li><p>unlink LIST</p>
</li></ul> <p>Still available. Usable as a method: <span class="code">"filename".IO.unlink </span> </p>
<ul><li><p>unlink</p>
</li></ul> <p>The zero argument (implicit <span class="code">$_ </span> ) version of unlink is not available in Perl 6.</p>
<a name="t3.4.162"$class><h2>3.4.162 unpack</h2></a>
<ul><li><p>unpack TEMPLATE,EXPR</p>
</li></ul> <ul><li><p>unpack TEMPLATE</p>
</li></ul> <p>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 <a href="">https://doc.perl6.org/routine/unpack</a> .</p>
<a name="t3.4.163"$class><h2>3.4.163 unshift</h2></a>
<ul><li><p>unshift ARRAY,LIST</p>
</li></ul> <ul><li><p>unshift EXPR,LIST</p>
</li></ul> <p>Available in Perl 6. Can be used as a method. <span class="code">unshift(@a, "blah") </span> is equivalent to <span class="code">@a.unshift("blah") </span> .</p>
<a name="t3.4.164"$class><h2>3.4.164 untie</h2></a>
<ul><li><p>untie VARIABLE</p>
</li></ul> <p>[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 <span class="code">tie </span> , above.</p>
<a name="t3.4.165"$class><h2>3.4.165 use</h2></a>
<ul><li><p>use Module VERSION LIST</p>
</li></ul> <ul><li><p>use Module VERSION</p>
</li></ul> <ul><li><p>use Module LIST</p>
</li></ul> <ul><li><p>use Module</p>
</li></ul> <ul><li><p>use VERSION</p>
</li></ul> <p>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</p>
<a name="t3.4.166"$class><h2>3.4.166 fc</h2></a>
<ul><li><p>utime LIST</p>
</li></ul> <p>S32 says this is gone, and refers you to <span class="code">Path.times </span> . Unfortunately, there seems to be no sign of <span class="code">Path.times </span> . Perhaps there will be something in <span class="code">IO::Path </span> , but it is not currently evident.</p>
<a name="t3.4.167"$class><h2>3.4.167 values</h2></a>
<ul><li><p>values HASH</p>
</li></ul> <ul><li><p>values ARRAY</p>
</li></ul> <ul><li><p>values EXPR</p>
</li></ul> <p>Available in Perl 6. Can also be used as a method. <span class="code">values %hash </span> is equivalent to <span class="code">%hash.values </span> .</p>
<a name="t3.4.168"$class><h2>3.4.168 vec</h2></a>
<ul><li><p>vec EXPR,OFFSET,BITS</p>
</li></ul> <p>S29 says "Should replace <span class="code">vec </span> with declared buffer/array of <span class="code">bit </span> , <span class="code">uint2 </span> , <span class="code">uint4 </span> , etc." It is unclear, however, that this has actually happened.</p>
<a name="t3.4.169"$class><h2>3.4.169 wait</h2></a>
<ul><li><p>wait</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] Unclear where this has gone. There's a <span class="code">wait </span> method in <span class="code">Supply </span> , and an <span class="code">await </span> method in both <span class="code">Channel </span> and <span class="code">Promise </span> . Which, if any or all, of these is a direct equivalent of Perl 5's <span class="code">wait </span> is unclear.</p>
<a name="t3.4.170"$class><h2>3.4.170 waitpid</h2></a>
<ul><li><p>waitpid PID,FLAGS</p>
</li></ul> <p>As with <span class="code">wait </span> , the disposition of this is unclear.</p>
<a name="t3.4.171"$class><h2>3.4.171 wantarray</h2></a>
<ul><li><p>wantarray</p>
</li></ul> <p>There is no <span class="code">wantarray </span> in Perl 6.</p>
<a name="t3.4.172"$class><h2>3.4.172 warn</h2></a>
<ul><li><p>warn LIST</p>
</li></ul> <p> <span class="code">warn </span> throws an exception. To simply print a message to <span class="code">$*ERR </span> , you would use the <span class="code">note </span> function. For more on exceptions, see <a href="">https://doc.perl6.org/language/exceptions</a> .</p>
<a name="t3.4.173"$class><h2>3.4.173 write</h2></a>
<ul><li><p>write FILEHANDLE</p>
</li></ul> <ul><li><p>write EXPR</p>
</li></ul> <ul><li><p>write</p>
</li></ul> <p>Formats are gone from Perl 6, so this no longer works.</p>
<a name="t3.4.174"$class><h2>3.4.174 y///</h2></a>
<ul><li><p>y///</p>
</li></ul> <p>This synonym for <span class="code">tr/// </span> is gone. For functionality, see the entry for <span class="code">tr/// </span> .</p>
<a name="t4"><h1 class="title">4 5to6-perlop</h1></a> <p class="subtitle">Perl 5 to Perl 6 guide - operators</p></a> <a name="t4.1"$class><h1>4.1 DESCRIPTION</h1></a>
<p>A (hopefully) comprehensive list of Perl 5 operators with their Perl 6 equivalents with notes on variations between them where necessary.</p>
<a name="t4.2"$class><h1>4.2 NOTE</h1></a>
<p>I will <i>not</i> 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.</p>
<a name="t4.3"$class><h1>4.3 SOURCES</h1></a>
<p>I'm taking my information from <a href="">https://doc.perl6.org</a> (in particular, <a href="">https://doc.perl6.org/language/operators</a> ), supplemented by the design documents at <a href="">https://design.perl6.org/</a> and input from the denizens of #perl6 on irc.freenode.org</p>
<a name="t4.3.1"$class><h2>4.3.1 Operator Precedence and Associativity</h2></a>
<p>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 <a href="">https://doc.perl6.org/language/operators#Operator_Precedence</a> .</p>
<a name="t4.3.2"$class><h2>4.3.2 Terms and List Operators</h2></a>
<p>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 <span class="code">print </span> and <span class="code">chdir </span> . As such, you can find information about them in <a href="">5to6-perlfunc.pod</a> . Parentheses are still used for grouping.</p>
<a name="t4.3.3"$class><h2>4.3.3 The Arrow Operator</h2></a>
<p>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 <span class="code">$arrayref->[7] </span> becomes <span class="code">$arrayref.[7] </span> in Perl 6 and, similarly, <span class="code">$user->name </span> becomes <span class="code">$user.name </span> . The <span class="code">=> </span> arrow is used for constructing Pairs, see <a href="">https://doc.perl6.org/language/terms#Pair</a> .</p>
<a name="t4.3.4"$class><h2>4.3.4 Auto-increment and Auto-decrement</h2></a>
<p>Work as in Perl 5. The one possible caveat is that they function by calling the <span class="code">succ </span> method for <span class="code">++ </span> and the <span class="code">pred </span> method for <span class="code">-- </span> . For builtin numeric types, this is unlikely to do something unusual, but custom types can define their own <span class="code">succ </span> and <span class="code">pred </span> methods, so in those cases, you should probably take note of what <span class="code">++ </span> and <span class="code">-- </span> will <i>actually</i> do.</p>
<a name="t4.3.5"$class><h2>4.3.5 Exponentiation</h2></a>
<p>Works as you would expect. The caveat in Perl 5's perlop about <span class="code">** </span> 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.</p>
<a name="t4.3.6"$class><h2>4.3.6 Symbolic Unary Operators</h2></a>
<p>As in Perl 5, unary <span class="code">! </span> and <span class="code">- </span> do logical arithmetic negation, respectively. <span class="code">?^ </span> is used for bitwise logical negation, which the documentation indicates is equivalent to <span class="code">! </span> . It may be relevant to note that these coerce their arguments to <span class="code">Bool </span> and <span class="code">Numeric </span> , respectively.</p>
<p>Unary <span class="code">~ </span> is the string context operator in Perl 6, so use prefix <span class="code">+^ </span> for bitwise integer negation. Assumes two's complement.</p>
<p> <span class="code">+ </span> <i>does</i> have an effect in Perl 6, coercing its argument to to the Numeric type.</p>
<p>Unary &lt;\> is no more. If you really want to take a reference to an existing named variable, you can use item context, like so: <span class="code">$aref = item(@array) </span> You can get a reference to a named subroutine by using the <span class="code">&amp; </span> sigil: &lt;$sref = &amp;foo> Anonymous arrays, hashes, and subs return their references during creation.</p>
<a name="t4.3.7"$class><h2>4.3.7 Binding Operators</h2></a>
<p> <span class="code">=~ </span> and <span class="code">!~ </span> have been replaced by <span class="code">~~ </span> and <span class="code">!~~ </span> , 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.</p>
<a name="t4.3.8"$class><h2>4.3.8 Multiplicative Operators</h2></a>
<p>Binary <span class="code">* </span> , <span class="code">/ </span> , and <span class="code">% </span> do multiplication, division, and modulo, respectively, as in Perl 5.</p>
<p>Binary <span class="code">x </span> is slightly different in Perl 6, and has a companion. <span class="code">print '-' x 80; </span> gives you a string of 80 dashes, but for the Perl 5 behavior of <span class="code">@ones = (1) x 80; </span> giving you a list of 80 "1"s, you would use <span class="code">@ones = 1 xx 80; </span> .</p>
<a name="t4.3.9"$class><h2>4.3.9 Additive Operators</h2></a>
<p>Binary <span class="code">+ </span> and &lt;-> do addition and subtraction, respectively, as you would expect..</p>
<p>As <span class="code">. </span> is the method call operator, so binary <span class="code">~ </span> acts as the concatenation operator in Perl 6.</p>
<a name="t4.3.10"$class><h2>4.3.10 Shift Operators</h2></a>
<p> <span class="code">&lt;&lt; >> and C&lt;&lt; >> </span> have been replaced by <span class="code">+&lt; </span> and <span class="code">+> </span> .</p>
<a name="t4.3.11"$class><h2>4.3.11 Named Unary Operators</h2></a>
<p>As noted above, you'll find these in <a href="">5to6-perlfunc.pod</a> .</p>
<a name="t4.3.12"$class><h2>4.3.12 Relational Operators</h2></a>
<p>These all work as in Perl 5.</p>
<a name="t4.3.13"$class><h2>4.3.13 Equality Operators</h2></a>
<p> <span class="code">== </span> and <span class="code">!= </span> both work as in Perl 5.</p>
<p> <span class="code">&lt;=> </span> and <span class="code">cmp </span> have different behavior in Perl 6. <span class="code">&lt;=> </span> does a numeric comparison, but returns &lt;Order::Less>, &lt;Order::Same>, or &lt;Order::More> instead of Perl 5's <span class="code">-1 </span> , <span class="code">0 </span> , or <span class="code">1 </span> . To get the Perl 5 behavior (with the change that it returns the <span class="code">Order </span> objects, rather than integers) of <span class="code">cmp </span> , you would use the <span class="code">leg </span> operator.</p>
<p> <span class="code">cmp </span> does either <span class="code">&lt;=> </span> or <span class="code">leg </span> , depending on the existing type of its arguments.</p>
<p> <span class="code">~~ </span> is the smart match operator as in Perl 5, but it's also <i>just</i> the match operator in Perl 6, as noted above. For how smart matching works in Perl 6, see <a href="">https://design.perl6.org/S03.html#Smart_matching</a> .</p>
<a name="t4.3.14"$class><h2>4.3.14 Smartmatch Operator</h2></a>
<p>See the entry on <span class="code">~~ </span> directly above.</p>
<a name="t4.3.15"$class><h2>4.3.15 Bitwise And</h2></a>
<p>Binary <span class="code">&amp; </span> is <span class="code">+&amp; </span> in Perl 6.</p>
<a name="t4.3.16"$class><h2>4.3.16 Bitwise Or and Exclusive Or</h2></a>
<p>Bitwise OR has changed from <span class="code">| </span> in Perl 5 to <span class="code">+| </span> in Perl 6. Similarly, bitwise XOR <span class="code">^ </span> is <span class="code">+^ </span> </p>
<a name="t4.3.17"$class><h2>4.3.17 C-style Logical And</h2></a>
<p>Unchanged.</p>
<a name="t4.3.18"$class><h2>4.3.18 C-style Logical Or</h2></a>
<p>Unchanged.</p>
<a name="t4.3.19"$class><h2>4.3.19 Logical Defined-Or</h2></a>
<p>Remains in Perl 6 as <span class="code">// </span> . Returns the first defined operand, or else the last operand. Also, there is a low precedence version, called <span class="code">orelse </span> .</p>
<a name="t4.3.20"$class><h2>4.3.20 Range Operators</h2></a>
<p>In list context, <span class="code">.. </span> 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:</p>
<pre class="code">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></pre>
<p>In scalar context, <span class="code">.. </span> and <span class="code">... </span> work as flip-flop operators in Perl 5, but are little-known, and probably even less used. Those operations have been taken over by <span class="code">ff </span> and <span class="code">fff </span> in Perl 6, but are not clearly documented at this time.</p>
<a name="t4.3.21"$class><h2>4.3.21 Conditional Operator</h2></a>
<p> <span class="code">?: </span> has been replaced by <span class="code">?? !! </span> . I. e. where you would use <span class="code">$x = $ok ? $y : $z; </span> in Perl 5, you would use <span class="code">$x = $ok ?? $y !! $z; </span> in Perl 6.</p>
<a name="t4.3.22"$class><h2>4.3.22 Assignment Operators</h2></a>
<p>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 <span class="code">.= </span> calls a mutating method on the object on the left, while <span class="code">~= </span> is the string concatenation assignment, as you might expect with the changes in <span class="code">. </span> and <span class="code">~ </span> . Also, the bitwise assignment operators are likely not separated into numeric and string versions ( <span class="code">&amp;= </span> , etc., vs. <span class="code">&amp;.= </span> , etc.), as that feature is currently experimental in Perl 5 itself - although, again, this is not specifically documented.</p>
<a name="t4.3.23"$class><h2>4.3.23 Comma Operator</h2></a>
<p>The comma operator works mostly as expected, but technically it creates <a href="/type/List">Lists</a> ) or separates arguments in function calls. Also, there is a <span class="code">: </span> variant that turns function calls into method calls - see <a href="">https://doc.perl6.org/language/operators#infix_%3A</a> .</p>
<p>The <span class="code">=> </span> 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.</p>
<a name="t4.3.24"$class><h2>4.3.24 List Operators (Rightward)</h2></a>
<p>Like the Named Unary Operators, you'll find these discussed in <a href="">5to6-perlfunc.pod</a> .</p>
<a name="t4.3.25"$class><h2>4.3.25 Logical Not</h2></a>
<p>The lower precedence version of <span class="code">! </span> . As with <span class="code">! </span> , coerces its argument to <span class="code">Bool </span> .</p>
<a name="t4.3.26"$class><h2>4.3.26 Logical And</h2></a>
<p>Lower precedence version of <span class="code">&amp;&amp; </span> as in Perl 5.</p>
<a name="t4.3.27"$class><h2>4.3.27 Logical or and Exclusive Or</h2></a>
<p> <span class="code">or </span> is the low precedence version of <span class="code">|| </span> . The documentation lists an <span class="code">xor </span> , but does not actually document it.</p>
<p>Additionally, there is a low precedence version of <span class="code">// </span> , called <span class="code">orelse </span> .</p>
<a name="t4.3.28"$class><h2>4.3.28 Quote and Quote-like Operators</h2></a>
<p>For all the gory details on quoting constructs, see <a href="">https://doc.perl6.org/language/quoting</a> .</p>
<p>There is a quoting operator that allows absolute literal strings: <span class="code">Q </span> or <span class="code">「…」 </span> , although the latter might be difficult to find on your keyboard, depending on your keyboard... Backslash escapes do <i>not</i> apply in <span class="code">Q </span> quoted strings. E. g. <span class="code">Q{This is still a closing curly brace → \} </span> renders "This is still a closing curly brace → \".</p>
<p> <span class="code">q </span> does what you expect, allowing backslash escapes. E. g. <span class="code">q{This is not a closing curly brace → \}, but this is → } </span> returning "This is not a closing curly brace → }, but this is →". As in Perl 5, you can get this behavior with single quotes.</p>
<p> <span class="code">qq </span> 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. <span class="code">@a = &lt;1 2 3>;say qq/@a[] example@example.com/; </span> results in "1 2 3 example@example.com". Hashes interpolate in a possibly unexpected manner: <span class="code">%a = 1 => 2, 3 => 4;say "%a[]"; </span> 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 <a href="">https://doc.perl6.org/language/quoting#Interpolation%3A_qq</a> .</p>
<p> <span class="code">qw </span> works as in Perl 5, and can also be rendered as <span class="code">&lt;...> </span> . E. g. <span class="code">qw/a b c/ </span> is equivalent to <span class="code">&lt;a b c> </span> .</p>
<p>There is also a version of <span class="code">qw </span> that interpolates, which is <span class="code">qqw </span> . So <span class="code">my $a = 42;say qqw/$a b c/; </span> gives you "42 b c".</p>
<p>Shell quoting is available through <span class="code">qx </span> , but you should note that backticks do not do shell quoting as in Perl 5, and Perl variables are <i>not</i> interpolated in <span class="code">qx </span> strings. If you need to interpolate Perl variables in a shell command string, you can use <span class="code">qqx </span> instead.</p>
<p>The <span class="code">qr </span> operator is gone from Perl 6.</p>
<p> <span class="code">tr/// </span> 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. <span class="code">tr/// </span> has a method version, which is better documented, called <span class="code">.trans </span> . <span class="code">.trans </span> uses a list of pairs, as follows: <span class="code">$x.trans(['a'..'c'] => ['A'..'C'], ['d'..'q'] => ['D'..'Q'], ['r'..'z'] => ['R'..'Z']); </span> A much more extensive description of the uses of <span class="code">.trans </span> can be found at <a href="">https://design.perl6.org/S05.html#Transliteration</a> . The <span class="code">y/// </span> equivalent has been done away with.</p>
<p>Heredocs are specified differently in Perl 6. You use <span class="code">:to </span> with your quoting operator, e. g. <span class="code">q:to/END/; </span> would start a heredoc ending with "END". Similarly, you get escaping and interpolation based on your quoting operator, i. e. literals with <span class="code">Q </span> , backslash escapes with <span class="code">q </span> , and interpolation with <span class="code">qq </span> .</p>
<a name="t4.3.29"$class><h2>4.3.29 I/O Operators</h2></a>
<p>The full details on Input/Output in Perl 6 can be found at <a href="">https://doc.perl6.org/language/io</a> .</p>
<p>As <span class="code">&lt;...> </span> is the quote-words construct in Perl 6, <span class="code">&lt;> </span> is not used for reading lines from a file. You can do that by either making an <span class="code">IO </span> object from a file name or using an open filehandle and then, in either case, calling <span class="code">.lines </span> on it. I. e. either <span class="code">my @a = "filename".IO.lines; </span> or <span class="code">my $fh = open "filename", :r;my @a = $fh.lines; </span> (In the latter case, we are using <span class="code">:r </span> to specifically open the file for reading). To do this in an iterative manner, you can use a <span class="code">for </span> loop this way:</p>
<pre class="code">for 'huge-csv'.IO.lines -> $line {
# Do something with $line
}
</pre>
<p>Note the use of <span class="code">-> </span> there. That's part of the Block syntax, and in Perl 6 is needed for <span class="code">if </span> , <span class="code">for </span> , <span class="code">while </span> , etc.</p>
<p>If you want to slurp the entire file into a scalar, you would - surprise! - use the <span class="code">.slurp </span> method. For instance, <span class="code">my $x = "filename".IO.slurp; </span> or <span class="code">my $fh = open "filename", :r;my $x = $fh.slurp; </span> .</p>
<p>As noted in <a href="">5to6-perlvar.pod</a> , the <span class="code">ARGV </span> magic input filehandle has been replaced by <span class="code">$*ARGFILES </span> , and the <span class="code">@ARGV </span> array of command line arguments has been replaced by <span class="code">@*ARGS </span> .</p>
<a name="t4.3.30"$class><h2>4.3.30 No-ops</h2></a>
<p>Although it's not specifically documented, <span class="code">1 while foo(); </span> appears to work in this sense.</p>
<a name="t4.3.31"$class><h2>4.3.31 Bitwise String Operators</h2></a>
<p>Documented individually above, but to summarize...</p>
<p>Bitwise integer negation is prefix <span class="code">+^ </span> . Bitwise boolean negation is <span class="code">?^ </span> .</p>
<p>Bitwise and is <span class="code">+&amp; </span> .</p>
<p>Bitwise integer or is <span class="code">+| </span> . Bitwise integer xor is infix <span class="code">+^ </span> . Bitwise boolean or is &lt;?|>.</p>
<p>Left shift and right shift are <span class="code">+&lt; </span> and <span class="code">+> </span> .</p>
<a name="t5"><h1 class="title">5 5to6-perlsyn</h1></a> <p class="subtitle">Perl 5 to Perl 6 guide - syntax</p></a> <p>perlsyn - Perl syntax</p>
<a name="t5.1"$class><h1>5.1 DESCRIPTION</h1></a>
<p>A (hopefully) comprehensive description of the differences between Perl 5 and Perl 6 with regards to the syntax elements described in the perlsyn document.</p>
<a name="t5.2"$class><h1>5.2 NOTE</h1></a>
<p>I will <i>not</i> 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.</p>
<a name="t5.3"$class><h1>5.3 SOURCES</h1></a>
<p>I'm taking my information from <a href="">http://doc.perl6.org</a> (in particular, <a href="">http://doc.perl6.org/language/syntax</a> and <a href="">http://doc.perl6.org/language/control</a> ), supplemented by the design documents at <a href="">http://design.perl6.org/</a> and input from the denizens of #perl6 on irc.freenode.org</p>
<a name="t5.4"$class><h1>5.4 Free Form</h1></a>
<p>Perl 6 is still <i>largely</i> 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. <span class="code">while($x &lt; 5)> or C&lt;my($x, $y)>). In Perl 6, that space is required, thus C&lt;while ($x &lt; 5)> or C&lt;my ($x, $y)>. In Perl 6, however, you can omit the parentheses altogether: C&lt;&lt; while $x &lt; 5 > </span> . This holds for <span class="code">if </span> , <span class="code">for </span> , etc.</p>
<p>Oddly, in Perl 5, you can leave spaces between an array or hash and its subscript, and before a postfix operator. So <span class="code">$seen {$_} ++ </span> is valid. No more. That would now have to be <span class="code">%seen{$_}++ </span> .</p>
<p>If it makes you feel better, you can use backslashes to "unspace" whitespace, so you can use whitespace where it would otherwise be forbidden.</p>
<p>You can find the details on this at <a href="">http://doc.perl6.org/language/5to6#Whitespace</a> .</p>
<a name="t5.4.1"$class><h2>5.4.1 Declarations</h2></a>
<p>As noted in <a href="">5to6-perlfunc.pod</a> , there is no <span class="code">undef </span> in Perl 6. A declared, but uninitialized scalar variable will evaluate to its type. In other words, <span class="code">my $x;say $x; </span> will give you "(Any)". <span class="code">my Int $y;say $y; </span> will give you "(Int)".</p>
<a name="t5.4.2"$class><h2>5.4.2 Comments</h2></a>
<p> <span class="code"># </span> starts a comment that runs to the end of the line as in Perl 5.</p>
<p>Embedded comments start with a hash character and a backtick ( <span class="code">#` </span> ), followed by an opening bracketing character, and continue to the matching closing bracketing character. Like so:</p>
<pre class="code">if #`( why would I ever write an inline comment here? ) True {
say "something stupid";
}
</pre>
<p>As in Perl 5, you can use pod directives to create multiline comments, with <span class="code">=begin comment </span> before and <span class="code">=end comment </span> after the comment.</p>
<a name="t5.4.3"$class><h2>5.4.3 Truth and Falsehood</h2></a>
<p>The one difference between Perl 5 truth and Perl 6 truth is that, unlike Perl 5, Perl 6 treats the string <span class="code">"0" </span> as true. Numeric <span class="code">0 </span> is still false, and you can use prefix <span class="code">+ </span> to coerce string <span class="code">"0" </span> 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.</p>
<a name="t5.4.4"$class><h2>5.4.4 Statement Modifiers</h2></a>
<p>Mostly, statement modifiers still work, with a few exceptions.</p>
<p>First, <span class="code">for </span> loops are exclusively what were known in Perl 5 as <span class="code">foreach </span> loops and <span class="code">for </span> is not used for C-style <span class="code">for </span> loops in Perl 6. To get that behavior, you want <span class="code">loop </span> . <span class="code">loop </span> cannot be used as a statement modifier.</p>
<p>In Perl 6, you cannot use the form <span class="code">do {...} while $x </span> . You will want to replace <span class="code">do </span> in that form with <span class="code">repeat </span> . Similarly for <span class="code">do {...} until $x </span> .</p>
<a name="t5.4.5"$class><h2>5.4.5 Compound Statements</h2></a>
<p>The big change from Perl 5 is that <span class="code">given </span> is not experimental or disabled by default in Perl 6. For the details on <span class="code">given </span> see <a href="">http://doc.perl6.org/language/control#given</a> .</p>
<a name="t5.4.6"$class><h2>5.4.6 Loop Control</h2></a>
<p> <span class="code">next </span> , <span class="code">last </span> , and <span class="code">redo </span> have not changed from Perl 5 to Perl 6.</p>
<p> <span class="code">continue </span> , however, does not exist in Perl 6. You would use a <span class="code">NEXT </span> block in the body of the loop.</p>
<pre class="code"># 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 ~= ':'
}
}
</pre>
<a name="t5.4.7"$class><h2>5.4.7 For Loops</h2></a>
<p>As noted above, C-style <span class="code">for </span> loops are not called <span class="code">for </span> loops in Perl 6. They are just <span class="code">loop </span> loops. To write an infinite loop, you do not need to use the C idiom of <span class="code">loop (;;) {...} </span> , but may just omit the spec completely: <span class="code">loop {...} </span> </p>
<a name="t5.4.8"$class><h2>5.4.8 Foreach Loops</h2></a>
<p>In Perl 5, <span class="code">for </span> , in addition to being used for C-style <span class="code">for </span> loops, is a synonym for <span class="code">foreach </span> . In Perl 6, <span class="code">for </span> is just used for <span class="code">foreach </span> style loops.</p>
<a name="t5.4.9"$class><h2>5.4.9 Switch Statements</h2></a>
<p>Perl 6 has actual switch statements, provided by <span class="code">given </span> with the individual cases handled by <span class="code">when </span> and <span class="code">default </span> . The basic syntax is:</p>
<pre class="code">given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}
</pre>
<p>The full details can be found at <a href="">http://doc.perl6.org/language/control#given</a> .</p>
<a name="t5.4.10"$class><h2>5.4.10 Goto</h2></a>
<p> <span class="code">goto </span> <i>probably</i> 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 <span class="code">goto </span> , see <a href="">http://design.perl6.org/S04.html#The_goto_statement</a> .</p>
<a name="t5.4.11"$class><h2>5.4.11 The Ellipsis Statement</h2></a>
<p> <span class="code">... </span> (along with <span class="code">!!! </span> and <span class="code">??? </span> ) are used to create stub declarations. This is a bit more complicated than the use of <span class="code">... </span> in Perl 5, so you'll probably want to look at <a href="">http://design.perl6.org/S06.html#Stub_declarations</a> for the gory details. That said, there doesn't seem to be an <i>obvious</i> reason why it shouldn't still fulfill the role it did in Perl 5, despite its role being expanded in Perl 6.</p>
<a name="t5.4.12"$class><h2>5.4.12 PODs: Embedded Documentation</h2></a>
<p>Pod has changed between Perl 5 and Perl 6. Probably the biggest difference is that you need to enclose your pod between <span class="code">=begin pod </span> and <span class="code">=end pod </span> 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 <span class="code">X&lt;> </span> 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 <span class="code">--doc </span> switch. E. g. <span class="code">perl6 --doc Whatever.pod </span> . This will output any problems to standard error. (Depending on how/where you've installed perl6, you may need to specify the location of <span class="code">Pod::To::Text </span> .) Details on Perl 6 style pod is at <a href="">http://design.perl6.org/S26.html</a> .</p>
<a name="t6"><h1 class="title">6 5to6-perlvar</h1></a> <p class="subtitle">Perl 5 to Perl 6 guide - special variables</p></a> <a name="t6.1"$class><h1>6.1 DESCRIPTION</h1></a>
<p>A (hopefully) comprehensive list of Perl 5 Special Variables with their Perl 6 equivalents with notes on variations between them where necessary.</p>
<a name="t6.2"$class><h1>6.2 NOTE</h1></a>
<p>I will <i>not</i> 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.</p>
<a name="t6.3"$class><h1>6.3 SOURCES</h1></a>
<p>I'm taking my information from <a href="">http://doc.perl6.org/language/variables</a> supplemented by <a href="">http://design.perl6.org/S28.html</a> and input from the denizens of #perl6 on irc.freenode.org</p>
<a name="t6.4"$class><h1>6.4 SPECIAL VARIABLES</h1></a>
<a name="t6.4.1"$class><h2>6.4.1 General Variables</h2></a>
<ul><li><p>$ARG</p>
</li></ul> <ul><li><p>$_</p>
</li></ul> <p>Thankfully, <span class="code">$_ </span> 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 <span class="code">say $_ </span> can be rendered in Perl 6 as <span class="code">$_.say </span> . 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 <span class="code">.say </span> .</p>
<ul><li><p>@ARG</p>
</li></ul> <ul><li><p>@_</p>
</li></ul> <p>As Perl 6 now has function signatures, your arguments can go there, rather than depending on <span class="code">@_ </span> for them. In fact, if you use a function signature, use of <span class="code">@_ </span> will spit at you telling it cannot override an existing signature.</p>
<p>If, however, you do not use a function signature, <span class="code">@_ </span> will contain the arguments you pass to the function as it did in Perl 5. Again, as with <span class="code">$_ </span> , you can call methods on it. Unlike <span class="code">$_ </span> you cannot assume <span class="code">@_ </span> as the default variable for those methods to operate on. I. e. <span class="code">@_.shift </span> works, <span class="code">.shift </span> does not.</p>
<ul><li><p>$LIST_SEPARATOR</p>
</li></ul> <ul><li><p>$"</p>
</li></ul> <p>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.</p>
<ul><li><p>$PROCESS_ID</p>
</li></ul> <ul><li><p>$PID</p>
</li></ul> <ul><li><p>$$</p>
</li></ul> <p> <span class="code">$$ </span> is replaced in Perl 6 by <span class="code">$*PID </span> </p>
<ul><li><p>$PROGRAM_NAME</p>
</li></ul> <ul><li><p>$0</p>
</li></ul> <p>You can access the program name in Perl 6 via <span class="code">$*PROGRAM-NAME </span> .</p>
<p>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).</p>
<ul><li><p>$REAL_GROUP_ID</p>
</li></ul> <ul><li><p>$GID</p>
</li></ul> <ul><li><p>$(</p>
</li></ul> <p>The real group id is provided by <span class="code">$*GROUP.Numeric </span> in Perl 6. <span class="code">$*GROUP.Str </span> returns the group name, rather than its number.</p>
<ul><li><p>$EFFECTIVE_GROUP_ID</p>
</li></ul> <ul><li><p>$EGID</p>
</li></ul> <ul><li><p>$)</p>
</li></ul> <p>The effective group id does not appear to be currently provided by Perl 6.</p>
<ul><li><p>$REAL_USER_ID</p>
</li></ul> <ul><li><p>$UID</p>
</li></ul> <ul><li><p>$&lt;</p>
</li></ul> <p>The real user id is provided by <span class="code">$*USER.Numeric </span> in Perl 6. <span class="code">$*USER.Str </span> returns the user name, rather than its number.</p>
<ul><li><p>$EFFECTIVE_USER_ID</p>
</li></ul> <ul><li><p>$EUID</p>
</li></ul> <ul><li><p>$></p>
</li></ul> <p>The effective user id does not appear to be currently provided by Perl 6.</p>
<ul><li><p>$SUBSCRIPT_SEPARATOR</p>
</li></ul> <ul><li><p>$SUBSEP</p>
</li></ul> <ul><li><p>$;</p>
</li></ul> <p>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.</p>
<ul><li><p>$a</p>
</li></ul> <ul><li><p>$b</p>
</li></ul> <p> <span class="code">$a </span> and <span class="code">$b </span> have no special meaning in Perl 6. <span class="code">sort() </span> does not use them for anything special. They're just regular old variables.</p>
<p>This feature has been extended by having blocks with placeholder parameters which are more versatile. Placeholder variables are created with the <span class="code">^ </span> twigil (e. g. <span class="code">$^z </span> . 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 <span class="code">($^q, $^z, $^a) </span> , they will be <i>assigned</i> in the order <span class="code">($^a, $^q, $^z) </span> . Ergo:</p>
<pre class="code"> 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
</pre>
<p>For more on placeholder variables, see <a href="">http://doc.perl6.org/language/variables#The_%5E_Twigil</a> </p>
<ul><li><p>%ENV</p>
</li></ul> <p>%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.</p>
<ul><li><p>$OLD_PERL_VERSION</p>
</li></ul> <ul><li><p>$]</p>
</li></ul> <p>The version of perl is returned by <span class="code">$*PERL.version </span> . For the beta this was "v6.b" with <span class="code">$*PERL </span> containing "Perl 6 (6.b)".</p>
<ul><li><p>$SYSTEM_FD_MAX</p>
</li></ul> <ul><li><p>$^F</p>
</li></ul> <p>Although the design documents (S28) indicate that this will likely become <span class="code">$*SYS_FD_MAX </span> , this has not yet been implemented.</p>
<ul><li><p>@F</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] A bit confusing at this point. Design doc S28 indicates that <span class="code">@F </span> in Perl 5 is replaced by <span class="code">@_ </span> 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 <span class="code">-a </span> and &lt;-F> command-line switches are not yet implemented in rakudo.</p>
<ul><li><p>@INC</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] If you've been following along, it will probably not surprise you that this is <span class="code">@*INC </span> in Perl 6. The Perl 6 docs say "Each repository is represented as an object with the CompUnitRepo interface in the @*INC array" which could probably use some further explanation. With the version of rakudo star I'm working with, each directory is prefixed with either <span class="code">file# </span> or <span class="code">inst# </span> . Presumably this will become clear when documentation for CompUnitRepo shows up.</p>
<ul><li><p>%INC</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] No longer exists. S28 says it is "encapsulated in CompUnitRepo object" which, as with <span class="code">@INC </span> raises the question of what that means.</p>
<ul><li><p>$INPLACE_EDIT</p>
</li></ul> <ul><li><p>$^I</p>
</li></ul> <p>S28 suggests $*INPLACE_EDIT, but it does not yet seem to exist.</p>
<ul><li><p>$^M</p>
</li></ul> <p>S28 suggests $*EMERGENCY_MEMORY, but it does not yet seem to exist.</p>
<ul><li><p>$OSNAME</p>
</li></ul> <ul><li><p>$^O</p>
</li></ul> <p>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...</p>
<pre class="code">C&lt;$*KERNEL> gives "darwin (14.3.0)"
C&lt;$*DISTRO> gives "macosx (10.10.3)"</pre>
<p>Using <span class="code">.version </span> on either of those will give you just the version number. <span class="code">.name </span> gives the kernel or distro name. Those objects contain other information as well.</p>
<p>S28 also lists <span class="code">$*VM </span> (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.</p>
<ul><li><p>%SIG</p>
</li></ul> <p>[NEEDS FURTHER RESEARCH] No equivalent variable. S28 indicates that this functionality is dealt with in Perl 6 by event filters and exception translation.</p>
<ul><li><p>$BASETIME</p>
</li></ul> <ul><li><p>$^T</p>
</li></ul> <p>Replaced in Perl 6 by <span class="code">$*INITITME </span> . Unlike in Perl 5, this is not in seconds since epoch, but an <span class="code">Instant </span> object, which is measured in atomic seconds, with fractions.</p>
<ul><li><p>$PERL_VERSION</p>
</li></ul> <ul><li><p>$^V</p>
</li></ul> <p>As with <span class="code">$] </span> this has been replaced with <span class="code">$PERL.version </span> .</p>
<ul><li><p>${^WIN32_SLOPPY_STAT}</p>
</li></ul> <p>There does not seem to be any analog to this in Perl 6.</p>
<ul><li><p>$EXECUTABLE_NAME</p>
</li></ul> <ul><li><p>$^X</p>
</li></ul> <p>This has been replaced by <span class="code">$*EXECUTABLE-NAME </span> . Confusingly, the Perl 6 Variables doc says "Favor $*EXECUTABLE because it is not guaranteed that the perl executable is in PATH." Confusingly because <span class="code">$*EXECUTABLE </span> is an <span class="code">IO </span> object, which does not seem to be what you would want here. <span class="code">$*EXECUTABLE.Str </span> would give the desired result, though.</p>
<a name="t6.4.2"$class><h2>6.4.2 Variables related to regular expressions</h2></a>
<a name="t6.4.2.1"$class><h3>6.4.2.1 Performance issues</h3></a>
<p>As shown below, <span class="code">$` </span> , <span class="code">$&amp; </span> , and <span class="code">$' </span> are gone from Perl 6, primarily replaced by variations on <span class="code">$/ </span> and, with their elimination, the associated performance issues in Perl 5 do not apply.</p>
<ul><li><p>$&lt; <i>digits</i> > ($1, $2, ...)</p>
</li></ul> <p>These existing variables do the same thing in Perl 6 as they do in Perl 5, except that they now start at <span class="code">$0 </span> rather than <span class="code">$1 </span> . Furthermore, they are synonyms for indexed items in the match variable <span class="code">$/ </span> . I. e. <span class="code">$0 </span> is equivalent to <span class="code">$/[0] </span> , <span class="code">$1 </span> is equivalent to <span class="code">$/[1] </span> , etc.</p>
<ul><li><p>$MATCH</p>
</li></ul> <ul><li><p>$&amp;</p>
</li></ul> <p> <span class="code">$/ </span> now contains the match object, so the Perl 5 behavior of <span class="code">$&amp; </span> can be obtained by stringifying it, i. e. <span class="code">~$/ </span> . <span class="code">$/.Str </span> also should work, but <span class="code">~$/ </span> seems to be the consensus preference.</p>
<ul><li><p>${^MATCH}</p>
</li></ul> <p>Since the former performance issues are done away with, this variable is not of use in Perl 6.</p>
<ul><li><p>$PREMATCH</p>
</li></ul> <ul><li><p>$`</p>
</li></ul> <p>Replaced by <span class="code">$/.prematch </span> .</p>
<ul><li><p>${^PREMATCH}</p>
</li></ul> <p>Since the former performance issues are done away with, this variable is not of use in Perl 6.</p>
<ul><li><p>$POSTMATCH</p>
</li></ul> <ul><li><p>$'</p>
</li></ul> <p>Replaced by <span class="code">$/.postmatch </span> .</p>
<ul><li><p>${^POSTMATCH}</p>
</li></ul> <p>Since the former performance issues are done away with, this variable is not of use in Perl 6.</p>
<ul><li><p>$LAST_PAREN_MATCH</p>
</li></ul> <ul><li><p>$+</p>
</li></ul> <p>Does not exist in Perl 6, but you can get the same information using <span class="code">$/[*- 1].Str </span> ( <span class="code">$/[*-1] </span> would be the match object, not the actual string).</p>
<p>If you want to <i>understand</i> why that works, you can look at these documents:</p>
<ul><li><p> <a href="">http://doc.perl6.org/routine/%5B%20%5D#language_documentation_Operators</a> </p>
</li></ul> <ul><li><p> <a href="">http://doc.perl6.org/type/Whatever</a> </p>
</li></ul> <p>...and possibly</p>
<ul><li><p> <a href="">http://design.perl6.org/S02.html#line_1126</a> </p>
</li></ul> <p>...though the design documents are not always up to date.</p>
<ul><li><p>$LAST_SUBMATCH_RESULT</p>
</li></ul> <ul><li><p>$^N</p>
</li></ul> <p>S28 suggests <span class="code">$*MOST_RECENT_CAPTURED_MATCH </span> , but there does not seem to be any implemented variable that matches <span class="code">$^N </span> .</p>
<ul><li><p>@LAST_MATCH_END</p>
</li></ul> <ul><li><p>@+</p>
</li></ul> <p>As with most regular expression related variables, this functionality is, at least in part, moved to the <span class="code">$/ </span> 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 <span class="code">.to </span> method. I. e. the first offset is <span class="code">$/[0].to </span> , which is synonymous with <span class="code">$0.to </span> . The value Perl 5 provides as <span class="code">$+[0] </span> is provided by <span class="code">$/.to </span> .</p>
<ul><li><p>%LAST_PAREN_MATCH</p>
</li></ul> <ul><li><p>%+</p>
</li></ul> <p>Once again, we move over to <span class="code">$/ </span> . The former <span class="code">$+{$match} </span> is <span class="code">$/{$match} </span> .</p>
<ul><li><p>@LAST_MATCH_START</p>
</li></ul> <ul><li><p>@-</p>
</li></ul> <p>Similarly to <span class="code">@+ </span> being replaced by using the <span class="code">.to </span> method, <span class="code">@- </span> is replaced by using the <span class="code">.from </span> method on <span class="code">$/ </span> and its variations. The first offset is <span class="code">$/[0].from </span> or the equivalent <span class="code">$0.from </span> . Perl 5's <span class="code">$- [0] </span> is <span class="code">$/.from </span> .</p>
<ul><li><p>%LAST_MATCH_START</p>
</li></ul> <ul><li><p>%-</p>
</li></ul> <p>Much like <span class="code">%+ </span> , a use of <span class="code">%-{$match} </span> would be replaced with <span class="code">$/{$match} </span> .</p>
<ul><li><p>$LAST_REGEXP_CODE_RESULT</p>
</li></ul> <ul><li><p>$^R</p>
</li></ul> <p>S28 suggests <span class="code">$*LAST_REGEXP_CODE_RESULT </span> , but no variable seems to actually exist yet.</p>
<ul><li><p>${^RE_DEBUG_FLAGS}</p>
</li></ul> <p>No equivalent.</p>
<ul><li><p>${^RE_TRIE_MAXBUF}</p>
</li></ul> <p>No equivalent.</p>
<a name="t6.4.3"$class><h2>6.4.3 Variables related to filehandles</h2></a>
<ul><li><p>$ARGV</p>
</li></ul> <p>The name of the current file when reading lines can be obtained through <span class="code">$*ARGFILES.filename </span> .</p>
<ul><li><p>@ARGV</p>
</li></ul> <p> <span class="code">@*ARGS </span> contains the command line arguments.</p>
<ul><li><p>ARGV</p>
</li></ul> <p>This has been replaced by <span class="code">$*ARGFILES </span> .</p>
<ul><li><p>ARGVOUT</p>
</li></ul> <p>As the <span class="code">-i </span> command line switch has not yet been implemented, there is not yet an equivalent of <span class="code">ARGVOUT </span> .</p>
<ul><li><p>$OUTPUT_FIELD_SEPARATOR</p>
</li></ul> <ul><li><p>$OFS</p>
</li></ul> <ul><li><p>$,</p>
</li></ul> <p>Currently no obvious equivalent.</p>
<ul><li><p>$INPUT_LINE_NUMBER</p>
</li></ul> <ul><li><p>$NR</p>
</li></ul> <ul><li><p>$.</p>
</li></ul> <p>The current line number is returned by the <span class="code">.ins </span> method on the appropriate filehandle. E. g. <span class="code">$*IN.ins </span> .</p>
<ul><li><p>$INPUT_RECORD_SEPARATOR</p>
</li></ul> <ul><li><p>$RS</p>
</li></ul> <ul><li><p>$/</p>
</li></ul> <p>This is accessed through the <span class="code">.nl-in </span> method on the filehandle. E. g. <span class="code">$*IN.nl-in </span> .</p>
<ul><li><p>$OUTPUT_RECORD_SEPARATOR</p>
</li></ul> <ul><li><p>$ORS</p>
</li></ul> <ul><li><p>$\</p>
</li></ul> <p>This is accessed through the <span class="code">.nl-out </span> method on the filehandle. E. g. <span class="code">$*OUT.nl-out </span> .</p>
<ul><li><p>$OUTPUT_AUTOFLUSH</p>
</li></ul> <ul><li><p>$|</p>
</li></ul> <p>Currently autoflush is not implemented in Perl 6.</p>
<ul><li><p>${^LAST_FH}</p>
</li></ul> <p>Not implemented in Perl 6.</p>
<a name="t6.4.3.1"$class><h3>6.4.3.1 Variables related to formats</h3></a>
<p>There are no built-in formats in Perl 6.</p>
<a name="t6.4.4"$class><h2>6.4.4 Error Variables</h2></a>
<p>Because of how error variables have changed in Perl 6, I will not detail the changes individually.</p>
<p>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.</p>
<a name="t6.4.5"$class><h2>6.4.5 Variables related to the interpreter state</h2></a>
<ul><li><p>$COMPILING</p>
</li></ul> <ul><li><p>$^C</p>
</li></ul> <ul><li><p>$^D</p>
</li></ul> <p>Currently no equivalents for either of these variables.</p>
<ul><li><p>${^ENCODING}</p>
</li></ul> <p>Although deprecated in Perl 5, this may have some sort of equivalent in <span class="code">$?ENC </span> , but this is far from clear.</p>
<ul><li><p>${^GLOBAL_PHASE}</p>
</li></ul> <p>No Perl 6 equivalent.</p>
<ul><li><p>$^H</p>
</li></ul> <ul><li><p>%^H</p>
</li></ul> <ul><li><p>${^OPEN}</p>
</li></ul> <p>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...</p>
<ul><li><p>$PERLDB</p>
</li></ul> <ul><li><p>$^P</p>
</li></ul> <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.</p>
<ul><li><p>${^TAINT}</p>
</li></ul> <p>S28 claims this variable is "pending". Not currently in Perl 6.</p>
<ul><li><p>${^UNICODE}</p>
</li></ul> <ul><li><p>${^UTF8CACHE}</p>
</li></ul> <ul><li><p>${^UTF8LOCALE}</p>
</li></ul> <p>These Unicode-related variables do not appear to exist in Perl 6, but - maybe? - could have analogs in <span class="code">$?ENC </span> somewhere. This, however, is totally unconfirmed.</p>
<a name="t6.4.6"$class><h2>6.4.6 Deprecated and removed variables</h2></a>
<p>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.</p>
<a name="t7"><h1 class="title">7 About the Docs</h1></a> <p class="subtitle">Documentation for the Perl 6 Documentation Project</p></a> <p>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.</p>
<p>An HTML version of the documentation is located online at <a href="">https://doc.perl6.org</a> .</p>
<p>The official source for this documentation is located at <a href="https://github.com/perl6/doc">perl6/doc on GitHub</a> .</p>
<a name="t7.1"$class><h1>7.1 Structure</h1></a>
<p>All of the documentation is written in Pod6 and kept in the <span class="code">lib/ </span> directory, and the <span class="code">lib/Language/ </span> and <span class="code">lib/Type/ </span> sub-directories. These files are processed as collections of definitions or "documentables", which are then post-processed and linked together.</p>
<a name="t7.2"$class><h1>7.2 Generating an HTML version</h1></a>
<p>Generating this documentation requires:</p>
<ul><li><p>A recent version of the Rakudo Perl 6 compiler</p>
</li></ul> <ul><li><p>The Perl 6 modules Pod::To::HTML and URI::Escape (can be installed via <a href="https://github.com/tadzik/panda">panda</a> )</p>
</li></ul> <ul><li><p> <b>Optional</b> : <a href="http://graphviz.org">GraphViz</a> , for creating graphs of the relationships between Perl 6 types</p>
</li></ul> <ul><li><p> <b>Optional</b> : <a href="http://pygments.org">Pygments</a> , for doing syntax highlighting</p>
</li></ul> <p>Then, to generate the documentation into the <span class="code">html/ </span> folder, run:</p>
<pre class="code">perl6 htmlify.p6</pre>
<p>Currently, to serve the generated documentation for your browser, Perl 5 with Mojolicious::Lite must be installed. Then run:</p>
<pre class="code">perl app.pl daemon</pre>
<a name="t7.3"$class><h1>7.3 Contributing</h1></a>
<a name="t7.3.1"$class><h2>7.3.1 Adding definitions</h2></a>
<p>Documentables can be defined using an <span class="code">=headN </span> Pod directive, where <span class="code">N </span> is greater than one (e.g. <span class="code">=head1 </span> , <span class="code">=head2 </span> , <span class="code">=head3 </span> , …).</p>
<p>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:</p>
<pre class="code">=head2 R<My Definition>
Some paragraphs, followed by some code:
my Code $examples = "amazing";
Mind === blown.
=head3 Minor details about R<My Definition>
It's fantastic.
=head2 And now, for something completely different
</pre>
<p>The documentable R<My Definition> extends down to the <span class="code">=head2 And now… </span> .</p>
<p>Documentables may contain other documentables. Class documentables, for example, often contain the methods the class implements.</p>
<p>Definitions must be in one of the following forms to be recognized as the start of a documentable:</p>
<ul><li><p> <span class="code">X&lt;How to use the X infix | infix,X> </span> (This a special case, which is always considered a definition)</p>
</li></ul> <ul><li><p> <span class="code">The X Infix </span> </p>
</li></ul> <ul><li><p> <span class="code">The C&lt;X> Infix </span> </p>
</li></ul> <ul><li><p> <span class="code">Infix X </span> </p>
</li></ul> <ul><li><p> <span class="code">Infix C&lt;X> </span> </p>
</li></ul> <ul><li><p> <span class="code">trait is cached </span> (A special case for the <a href="/language/functions#Traits">trait</a> documentables)</p>
</li></ul> <a name="t8"><h1 class="title">8 Classes and Objects</h1></a> <p class="subtitle">A tutorial for creating and using classes in Perl 6</p></a> More descriptive title?
<p>The following program 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.</p>
<pre class="code">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();
</pre>
<a name="t8.1"$class><h1>8.1 Starting with class</h1></a>
<p> <span class="indexed$additional-class"><a name="r1"></a></span> <span class="indexed$additional-class"><a name="r2"></a></span> </p>
<p> <span class="indexed$additional-class"><a name="r3"></a></span> <span class="indexed$additional-class"><a name="r4"></a></span> <span class="indexed$additional-class"><a name="r5"></a></span> <span class="indexed$additional-class"><a name="r6"></a></span> <span class="indexed$additional-class"><a name="r7"></a></span> </p>
<p>Perl 6, like many other languages, uses the <span class="code">class </span> 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 <span class="code">has </span> keyword, and behaviors introduced through the <span class="code">method </span> keyword.</p>
<p> <span class="indexed$additional-class"><a name="r8"></a></span> <span class="indexed$additional-class"><a name="r9"></a></span> <span class="indexed$additional-class"><a name="r10"></a></span> </p>
<p>Declaring a class creates a <i>type object</i> which, by default, is installed into the current package (just like a variable declared with <span class="code">our </span> scope). This type object is an "empty instance" of the class. You've already seen these in previous chapters. For example, types such as <span class="code">Int </span> and <span class="code">Str </span> refer to the type object of one of the Perl 6 built-in classes. The example above uses the class name <span class="code">Task </span> so that other code can refer to it later, such as to create class instances by calling the <span class="code">new </span> method.</p>
<p>Type objects are <i>undefined</i> , in the sense that they return <span class="code">False </span> if you call the <span class="code">.defined </span> method on them. You can use this method to find out if a given object is a type object or not:</p>
<pre class="code">my $obj = Int;
if $obj.defined {
say "Ordinary, defined object";
} else {
say "Type object";
}</pre>
<a name="t8.2"$class><h1>8.2 State</h1></a>
<p> <span class="indexed$additional-class"><a name="r11"></a></span> <span class="indexed$additional-class"><a name="r12"></a></span> </p>
<p> <span class="indexed$additional-class"><a name="r13"></a></span> <span class="indexed$additional-class"><a name="r14"></a></span> </p>
<p>The first three lines inside the class block all declare attributes (called <i>fields</i> or <i>instance storage</i> in other languages). These are storage locations that every instance of a class will obtain. Just as a <span class="code">my </span> variable cannot be accessed from outside its declared scope, attributes are not accessible outside of the class. This <i>encapsulation</i> is one of the key principles of object oriented design.</p>
<p>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:</p>
<pre class="code">has &amp;!callback;</pre>
<p> <span class="indexed$additional-class"><a name="r15"></a></span> <span class="indexed$additional-class"><a name="r16"></a></span> <span class="indexed$additional-class"><a name="r17"></a></span> </p>
<p>The <span class="code">&amp; </span> sigil indicates that this attribute represents something invocable. The <span class="code">! </span> character is a <i>twigil</i> , or secondary sigil. A twigil forms part of the name of the variable. In this case, the <span class="code">! </span> twigil emphasizes that this attribute is private to the class.</p>
<p>The second declaration also uses the private twigil:</p>
<pre class="code">has Task @!dependencies;</pre>
<p>However, this attribute represents an array of items, so it requires the <span class="code">@ </span> 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 <span class="code">Task </span> class (or some subclass of it).</p>
<p>The third attribute represents the state of completion of a task:</p>
<pre class="code">has Bool $.done;</pre>
<p> <span class="indexed$additional-class"><a name="r18"></a></span> <span class="indexed$additional-class"><a name="r19"></a></span> <span class="indexed$additional-class"><a name="r20"></a></span> <span class="indexed$additional-class"><a name="r21"></a></span> </p>
<p>This scalar attribute (with the <span class="code">$ </span> sigil) has a type of <span class="code">Bool </span> . Instead of the <span class="code">! </span> twigil, the <span class="code">. </span> twigil is used. While Perl 6 does enforce encapsulation on attributes, it also saves you from writing accessor methods. Replacing the <span class="code">! </span> with a <span class="code">. </span> both declares the attribute <span class="code">$!done </span> and an accessor method named <span class="code">done </span> . It's as if you had written:</p>
<pre class="code">has Bool $!done;
method done() { return $!done }</pre>
<p>Note that this is not like declaring a public attribute, as some languages allow; you really get <i>both</i> 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.</p>
<p>Note that using the <span class="code">. </span> 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:</p>
<pre class="code">has Bool $.done is rw;</pre>
<p> <span class="indexed$additional-class"><a name="r22"></a></span> </p>
<p>The <span class="code">is rw </span> trait causes the generated accessor method to return something external code can modify to change the value of the attribute.</p>
<p>You can also supply default values to attributes (which works equally for those with and without accessors):</p>
<pre class="code">has Bool $.done = False;</pre>
<p>The assignment is carried out at object build time. The right-hand side is evaluated at that time, and can even reference earlier attributes:</p>
<pre class="code">has Task @!dependencies;
has $.ready = not @!dependencies;</pre>
<a name="t8.3"$class><h1>8.3 Static fields?</h1></a>
<p>Perl 6 has no <b>static</b> keyword. Nevertheless any class may declare anything that a module can, so making a scoped variable sounds like good idea.</p>
<pre class="code">class Singleton {
my Singleton $instance;
method new {!!!}
submethod instance {
$instance = Singleton.bless unless $instance;
$instance;
}
}
</pre>
<p>Class attributes defined by <a href="">my</a> or <a href="">our</a> 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 <a href="">use</a> keyword.</p>
<pre class="code">class HaveStaticAttr {
my Foo $.foo = some_complicated_subroutine;
}</pre>
<p>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.</p>
<a name="t8.4"$class><h1>8.4 Methods</h1></a>
<p> <span class="indexed$additional-class"><a name="r23"></a></span> <span class="indexed$additional-class"><a name="r24"></a></span> </p>
<p>While attributes give objects state, methods give objects behaviors. Let's ignore the <span class="code">new </span> method temporarily; it's a special type of method. Consider the second method, <span class="code">add-dependency </span> , which adds a new task to a task's dependency list.</p>
<pre class="code">method add-dependency(Task $dependency) {
push @!dependencies, $dependency;
}</pre>
<p> <span class="indexed$additional-class"><a name="r25"></a></span> </p>
<p>In many ways, this looks a lot like a <span class="code">sub </span> 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 <span class="code">Task </span> class can call this method with the <span class="code">. </span> method call operator. Second, a method places its invocant into the special variable <span class="code">self </span> .</p>
<p>The method itself takes the passed parameter -- which must be an instance of the <span class="code">Task </span> class -- and <span class="code">push </span> es it onto the invocant's <span class="code">@!dependencies </span> attribute.</p>
<p>The second method contains the main logic of the dependency handler:</p>
<pre class="code">method perform() {
unless $!done {
.perform() for @!dependencies;
&amp;!callback();
$!done = True;
}
}</pre>
<p>It takes no parameters, working instead with the object's attributes. First, it checks if the task has already completed by checking the <span class="code">$!done </span> attribute. If so, there's nothing to do.</p>
<p> <span class="indexed$additional-class"><a name="r26"></a></span> </p>
<p>Otherwise, the method performs all of the task's dependencies, using the <span class="code">for </span> construct to iterate over all of the items in the <span class="code">@!dependencies </span> attribute. This iteration places each item -- each a <span class="code">Task </span> object -- into the topic variable, <span class="code">$_ </span> . Using the <span class="code">. </span> method call operator without specifying an explicit invocant uses the current topic as the invocant. Thus the iteration construct calls the <span class="code">.perform() </span> method on every <span class="code">Task </span> object in the <span class="code">@!dependencies </span> attribute of the current invocant.</p>
<p>After all of the dependencies have completed, it's time to perform the current <span class="code">Task </span> 's task by invoking the <span class="code">&amp;!callback </span> attribute directly; this is the purpose of the parentheses. Finally, the method sets the <span class="code">$!done </span> attribute to <span class="code">True </span> , so that subsequent invocations of <span class="code">perform </span> on this object (if this <span class="code">Task </span> is a dependency of another <span class="code">Task </span> , for example) will not repeat the task.</p>
<a name="t8.4.1"$class><h2>8.4.1 Private Methods</h2></a>
<p>Analogous to attributes methods can be private. Private methods are declared with a prefixed exclamation mark. They are called with <span class="code">self! </span> followed by the methods 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 <span class="code">trusts </span> and the to be trusted class has to be declared already. Calling a private methods of another class requires an instance of that class and the fully qualified name of the method. Trust also applies to accessor methods of private attributes.</p>
<pre class="code">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();</pre>
<p>Trust relationships are not subject to inheritance. To trust the global namespace, the pseudo package <span class="code">GLOBAL </span> can be used.</p>
<a name="t8.5"$class><h1>8.5 Constructors</h1></a>
<p> <span class="indexed$additional-class"><a name="r27"></a></span> </p>
<p>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 <span class="code">new </span> from the base class <span class="code">Object </span> , but you are free to override <span class="code">new </span> , as this example does:</p>
<pre class="code">method new(&amp;callback, *@dependencies) {
return self.bless(:&amp;callback, :@dependencies);
}</pre>
<p> <span class="indexed$additional-class"><a name="r28"></a></span> <span class="indexed$additional-class"><a name="r29"></a></span> </p>
<p>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 <a href="">bless</a> method, also inherited from <a href="">Mu</a> . The <span class="code">bless </span> method expects a set of named parameters providing the initial values for each attribute.</p>
<p>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 <span class="code">Task </span> instances. The constructor captures these into the <span class="code">@dependencies </span> slurpy array and passes them as named parameters to <span class="code">bless </span> (note that <span class="code">:&amp;callback </span> uses the name of the variable -- minus the sigil -- as the name of the parameter).</p>
<p> <span class="indexed$additional-class"><a name="r30"></a></span> </p>
<p>Private attributes really are private. This means that <span class="code">bless </span> is not allowed to bind things to <span class="code">&amp;!callback </span> and <span class="code">@!dependencies </span> directly. To do this, we override the <span class="code">BUILD </span> submethod, which is called on the brand new object by <span class="code">bless </span> :</p>
<pre class="code">submethod BUILD(:&amp;!callback, :@!dependencies) { }</pre>
<p>Since <span class="code">BUILD </span> runs in the context of the newly created <span class="code">Task </span> object, it is allowed to manipulate those private attributes. The trick here is that the private attributes ( <span class="code">&amp;!callback </span> and <span class="code">@!dependencies </span> ) are being used as the bind targets for <span class="code">BUILD </span> 's parameters. Zero-boilerplate initialization! See <a href="/language/objects#Object_Construction">objects</a> for more information.</p>
<p>The <span class="code">BUILD </span> method is responsible for initializing all attributes, it must handle default values too:</p>
<pre class="code">has &amp;!callback;
has @!dependencies;
has Bool ($.done, $.ready);
submethod BUILD(
:&amp;!callback,
:@!dependencies,
:$!done = False,
:$!ready = not @!dependencies
) { }</pre>
<p>See <a href="/language/objects#Object_Construction">Object Construction</a> for more options to influence object construction and attribute initialization.</p>
<a name="t8.6"$class><h1>8.6 Consuming our class</h1></a>
<p>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:</p>
<pre class="code">my $eat = Task.new({ say 'eating dinner. NOM!' });</pre>
<p>An earlier section explained that declaring the class <span class="code">Task </span> 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; <span class="code">new </span> is an example, as it creates a new object rather than modifying or accessing an existing object.</p>
<p>Unfortunately, dinner never magically happens. It has dependent tasks:</p>
<pre class="code">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' })
)
);</pre>
<p>Notice how the custom constructor and sensible use of whitespace allows a layout which makes task dependencies clear.</p>
<p>Finally, the <span class="code">perform </span> method call recursively calls the <span class="code">perform </span> method on the various other dependencies in order, giving the output:</p>
<pre class="code">making some money
going to the store
buying food
cleaning kitchen
making dinner
eating dinner. NOM!</pre>
<a name="t8.7"$class><h1>8.7 Inheritance</h1></a>
<p>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.</p>
<p>TODO: the example here is rather bad, and needs to be replaced (or much improved). See <a href="">https://github.com/perl6/book/issues/58</a> for discussion.</p>
<pre class="code">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] ~ '.';
}
}
</pre>
<p>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.</p>
<pre class="code">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();
</pre>
<a name="t8.7.1"$class><h2>8.7.1 Overriding inherited methods</h2></a>
<p>Of course, classes can override methods and attributes defined by parent classes by defining their own. The example below demonstrates the <span class="code">Baker </span> class overriding the <span class="code">Cook </span> 's <span class="code">cook </span> method.</p>
<pre class="code">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
</pre>
<p>Because the dispatcher will see the <span class="code">cook </span> method on <span class="code">Baker </span> before it moves up to the parent class the <span class="code">Baker </span> 's <span class="code">cook </span> method will be called.</p>
<p>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.</p>
<a name="t8.7.2"$class><h2>8.7.2 Multiple inheritance</h2></a>
<p>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 approach to handling multiple inheritance.</p>
isn't Perl 5 also C3 now?
<pre class="code">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');
</pre>
<p>Now all the methods made available to the Programmer and the Cook classes are available from the GeekCook class.</p>
<p>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 <a href="/language/objects#Roles">Roles</a> .</p>
<a name="t8.8"$class><h1>8.8 Introspection</h1></a>
<p>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.</p>
<p>Given an object <span class="code">$o </span> , and the class definitions from the previous sections, we can ask it a few questions:</p>
<pre class="code">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;</pre>
<p>The output can look like this:</p>
<pre class="code">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</pre>
<p>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 <span class="code">Employee </span> or one that inherits from it, but not <span class="code">GeekCook </span> .</p>
<p>The <span class="code">.WHAT </span> method returns the type object associated with the object <span class="code">$o </span> , which tells us the exact type of <span class="code">$o </span> : in this case <span class="code">Programmer </span> .</p>
<p> <span class="code">$o.perl </span> returns a string that can be executed as Perl code, and reproduces the original object <span class="code">$o </span> . While this does not work perfectly in all cases <div class="marginale">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 <span class="code">.perl </span> at some point.</div> , it is very useful for debugging simple objects.</p>
<p> <span class="code">$o.^methods(:local) </span> produces a list of <a href="/type/Method">Method</a> s that can be called on <span class="code">$o </span> . The <span class="code">:local </span> named argument limits the returned methods to those defined in the <span class="code">Employee </span> class and excludes the inherited methods.</p>
<p>The syntax of calling a method with <span class="code">.^ </span> instead of a single dot means that it is actually a method call on the <i>meta class</i> , which is a class managing the properties of the <span class="code">Employee </span> class -- or any other class you are interested in. This meta class enables other ways of introspection too:</p>
<pre class="code">say $o.^attributes.join(', ');
say $o.^parents.map({ $_.^name }).join(', ');</pre>
<p>Finally <span class="code">$o.^name </span> calls the <span class="code">name </span> method on the meta object, which unsurprisingly returns the class name.</p>
<p>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 <span class="code">.WHAT </span> , seeing a construction recipe for it with <span class="code">.perl </span> , and so on, you'll get a good idea of what its return value is. With <span class="code">.^methods </span> you can learn what you can do with the class.</p>
<p>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.</p>
<a name="t9"><h1 class="title">9 Concurrency</h1></a> <p class="subtitle">Concurrency and Asynchronous Programming</p></a> <p>In common with most modern programming languages, Perl 6 is designed to <a href="http://en.wikipedia.org/wiki/Concurrent_computing">support concurrency</a> (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).</p>
<p>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.</p>
I'm not quite clear which specific features should be included below
hyper-operators, autothreading junctions?
<p>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. <a href="">Thread</a> and <a href="">Scheduler</a> ) and use the higher-level interfaces.</p>
<a name="t9.1"$class><h1>9.1 High-level APIs</h1></a>
<a name="t9.1.1"$class><h2>9.1.1 Promises</h2></a>
<p>A <a href="/type/Promise">Promise</a> (also called <i>future</i> 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.</p>
<pre class="code">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"
</pre>
<p>Promises gain much of their power by being composable, for example by chaining:</p>
<pre class="code">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</pre>
<p>Here the <a href="/type/Promise#method_then">then</a> method schedules code to be executed when the first <a href="">Promise</a> is kept or broken, itself returning a new <a href="">Promise</a> which will be kept with the result of the code when it is executed (or broken if the code fails.) <span class="code">keep </span> changes the status of the promise to <span class="code">Kept </span> setting the result to the positional argument. <span class="code">result </span> 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 <span class="code">keep </span> , ) otherwise it will throw an exception based on the value passed to <span class="code">break </span> . The latter behaviour is illustrated with:</p>
<pre class="code">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</pre>
<p>Here the <span class="code">break </span> will cause the code block of the <span class="code">then </span> to throw an exception when it calls the <span class="code">result </span> 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 <a href="">Exception</a> object will then be available from <span class="code">cause </span> . If the promise had not been broken <span class="code">cause </span> would raise a <a href="">X::Promise::CauseOnlyValidOnBroken</a> exception.</p>
<p>A <a href="">Promise</a> can also be scheduled to be automatically kept at a future time:</p>
<pre class="code">my $promise1 = Promise.in(5);
my $promise2 = $promise1.then(-> $v { say $v.status; 'Second Result' });
say $promise2.result;</pre>
<p>The <a href="/type/Promise#method_in">method in</a> creates a new promise and schedules a new task to call <span class="code">keep </span> on it no earlier than the supplied number of seconds, returning the new <a href="">Promise</a> object.</p>
<p>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 <a href="/type/Promise#method_start">start method</a> provides a shortcut for that:</p>
<pre class="code">my $promise = Promise.start(
{ my $i = 0; for 1 .. 10 { $i += $_ }; $i}
);
say $promise.result; # 55</pre>
<p>Here the <span class="code">result </span> of the promise returned is the value returned from the code. Similarly if the code fails (and the promise is thus broken), then <span class="code">cause </span> will be the <a href="">Exception</a> object that was thrown:</p>
<pre class="code">my $promise = Promise.start({ die "Broken Promise" });
try $promise.result;
say $promise.cause;</pre>
<p>This is considered to be such a commonly required pattern that it is also provided as subroutines:</p>
<pre class="code">my $promise = start {
my $i = 0;
for 1 .. 10 {
$i += $_
}
$i
}
my $result = await $promise;
say $result;</pre>
<p> <span class="code">await </span> is almost equivalent to calling <span class="code">result </span> on the promise object returned by <span class="code">start </span> but it will also take a list of promises and return the result of each:</p>
<pre class="code">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</pre>
<p>In addition to <span class="code">await </span> , two class methods combine several <a href="">Promise</a> objects into a new promise: <span class="code">allof </span> returns a promise that is kept when all the original promises are kept or broken when one of them is broken:</p>
<pre class="code">my $promise = Promise.allof(
Promise.in(2),
Promise.in(3)
);
await $promise;
say "All done"; # Should be not much more than three seconds later</pre>
<p>And <span class="code">anyof </span> returns a new promise that will be kept when any of the original promises is kept or broken when any of them is broken:</p>
<pre class="code">my $promise = Promise.anyof(
Promise.in(3),
Promise.in(8600)
);
await $promise;
say "All done"; # Should be about 3 seconds later</pre>
<p>Unlike <span class="code">await </span> 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.</p>
<p>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 <a href="/type/Promise#method_vow">method vow</a> , which returns a <a href="">Vow</a> 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 <a href="">X::Promise::Vowed</a> will be thrown, as long as the vow object is kept private, the status of the promise is safe:</p>
<pre class="code">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;</pre>
<p>The methods that return a promise that will be kept or broken automatically such as <span class="code">in </span> or <span class="code">start </span> will do this, so it is not necessary to do it for these.</p>
<a name="t9.1.2"$class><h2>9.1.2 Supplies</h2></a>
<p>A <a href="">Supply</a> 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.</p>
<p>At its simplest, a <a href="">Supply</a> is a message stream that can have multiple subscribers created with the method <span class="code">tap </span> on to which data items can be placed with <span class="code">emit </span> .</p>
<p>The <a href="">Supply</a> can either be <span class="code">live </span> or <span class="code">on-demand </span> . A <span class="code">live </span> <a href="">Supply</a> is created by the <a href="">Supplier</a> factory, each emitted value is passed to all the active tappers as they are added:</p>
<pre class="code">my $supplier = Supplier.new;
my $supply = $supplier.Supply;
$supply.tap( -> $v { say $v });
for 1 .. 10 {
$supplier.emit($_);
}</pre>
<p>Note that the <span class="code">tap </span> is called on a <a href="">Supply</a> object created by the <a href="">Supplier</a> and new values are emitted on the <a href="">Supplier</a> .</p>
<p>Or alternatively as an <span class="code">on-demand </span> <a href="">Supply</a> created by the <span class="code">supply </span> keyword:</p>
<pre class="code">my $supply = supply {
for 1 .. 10 {
emit($_);
}
}
$supply.tap( -> $v { say $v });</pre>
<p>In this case the code in the supply block is executed every time the <a href="">Supply</a> returned by <span class="code">supply </span> is tapped, as demonstrated by:</p>
<pre class="code">my $supply = supply {
for 1 .. 10 {
emit($_);
}
}
$supply.tap( -> $v { say "First : $v" });
$supply.tap( -> $v { say "Second : $v" });</pre>
<p>The <span class="code">tap </span> method returns a <a href="">Tap</a> 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:</p>
<pre class="code">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");</pre>
<p>Calling <span class="code">done </span> on the supply object calls the <span class="code">done </span> callback that may be specified for any taps, but does not prevent any further events being emitted to the stream, or taps receiving them.</p>
<p>The method <span class="code">interval </span> returns a new <span class="code">on-demand </span> 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 :</p>
<pre class="code">my $supply = Supply.interval(2);
$supply.tap(-> $v { say $v });
sleep 10;</pre>
<p>This could also be written using the <span class="code">react </span> keyword:</p>
<pre class="code">react {
whenever Supply.interval(2) -> $v {
say $v;
done() if $v == 4;
}
}</pre>
<p>Here the <span class="code">whenever </span> keyword creates a tap on the <a href="">Supply</a> from the provided block. The <span class="code">react </span> block is exited when <span class="code">done() </span> is called in one of the taps.</p>
<p>A second argument can be supplied to <span class="code">interval </span> which specifies a delay in seconds before the first event is fired. Each tap of a supply created by <span class="code">interval </span> has its own sequence starting from 0, as illustrated by the following:</p>
<pre class="code">my $supply = Supply.interval(2);
$supply.tap(-> $v { say "First $v" });
sleep 6;
$supply.tap(-> $v { say "Second $v"});
sleep 10;</pre>
<p>An <span class="code">on-demand </span> <a href="">Supply</a> can also be created from a list of values that will be emitted in turn, thus the first <span class="code">on-demand </span> example could be written as:</p>
<pre class="code">react {
whenever Supply.from-list(1..10) -> $v {
say $v;
}
}</pre>
<p>An existing supply object can be filtered or transformed, using the methods <span class="code">grep </span> and <span class="code">map </span> respectively, to create a new supply in a manner like the similarly named list methods: <span class="code">grep </span> returns a supply such that only those events emitted on the source stream for which the <span class="code">grep </span> condition is true is emitted on the second supply:</p>
<pre class="code">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($_);
}</pre>
<p> <span class="code">map </span> 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 <span class="code">map </span> is emitted:</p>
<pre class="code">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($_);
}</pre>
<a name="t9.1.3"$class><h2>9.1.3 Channels</h2></a>
<p>A <a href="">Channel</a> 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 <a href="">Channel</a> 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 <a href="">Supply</a> .</p>
<p>An item is queued onto the <a href="">Channel</a> with the <a href="/type/Channel#method_send">method send</a> , and the <a href="/type/Channel#method_receive">method receive</a> removes an item from the queue and returns it, blocking until a new item is sent if the queue is empty:</p>
<pre class="code">my $channel = Channel.new;
$channel.send('Channel One');
say $channel.receive; # 'Channel One'</pre>
<p>If the channel has been closed with the <a href="/type/Channel#method_close">method close</a> then any <span class="code">send </span> will cause the exception <a href="">X::Channel::SendOnClosed</a> to be thrown, and a <span class="code">receive </span> will throw a <a href="">X::Channel::ReceiveOnClose</a> if there are no more items on the queue.</p>
<p>The <a href="/type/Channel#method_list">method list</a> returns all the items on the <a href="">Channel</a> and will block until further items are queued unless the channel is closed:</p>
<pre class="code">my $channel = Channel.new;
await (^10).map: -> $r {
start {
sleep $r;
$channel.send($r);
}
}
$channel.close;
for $channel.list -> $r {
say $r;
}</pre>
<p>There is also the non-blocking <a href="/type/Channel#method_poll">method poll</a> which returns an available item from the channel or <a href="">Nil</a> 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:</p>
<pre class="code">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;</pre>
<p>The <a href="/type/Channel#method_closed">method closed</a> returns a <a href="">Promise</a> that will be kept (and consequently will evaluate to True in a boolean context,) when the channel is closed.</p>
<p>Channels can be used in place of the <a href="">Supply</a> in the <span class="code">whenever </span> of a <span class="code">react </span> block described earlier:</p>
<pre class="code">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;</pre>
<p>It is also possible to obtain a <a href="">Channel</a> from a <a href="">Supply</a> using the <a href="/type/Supply#method_Channel">Supply method</a> which returns a <a href="">Channel</a> which is fed by a <span class="code">tap </span> on the <a href="">Supply</a> :</p>
<pre class="code">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;</pre>
<p> <span class="code">Channel </span> will return a different <a href="">Channel</a> fed with the same data each time it is called. This could be used, for instance, to fan-out a <a href="">Supply</a> to one or more <a href="">Channel</a> s to provide for different interfaces in a program.</p>
<a name="t9.1.4"$class><h2>9.1.4 Proc::Async</h2></a>
<p> <a href="">Proc::Async</a> builds on the facilities described to run and interact with an external program asynchronously:</p>
<pre class="code">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.</pre>
<p>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 <a href="/type/Proc::Async#method_start">start</a> is called, which will return a <a href="">Promise</a> that will be kept when the program exits. The standard output and standard error of the program are available as <a href="">Supply</a> objects from the methods <a href="/type/Proc::Async#method_stdout">stdout</a> and <a href="/type/Proc::Async#method_stderr">stderr</a> respectively which can be tapped as required.</p>
<p>If you want to write to the standard input of the program you can supply the <span class="code">:w </span> adverb to the constructor and use the methods <a href="/type/Proc::Async#method_write">write</a> , <a href="/type/Proc::Async#method_print">print</a> or <a href="/type/Proc::Async#method_say">say</a> to write to the opened pipe once the program has been started:</p>
<pre class="code">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.</pre>
<p>Some programs (such as <span class="code">grep </span> without a file argument in this example, ) won't exit until their standard input is closed so <a href="/type/Proc::Async#method_close-stdin">close-stdin</a> can be called when you are finished writing to allow the <a href="">Promise</a> returned by <span class="code">start </span> to be kept.</p>
<a name="t9.2"$class><h1>9.2 Low-level APIs</h1></a>
<a name="t9.2.1"$class><h2>9.2.1 Threads</h2></a>
<p>The lowest level interface for concurrency is provided by <a href="">Thread</a> . 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.</p>
<p>A thread can either be created and then actually run later:</p>
<pre class="code">my $thread = Thread.new(code => { for 1 .. 10 -> $v { say $v }});
# ...
$thread.run;</pre>
<p>Or can be created and run at a single invocation:</p>
<pre class="code">my $thread = Thread.start({ for 1 .. 10 -> $v { say $v }});</pre>
<p>In both cases the completion of the code encapsulated by the <a href="">Thread</a> object can be waited on with the <span class="code">finish </span> method which will block until the thread completes:</p>
<pre class="code">$thread.finish;</pre>
<p>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.</p>
<a name="t9.2.2"$class><h2>9.2.2 Schedulers</h2></a>
<p>The next level of the concurrency API is supplied by classes that implement the interface defined by the role <a href="">Scheduler</a> . 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 <a href="">Proc::Async</a> , <a href="">Promise</a> and <a href="">Supply</a> allow you to explicitly supply a scheduler.</p>
<p>The current default global scheduler is available in the variable <span class="code">$*SCHEDULER </span> .</p>
<p>The primary interface of a scheduler (indeed the only method required by the <a href="">Scheduler</a> interface) is the <span class="code">cue </span> method:</p>
<pre class="code">method cue(:&amp;code, Instant :$at, :$in, :$every, :$times = 1; :&amp;catch)</pre>
<p>This will schedule the <a href="">Callable</a> in <span class="code">&amp;code </span> to be executed in the manner determined by the adverbs (as documented in <a href="">Scheduler</a> ) using the execution scheme as implemented by the scheduler. For example:</p>
<pre class="code">my $i = 0;
my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );
sleep 20;</pre>
<p>Assuming that the <span class="code">$*SCHEDULER </span> 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 <a href="">Cancellation</a> object which can be used to cancel the scheduled execution before normal completion:</p>
<pre class="code">my $i = 0;
my $cancellation = $*SCHEDULER.cue({ say $i++}, every => 2 );
sleep 10;
$cancellation.cancel;
sleep 10;</pre>
<p>should only output 0 to 5,</p>
<p>Despite the apparent advantage the <a href="">Scheduler</a> interface provides over that of <a href="">Thread</a> 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.</p>
<p>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.</p>
<a name="t9.2.2.1"$class><h3>9.2.2.1 ThreadPoolScheduler</h3></a>
<p>The <a href="">ThreadPoolScheduler</a> 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 <span class="code">cue </span> may queue the code until such time as a thread becomes available.</p>
<p>Rakudo allows the maximum number of threads allowed in the default scheduler to be set by the environment variable <span class="code">RAKUDO_MAX_THREADS </span> at the time the program is started.</p>
<a name="t9.2.2.2"$class><h3>9.2.2.2 CurrentThreadScheduler</h3></a>
<p>The <a href="">CurrentThreadScheduler</a> is a very simple scheduler that will always schedule code to be run straight away on the current thread. The implication is that <span class="code">cue </span> on this scheduler will block until the code finishes execution, limiting its utility to certain special cases such as testing.</p>
<a name="t9.2.3"$class><h2>9.2.3 Locks</h2></a>
<p>The class <a href="">Lock</a> 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 ( <a href="">Promise</a> , <a href="">Supply</a> and <a href="">Channel</a> ,) use a <a href="">Lock</a> where required it is unlikely that user code will need to use a <a href="">Lock</a> directly.</p>
<p>The primary interface to <a href="">Lock</a> is the method <a href="/type/Lock#method_protect">protect</a> which ensures that a block of code (commonly called a "critical section",) is only executed in one thread at a time:</p>
<pre class="code">my $lock = Lock.new;
my $a = 0;
await (^10).map: {
start {
$lock.protect({
my $r = rand;
sleep $r;
$a++;
});
}
}
say $a; # 10</pre>
<p> <span class="code">protect </span> returns whatever the code block returns.</p>
<p>Because <span class="code">protect </span> will block any threads that are waiting to execute the critical section the code should be as quick as possible.</p>
<a name="t9.3"$class><h1>9.3 Safety Concerns</h1></a>
<p>Some shared data concurrency issues are less obvious than others. For a good general write-up on this subject see this <a href="https://6guts.wordpress.com/2014/04/17/racing-to-writeness-to-wrongness-leads/">blog post</a> .</p>
<p>One particular issue of note is when container autovivification or extension takes place. When an <a href="">Array</a> or a <a href="">Hash</a> entry is initially assigned the underlying structure is altered and that operation is not async safe. For example, in this code:</p>
<pre class="code">my @array;
my $slot := @array[20];
$slot = 'foo';</pre>
<p>The third line is the critical section as that is when the array is extended. The simplest fix is to use a &lt;Lock> to protect the critical section . A possibly better fix would be to refactor the code so that sharing a container is not necessary.</p>
<a name="t10"><h1 class="title">10 Containers</h1></a> <p class="subtitle">A low-level explanation of Perl 6 containers</p></a> <p>This article started as a conversion on IRC explaining the difference between the <span class="code">Array </span> and the <span class="code">List </span> type in Perl 6. It explains the levels of indirection involved in dealing with variables and container elements.</p>
<a name="t10..1"$class><h2>10..1 What is a variable?</h2></a>
<p>Some people like to say "everything is an object", but in fact a variable is not a user-exposed object in Perl 6.</p>
<p>When the compiler encounters a variable declaration like <span class="code">my $x </span> , 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.</p>
<p>At run time, a variable appears as an entry in a <i>lexical pad</i> , or <i>lexpad</i> for short. This is a per-scope data structure that stores a pointer for each variable.</p>
<p>In the case of <span class="code">my $x </span> , the lexpad entry for the variable <span class="code">$x </span> is a pointer to an object of type <span class="code">Scalar </span> , usually just called <i>the container</i> .</p>
<a name="t10..2"$class><h2>10..2 Scalar containers</h2></a>
<p>Although objects of type <span class="code">Scalar </span> are everywhere in Perl 6, you usually never see them directly as objects, because most operations <i>decontainerize</i> , which means they act on the <span class="code">Scalar </span> container's contents instead of the container itself.</p>
<p>In code like</p>
<pre class="code">my $x = 42;
say $x;</pre>
<p>the assignment <span class="code">$x = 42 </span> stores a pointer to the <span class="code">Int </span> object 42 in the scalar container to which the lexpad entry for <span class="code">$x </span> points.</p>
<p>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 <span class="code">Scalar </span> it means "replace the previously stored value with the new one".</p>
<p>Note that subroutine signatures allow passing around of containers:</p>
<pre class="code">sub f($a is rw) {
$a = 23;
}
my $x = 42;
f($x);
say $x; # 23</pre>
<p>Inside the subroutine, the lexpad entry for <span class="code">$a </span> points to the same container that <span class="code">$x </span> points to outside the subroutine. Which is why assignment to <span class="code">$a </span> also modifies the contents of <span class="code">$x </span> .</p>
<p>Likewise a routine can return a container if it is marked as <span class="code">is rw </span> :</p>
<pre class="code">my $x = 23;
sub f() is rw { $x };
f() = 42;
say $x; # 42</pre>
<p>For explicit returns, <span class="code">return-rw </span> instead of <span class="code">return </span> must be used.</p>
<p>Returning a container is how <span class="code">is rw </span> attribute accessors work. So</p>
<pre class="code">class A {
has $.attr is rw;
}</pre>
<p>is equivalent to</p>
<pre class="code">class A {
has $!attr;
method attr() is rw { $!attr }
}</pre>
<p>Scalar containers are transparent to type checks and most kinds of read-only accesses. A <span class="code">.VAR </span> makes them visible:</p>
<pre class="code">my $x = 42;
say $x.^name; # Int
say $x.VAR.^name; # Scalar</pre>
<p>And <span class="code">is rw </span> on a parameter requires the presence of a writable Scalar container:</p>
<pre class="code">sub f($x is rw) { say $x };
f 42; # Parameter '$x' expected a writable container, but got Int value</pre>
<a name="t10..3"$class><h2>10..3 Binding</h2></a>
<p>Next to assignment, Perl 6 also supports <i>binding</i> with the <span class="code">:= </span> 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</p>
<pre class="code">my $x := 42;</pre>
<p>then the lexpad entry for <span class="code">$x </span> directly points to the <span class="code">Int </span> 42. Which means that you cannot assign to it anymore:</p>
<pre class="code">$ perl6 -e 'my $x := 42; $x = 23'
Cannot modify an immutable value
in block at -e:1</pre>
<p>You can also bind variables to other variables:</p>
<pre class="code">my $a = 0;
my $b = 0;
$a := $b;
$b = 42;
say $a; # 42</pre>
<p>Here, after the initial binding, the lexpad entries for <span class="code">$a </span> and <span class="code">$b </span> both point to the same scalar container, so assigning to one variable also changes the contents of the other.</p>
<p>You've seen this situation before: it is exactly what happened with the signature parameter marked as <span class="code">is rw </span> .</p>
<p>Sigilless variabes also bind by default and so do parameters with the trait <span class="code">is raw </span> .</p>
<pre class="code">my $a = 42;
my \b = $a;
b++;
say $a; # 43
sub f($c is raw) { $c++ }
f($a);
say $a; # 44</pre>
<a name="t10..4"$class><h2>10..4 Scalar containers and listy things</h2></a>
<p>There are a number of positional container types with slightly different semantics in Perl 6. The most basic one is <a href="/type/List">List</a> It is created by the comma operator.</p>
<pre class="code">say (1, 2, 3).^name; # List</pre>
<p>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:</p>
<pre class="code">my $x = 42;
($x, 1, 2)[0] = 23;
say $x; # 23
($x, 1, 2)[1] = 23; # Error: Cannot modify an immutable value</pre>
<p>So the list doesn't care about whether its elements are values or containers, they just store and retrieve whatever was given to them.</p>
<p>Lists can also be lazy, so elements at the end are generated on demand from an iterator.</p>
<p>An <span class="code">Array </span> is just like a list, except that it forces all its elements to be containers, which means that you can always assign to elements:</p>
<pre class="code">my @a = 1, 2, 3;
@a[0] = 42;
say @a; # 42 2 3</pre>
<p> <span class="code">@a </span> actually stores three scalar containers. <span class="code">@a[0] </span> returns one of them, and the assignment operator replaces the integer value stored in that container with the new one, <span class="code">42 </span> .</p>
<p>An <a href="">Array</a> also has methods that can change the number of elements, notably <span class="code">push </span> , <span class="code">pop </span> , <span class="code">shift </span> , <span class="code">unshift </span> and <span class="code">splice </span> .</p>
<a name="t10..5"$class><h2>10..5 Assigning and binding to array variables</h2></a>
<p>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).</p>
<p>Nevertheless, it's easy to observe how different they are:</p>
<pre class="code">my $x = 42; say $x.^name; # Int
my @a = 42; say @a.^name; # Array</pre>
<p>This is because the <span class="code">Scalar </span> container type hides itself well, but <span class="code">Array </span> makes no such effort. Also assignment to an array variable is coercive, so you can assign a non-array value to an array variable.</p>
<p>To place a non- <span class="code">Array </span> into an array variable, binding works:</p>
<pre class="code">my @a := (1, 2, 3);
say @a.WHAT; # (List)</pre>
<a name="t10..6"$class><h2>10..6 Binding to array elements</h2></a>
<p>As a curious side note, Perl 6 supports binding to array elements:</p>
<pre class="code">my @a = (1, 2, 3);
@a[0] := my $x;
$x = 42;
say @a; # 42 2 3</pre>
<p>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).</p>
<p>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 <span class="code">BIND-KEY </span> ) is called on the array. This method handles binding to array elements.</p>
<p>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.</p>
<pre class="code">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.</pre>
<p>Operations that mix Lists and Arrays generally protect against such a thing happening accidentally.</p>
<a name="t10..7"$class><h2>10..7 Flattening, items and containers</h2></a>
<p>The <span class="code">% </span> and <span class="code">@ </span> sigils in Perl 6 generally indicate multiple values to an iteration construct, whereas the <span class="code">$ </span> sigil indicates only one value.</p>
<pre class="code">my @a = 1, 2 3;
for @a { }; # 3 iterations
my $a = (1, 2, 3);
for $a { }; # 1 iteration</pre>
<p>Contrary to earlier versions of Perl 6, and to Perl 5, <span class="code">@ </span> -sigiled variables do not flatten in list context:</p>
<pre class="code">my @a = 1, 2, 3;
my @b = @a, 4, 5;
say @b.elems; # 3</pre>
<p>There are operations that flatten out sublists that are not inside a scalar container: slurpy parameters ( <span class="code">*@a </span> ) and explicit calls to <span class="code">flat </span> :</p>
<pre class="code">my @a = 1, 2, 3;
say (flat @a, 4, 5).elems; # 5
sub f(*@x) { @x.elems };
say f @a, 4, 5; # 5</pre>
<p>As hinted above, scalar containers prevent that flattening:</p>
<pre class="code">sub f(*@x) { @x.elems };
say f $@a, 4, 5; # 3</pre>
<p>The <span class="code">@ </span> character can also be used as a prefix to remove a scalar container:</p>
<pre class="code">my $x = (1, 2, 3);
.say for @$x; # 3 iterations</pre>
<p>Methods generally don't care whether their invocant is in a scalar, so</p>
<pre class="code">my $x = (1, 2, 3);
$x.map(*.say); # 3 iterations</pre>
<p>maps over a list of three elements, not of one.</p>
<a name="t10..8"$class><h2>10..8 Custom containers</h2></a>
<p>To provide custom containers Perl 6 provides the class <span class="code">Proxy </span> . 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 then the type of the variable it is bound to. We can use type captures to work with types in Perl 6.</p>
<pre class="code">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</pre>
<a name="t11"><h1 class="title">11 Control Flow</h1></a> <p class="subtitle">Statements used to control the flow of execution</p></a> <a name="t11..1"$class><h2>11..1 statements </h2></a>
<p>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.</p>
<pre class="code">say "Hello";
say "World";</pre>
<p>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:</p>
<pre class="code">say
"Hello"; say "World";</pre>
<a name="t11..2"$class><h2>11..2 blocks </h2></a>
<p>Like many languages, Perl 6 uses <span class="code">blocks </span> enclosed by <span class="code">{ </span> and <span class="code">} </span> 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 <span class="code">} </span> .</p>
<pre class="code">{ say "Hello"; say "World" }</pre>
<p>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.</p>
<pre class="code">say 1; # says "1"
{ say 2; say 3 }; # says "2" then says "3"
say 4; # says "4"</pre>
<p>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 <a href="/language/functions#Blocks and Lambdas">elsewhere</a> . For now it is just important to understand when blocks run and when they do not:</p>
<pre class="code">say "We get here"; { say "then here." }; { say "not here"; 0; } or die;</pre>
<p>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 <span class="code">Block </span> 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 <span class="code">Block </span> object, so it just gets thrown away.</p>
<p>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.</p>
<p>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:</p>
<pre class="code"># 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"</pre>
<p>...but:</p>
<pre class="code">{ 42.say } { 43.say } #-> Syntax error
{ 42.say; } { 43.say } #-> Also a syntax error, of course</pre>
<p>So, be careful when you backspace in a line-wrapping editor:</p>
<pre class="code">{ "Without semicolons line-wrapping can be a bit treacherous.".say } \
{ 43.say } #-> Syntax error</pre>
<p>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.</p>
<a name="t11..3"$class><h2>11..3 do </h2></a>
<p>The simplest way to run a block where it cannot be a stand-alone statement is by writing <span class="code">do </span> before it:</p>
<pre class="code"># This dies half of the time
do { say "Heads I win, tails I die."; Bool.pick } or die; say "I win.";</pre>
<p>Note that you need a space between the do and the block.</p>
<p>The whole <span class="code">do {...} </span> 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:</p>
<pre class="code">False and do { 42.say };</pre>
<p>...will not say 42. However, the block is only evaluated once each time the expression it is contained in is evaluated:</p>
<pre class="code"># This says "(..1 ..2 ..3)" not "(..1 ...2 ....3)"
my $f = "."; say do { $f ~= "." } X~ 1,2,3;</pre>
<p>In other words, it follows the same reification rules as everything else.</p>
<p>Technically, <span class="code">do </span> is a loop which runs exactly one iteration.</p>
<p>A <span class="code">do </span> 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:</p>
<pre class="code">3, do if 1 { 2 } ; #-> 3, 2
3, (if 1 { 2 }) ; #-> 3, 2
3, if 1 { 2 } ; # Syntax error</pre>
<p>...which brings us to <span class="code">if </span> .</p>
<a name="t11..4"$class><h2>11..4 if </h2></a>
<p>To conditionally run a block of code, use an <span class="code">if </span> followed by a condition. The condition, an expression, will be evaluated immediately after the statement before the <span class="code">if </span> finishes. The block attached to the condition will only be evaluated if the condition means True when coerced to <span class="code">Bool </span> . Unlike some languages the condition does not have to be parenthesized, instead the <span class="code">{ </span> and <span class="code">} </span> around the block are mandatory:</p>
<pre class="code">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"</pre>
<p>There is also a form of <span class="code">if </span> 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:</p>
<pre class="code">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</pre>
<p>The statement modifier form is probably best used sparingly.</p>
<p>The <span class="code">if </span> statement itself will either <a href="/type/Slip">slip</a> us an empty list, if it does not run the block, or it will return the value which the block produces:</p>
<pre class="code">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)"</pre>
<p>For the statement modifier it is the same, except you have the value of the statement instead of a block:</p>
<pre class="code">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</pre>
<p>The <span class="code">if </span> does not change the topic ( <span class="code">$_ </span> ) by default. In order to access the value which the conditional expression produced, you have to ask for it more strongly:</p>
<pre class="code">$_ = 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"</pre>
<a name="t11..4.1"$class><h3>11..4.1 else/elsif </h3></a>
<p>A compound conditional may be produced by following an <span class="code">if </span> conditional with <span class="code">else </span> to provide an alternative block to run when the conditional expression is false:</p>
<pre class="code">if 0 { say "no" } else { say "yes" } ; # says "yes"
if 0 { say "no" } else{ say "yes" } ; # syntax error, space is required</pre>
<p>The <span class="code">else </span> cannot be separated from the conditional statement by a semicolon, but as a special case, it is OK to have a newline.</p>
<pre class="code">if 0 { say "no" }; else { say "yes" } ; # syntax error
if 0 { say "no" }
else { say "yes" } ; # says "yes"</pre>
<p>Additional conditions may be sandwiched between the <span class="code">if </span> and the <span class="code">else </span> using <span class="code">elsif </span> . 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 <span class="code">elsif </span> instead of an <span class="code">else </span> if you want.</p>
<pre class="code">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"</pre>
<p>You cannot use the statement modifier form with <span class="code">else </span> or <span class="code">elsif </span> :</p>
<pre class="code">42.say if 0 else { 43.say } # syntax error</pre>
<p>All the same rules for semicolons and newlines apply, consistently</p>
<pre class="code">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"</pre>
<p>The whole thing either <a href="/type/Slip">slips</a> us an empty list (if no blocks were run) or returns the value produced by the block that did run:</p>
<pre class="code">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)"</pre>
<p>It's possible to obtain the value of the previous expression inside an <span class="code">else </span> , which could be from <span class="code">if </span> or the last <span class="code">elsif </span> if any are present:</p>
<pre class="code">$_ = 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"</pre>
<a name="t11..4.2"$class><h3>11..4.2 unless </h3></a>
<p>When you get sick of typing "if not (X)" you may use <span class="code">unless </span> to invert the sense of a conditional statement. You cannot use <span class="code">else </span> or <span class="code">elsif </span> with <span class="code">unless </span> because that ends up getting confusing. Other than those two differences <span class="code">unless </span> works the same as <a href="">if</a> :</p>
<pre class="code">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)"</pre>
<a name="t11..4.3"$class><h3>11..4.3 with, orwith, without </h3></a>
<p>The <span class="code">with </span> statement is like <span class="code">if </span> but tests for definedness rather than truth. In addition, it topicalizes on the condition, much like <span class="code">given </span> :</p>
<pre class="code">with "abc".index("a") { .say } # prints 0</pre>
<p>Instead of <span class="code">elsif </span> , <span class="code">orwith </span> may be used to chain definedness tests:</p>
<pre class="code"># 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" }</pre>
<p>You may intermix <span class="code">if </span> -based and <span class="code">with </span> -based clauses.</p>
<pre class="code"># This says "Yes"
if 0 { say "No" } orwith Nil { say "No" } orwith 0 { say "Yes" };</pre>
<p>As with <span class="code">unless </span> , you may use <span class="code">without </span> to check for undefinedness, but you may not add an <span class="code">else </span> clause:</p>
<pre class="code">without $answer { fail "Got: $_" }</pre>
<p>There are also <span class="code">with </span> and <span class="code">without </span> statement modifiers:</p>
<pre class="code">return 42 with $answer;
.throw without $answer;</pre>
<a name="t11..5"$class><h2>11..5 for </h2></a>
<p>The <span class="code">for </span> 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.</p>
<pre class="code">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
</pre>
<p>Pointy block syntax or a <a href="/language/variables#The C<^">placeholder</a> Twigil> may be used to name the parameter, of course.</p>
<pre class="code">for @foo -> $item { print $item }
for @foo { print $^item } # same thing
</pre>
<p>Multiple parameters can be declared, in which case the iterator takes as many elements from the list as needed before running the block.</p>
<pre class="code">for %hash.kv -> $key, $value { print "$key => $value\n" }
for 1, 1.1, 2, 2.1 { say "$^x &lt; $^y" } # says "1 &lt; 1.1" then says "2 &lt; 2.1"
</pre>
<p>A <span class="code">for </span> 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:</p>
<pre class="code">for $*IN.lines -> $line {...}
</pre>
<p>Iteration variables are always lexical, so you don't need to use <span class="code">my </span> to give them the appropriate scope. Also, they are read-only aliases. If you need them to be read-write, use <span class="code">&lt;-> </span> instead of <span class="code">-> </span> . If you need to make <span class="code">$_ </span> read-write in a for loop, do so explicitly.</p>
<pre class="code">for @cars &lt;-> $_ {...}
</pre>
<p>A for loop can produce a a <span class="code">List </span> 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:</p>
<pre class="code">(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
</pre>
<a name="t11..6"$class><h2>11..6 gather/take </h2></a>
<p> <span class="code">gather </span> is a statement or block prefix that returns a <a href="/type/Seq">sequence</a> of values. The values come from calls to <span class="code">take </span> in the dynamic scope of the <span class="code">gather </span> block.</p>
<pre class="code">my @a = gather {
take 1;
take 5;
take 42;
}
say join ', ', @a; # 1, 5, 42</pre>
<p> <span class="code">gather/take </span> generates values lazily, so the <span class="code">gather </span> block generally runs only until it hits the first <span class="code">take </span> . Code after the first <span class="code">take </span> is executed as soon as the next value is consumed from the returned sequence.</p>
<p>For example</p>
<pre class="code">my \vals = gather {
take 1;
say "Produced a value";
take 2;
}
say vals[0];
say 'between consumption of two values';
say vals[1];</pre>
<p>produces this output:</p>
<pre class="code">1
between consumption of two values
Produced a value
2</pre>
<p> <span class="code">gather/take </span> is scoped dynamically, so you can call <span class="code">take </span> from subs or methods that are called from within <span class="code">gather </span> :</p>
<pre class="code">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)</pre>
<a name="t11..7"$class><h2>11..7 given </h2></a>
<p>The <span class="code">given </span> statement is Perl 6's topicalizing keyword in a similar way that <span class="code">switch </span> topicalizes in languages such as C. In other words, <span class="code">given </span> sets <span class="code">$_ </span> inside the following block. The keywords for individual cases are <span class="code">when </span> and <span class="code">default </span> . The usual idiom looks like this:</p>
<pre class="code">given EXPR {
when EXPR { ... }
when EXPR { ... }
default { ... }
}</pre>
<p>The <span class="code">given </span> statement is often used alone:</p>
<pre class="code">given EXPR { .say; .Numeric; }</pre>
<p>This is a lot more understandable than:</p>
<pre class="code">{ .say; .Numeric; }(EXPR)</pre>
<a name="t11..7.1"$class><h3>11..7.1 default and when </h3></a>
<p>A block containing a <span class="code">default </span> statement will be left immediately when the sub-block after the <span class="code">default </span> statement is left. It is as though the rest of the statements in the block are skipped.</p>
<pre class="code">given 42 {
"This says".say;
$_ == 42 and ( default { "This says, too".say; 43; } );
"This never says".say;
}
# The above block evaluates to 43</pre>
<p>A <span class="code">when </span> statement will also do this (but a <span class="code">when </span> statement modifier will <i>not</i> .)</p>
<p>In addition, <span class="code">when </span> statements <span class="code">smartmatch </span> the topic ( <span class="code">$_ </span> ) against a supplied expression such that it is possible to check against values, regular expressions, and types when specifying a match.</p>
<pre class="code">for 42, 43, "foo", 44 {
when Int { .say }
default { say "Not an Int" }
}
#-> 42 43 Not an Int 44</pre>
<p>In this form, the <span class="code">given </span> / <span class="code">when </span> construct acts much like a set of <span class="code">if </span> / <span class="code">elsif </span> / <span class="code">else </span> statements. Be careful with the order of the <span class="code">when </span> statements. The following code says <span class="code">"Int" </span> not <span class="code">42 </span> .</p>
<pre class="code">given 42 {
when Int { say "Int" }
when 42 { say 42 }
default { say "huh?" }
}
#-> Int</pre>
<p>When a <span class="code">when </span> statement or <span class="code">default </span> statement causes the outer block to return, nesting <span class="code">when </span> or <span class="code">default </span> 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:</p>
<pre class="code">given 42 {
when Int {
when 42 { say 42 }
say "Int"
}
default { say "huh?" }
}
#-> 42</pre>
<a name="t11..7.2"$class><h3>11..7.2 proceed and succeed </h3></a>
<p>Both <span class="code">proceed </span> and <span class="code">succeed </span> are meant to be used only from inside <span class="code">when </span> or <span class="code">default </span> blocks.</p>
<p>The <span class="code">proceed </span> statement will immediately leave the <span class="code">when </span> or <span class="code">default </span> block, skipping the rest of the statements, and resuming after the block. This prevents the <span class="code">when </span> or <span class="code">default </span> from exiting the outer block.</p>
<pre class="code">default {
proceed;
"This never says".say
}
"This says".say;</pre>
<p>This is most often used to enter multiple <span class="code">when </span> blocks. <span class="code">proceed </span> will resume matching after a successful match, like so:</p>
<pre class="code">given 42 {
when Int { say "Int"; proceed }
when 42 { say 42 }
when 40..* { say "greater than 40" }
default { say "huh?" }
}
# -> Int
# -> 42</pre>
<p>Note that the <span class="code">when 40..* </span> match didn't occur. For this to match such cases as well, one would need a proceed in the <span class="code">when 42 </span> block.</p>
<p>This is not like a <span class="code">C </span> <span class="code">switch </span> statement, because the <span class="code">proceed </span> does not merely enter the directly following block, it attempts to match the <span class="code">given </span> value once more, consider this code:</p>
<pre class="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</pre>
<p>...which matches the <span class="code">Int </span> , skips <span class="code">43 </span> since the value doesn't match, matches <span class="code">42 </span> since this is the next positive match, but doesn't enter the <span class="code">default </span> block since the <span class="code">when 42 </span> block doesn't contain a <span class="code">proceed </span> .</p>
<p>By contrast, the <span class="code">succeed </span> keyword shortcircuits execution and exits the entire <span class="code">given </span> block at that point. It may also take an argument to specify a final value for the block.</p>
<pre class="code">given 42 {
when Int {
say "Int";
succeed "Found";
say "never this!";
}
when 42 { say 42 }
default { say "dunno?" }
}
#-> Int</pre>
<p>If you are not inside a when or default block, it is an error to try to use <span class="code">proceed </span> or <span class="code">succeed </span> . Also remember, the <span class="code">when </span> statement modifier form does not cause any blocks to be left, and any <span class="code">succeed </span> or <span class="code">proceed </span> in such a statement applies to the surrounding clause, if there is one:</p>
<pre class="code">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;
}</pre>
<a name="t11..8"$class><h2>11..8 loop </h2></a>
<p>The <span class="code">loop </span> statement is the C-style <span class="code">for </span> loop in disguise:</p>
<pre class="code">loop (my $i = 0; $i &lt; 10; $i++) {
...
}</pre>
<p>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,</p>
<pre class="code">loop {...}</pre>
<p>is equivalent to the C-ish idiom:</p>
<pre class="code">loop (;;) {...}</pre>
<p>The <span class="code">loop </span> statement may be used to produce values from the result of each run of the attached block if it appears in lists:</p>
<pre class="code">(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</pre>
<p>Unlike a <span class="code">for </span> loop, one should not rely on whether returned values are produced lazily, for now. It would probably be best to use <span class="code">eager </span> to guarantee that a loop whose return value may be used actually runs:</p>
<pre class="code">sub heads-in-a-row {
(eager loop (; 2.rand &lt; 1;) { "heads".say })
}</pre>
<a name="t11..9"$class><h2>11..9 while, until </h2></a>
<p>The <span class="code">while </span> statement executes the block as long as its condition is true. So</p>
<pre class="code">my $x = 1;
while $x &lt; 4 {
print $x++;
}
print "\n";
</pre>
<p>produces</p>
<pre class="code">123
</pre>
<p>Similarly, the <span class="code">until </span> statement executes the block as long as the expression is false.</p>
<pre class="code">my $x = 1;
until $x > 3 {
print $x++;
}
print "\n";
</pre>
<p>again produces</p>
<pre class="code">123
</pre>
<p>The condition for <span class="code">while </span> or <span class="code">until </span> can be parenthesized, but there must be a space between the keyword and the opening parenthesis of the condition.</p>
<p>Both <span class="code">while </span> and <span class="code">until </span> can be used as statement modifiers. E. g.</p>
<pre class="code">$x++ while $x &lt; 12
</pre>
<p>Also see <span class="code">repeat/while </span> and <span class="code">repeat/until </span> below.</p>
<p>All these forms may produce a return value the same way <span class="code">loop </span> does.</p>
<a name="t11..10"$class><h2>11..10 repeat/while, repeat/until </h2></a>
<p>Perl 5 allows one to apply a statement modifier to a <span class="code">do </span> block such that C-like constructs such as</p>
<pre class="code">do {
...
} while $x &lt; 10; # allowed in Perl 5; not in Perl 6</pre>
<p>are possible.</p>
<p>This is specifically disallowed in Perl 6. Nevertheless, one can repeat a block up to a given condition in the same way wit a <span class="code">repeat </span> loop:</p>
<pre class="code">repeat {
...
} while $x &lt; 10;</pre>
<p>This can also be written quite naturally with <span class="code">until </span> :</p>
<pre class="code">repeat {
...
} until $x >= 10;</pre>
<p>All these forms may produce a return value the same way <span class="code">loop </span> does.</p>
<a name="t11..11"$class><h2>11..11 return </h2></a>
TODO
<a name="t11..12"$class><h2>11..12 LABELs</h2></a>
<p> <span class="code">while </span> , <span class="code">until </span> , and <span class="code">for </span> loops can all take a label, which can be used to identify them for <span class="code">next </span> , <span class="code">last </span> , and <span class="code">redo </span> . For instance:</p>
<pre class="code">LINE: for $*IN.lines -> $line {
last LINE if $line ~~ /^$/; # exit when done with header
...
}
</pre>
<a name="t11..13"$class><h2>11..13 next </h2></a>
<p>The <span class="code">next </span> command starts the next iteration of the loop. So the code</p>
<pre class="code">my @x = 1, 2, 3, 4, 5;
for @x -> $x {
next if $x == 3;
print $x;
}
</pre>
<p>prints "1245".</p>
<a name="t11..14"$class><h2>11..14 last </h2></a>
<p>The <span class="code">last </span> command immediately exits the loop in question.</p>
<pre class="code">my @x = 1, 2, 3, 4, 5;
for @x -> $x {
last if $x == 3;
print $x;
}
</pre>
<p>prints "12".</p>
<a name="t11..15"$class><h2>11..15 redo </h2></a>
<p>The <span class="code">redo </span> command restarts the loop block without evaluating the conditional again.</p>
<pre class="code">{ my $x = prompt("Enter a number"); redo unless is_a_number($x) }
</pre>
<a name="t11..16"$class><h2>11..16 goto </h2></a>
TODO
<a name="t12"><h1 class="title">12 Exceptions</h1></a> <p class="subtitle">Using exceptions in Perl 6</p></a> <p>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.</p>
<p>All built-in exceptions inherit from <a href="">Exception</a> , which provides some basic behavior, such as storing a backtrace and providing an interface for the backtrace printer.</p>
<a name="t12..1"$class><h2>12..1 Ad-hoc exceptions</h2></a>
<p>Ad-hoc exceptions work just like in traditional Perl 5, one can simply use <span class="code">die </span> with a message as to what went wrong:</p>
<pre class="code">die "oops, something went wrong";
#!> oops, something went wrong in block &lt;unit> at /tmp/0IeSX_XSWO:1</pre>
<a name="t12..2"$class><h2>12..2 Typed exceptions</h2></a>
<p>Typed exceptions provide more information about the kind of error that occurred within the exception object itself. For instance, if while executing <span class="code">.zombie copy </span> on an object the path <span class="code">foo/bar </span> is unavailable (and was expected to be available), then one could raise an <a href="">X::IO::DoesNotExist</a> exception like so:</p>
<pre class="code">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</pre>
<p>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.</p>
<a name="t12..3"$class><h2>12..3 Catching exceptions</h2></a>
<p>It is possible to handle exceptional circumstances by supplying a <span class="code">CATCH </span> block:</p>
<pre class="code">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!</pre>
<p>Here, we are saying that if any exception of type <span class="code">X::IO </span> occurs, then the message <span class="code">some kind of IO exception was caught! </span> will be displayed.</p>
<p>A <span class="code">CATCH </span> block uses smart matching similarly to how <span class="code">given/when </span> smart matches on options, thus it is possible to catch various categories of exceptions and handle them appropriately inside a <span class="code">when </span> block.</p>
<p>To handle all exceptions use a <span class="code">default </span> statement.</p>
<pre class="code">CATCH {
default {
say .WHAT.perl, do given .backtrace[0] { .file, .line, .subname }
}
}</pre>
<a name="t12..4"$class><h2>12..4 Throwing exceptions</h2></a>
<p>One can also explicitly throw exceptions via the <span class="code">.throw </span> method on an <span class="code">Exception </span> object.</p>
<p>This example throws an <span class="code">AdHoc </span> exception, catches it and allows the code to continue from the point of the exception by calling the <span class="code">.resume </span> method.</p>
<pre class="code">{
X::AdHoc.new(:payload&lt;foo>).throw;
"OHAI".say;
CATCH {
when X::AdHoc { .resume }
}
}
"OBAI".say;
#-> OHAI
#-> OBAI</pre>
<p>If the <span class="code">CATCH </span> block doesn't match the exception thrown, then the exception's payload is passed on to the backtrace printing mechanism.</p>
<pre class="code">{
X::AdHoc.new(:payload&lt;foo>).throw;
"OHAI".say;
CATCH { }
}
"OBAI".say;
#!> foo
#!> in block &lt;unit> at /tmp/FbtB60dxVO:1</pre>
<p>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 <span class="code">CATCH </span> block.</p>
<pre class="code">{
X::AdHoc.new(:payload&lt;foo>).throw;
"OHAI".say;
CATCH {
when X::AdHoc { }
}
}
"OBAI".say;
#-> OBAI</pre>
<p> <span class="code">throw </span> can be viewed as the method form of <span class="code">die </span> , just that in this particular case, the sub and method forms of the routine have different names.</p>
<a name="t13"><h1 class="title">13 FAQ</h1></a> <p class="subtitle">Frequently Asked Questions about Perl 6</p></a> <a name="t13.1"$class><h1>13.1 General</h1></a>
<a name="t13.1.1"$class><h2>13.1.1 What's the difference between Rakudo and Perl 6?</h2></a>
<p>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.</p>
<a name="t13.1.2"$class><h2>13.1.2 As a Perl 6 beginner what should I install?</h2></a>
<p>Linux or Mac users probably want to download Rakudo Star and install via compilation (a simple process) the MoarVM based version available from <a href="http://rakudo.org/downloads/star">http://rakudo.org/downloads/star/</a> .</p>
<p>Compilation needs a C compiler and Perl 5 installed.</p>
<p>Or there is an official rakudo star docker image at <a href="">https://hub.docker.com/_/rakudo-star/</a> </p>
<p>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.</p>
<p>To use panda (see below) to install library modules you will need git and Perl 5's Test::Harness.</p>
<p>There should be Linux and Mac binaries available shortly from vendors and third parties. Although vendor versions may be outdated.</p>
<a name="t13.1.3"$class><h2>13.1.3 As an intermediate to advanced user I want to track Rakudo development.</h2></a>
<p>Install <a href="https://github.com/tadzik/rakudobrew">rakudobrew</a> which resembles Perl 5's perlbrew and the equivalent Python and Ruby tools.</p>
<a name="t13.1.4"$class><h2>13.1.4 Where can I find good documentation on Perl 6?</h2></a>
<p>The most reliable information is to be found either under the perl6.org domains or directly linked from it.</p>
<p> <a href="https://www.perl6.org/documentation/">https://www.perl6.org/documentation/</a> with <a href="https://doc.perl6.org/">https://doc.perl6.org/</a> as the canonical technical reference.</p>
<p>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.</p>
<p>You could also try searching the Freenode #perl6 IRC channel log via <a href="https://www.google.co.uk/search?q=site:irclog.perlgeek.de+inurl:perl6">Google</a> </p>
<a name="t13.1.5"$class><h2>13.1.5 What is the Perl 6 spec?</h2></a>
<p>The "spec" refers to the official test suite for Perl 6. It's called roast and <a href="https://github.com/perl6/roast">hosted on github</a> . It is the measure of how complete a Perl 6 implementation is.</p>
<a name="t13.1.6"$class><h2>13.1.6 Is there a glossary of Perl 6 related terms?</h2></a>
<p>See <a href="https://design.perl6.org/S99.html">S99</a> </p>
<a name="t13.1.7"$class><h2>13.1.7 I'm a Perl 5 programmer. Where is a list of differences between Perl 5 and 6?</h2></a>
<p>See the pod with the 5to6- prefix under <a href="https://doc.perl6.org/language.html">https://doc.perl6.org/language.html</a> </p>
<a name="t13.2"$class><h1>13.2 Modules</h1></a>
<a name="t13.2.1"$class><h2>13.2.1 Is there a CPAN for Perl 6?</h2></a>
<p>There isn't yet a module repository for Perl 6 as sophisticated as CPAN. But <a href="https://modules.perl6.org/">modules.perl6.org</a> has a list of known Perl 6 modules called the "ecosystem" hosted on github, and <a href="https://github.com/tadzik/panda/">panda</a> can install those that work with <a href="http://rakudo.org/">rakudo</a> .</p>
<p>Support for installing Perl 6 modules from the Perl 5 CPAN is on its way.</p>
<a name="t13.2.2"$class><h2>13.2.2 Can I use Perl 5 modules from Perl 6?</h2></a>
<p>Yes, with <a href="https://github.com/niner/Inline-Perl5/">Inline::Perl5</a> , which works well with most Perl 5 modules. It can even run Perl 5 Catalyst and DBI.</p>
<a name="t13.2.3"$class><h2>13.2.3 Can I use C and C++ from Perl 6?</h2></a>
<p> <a href="https://docs.perl6.org/language/nativecall">Nativecall</a> makes this particularly easy.</p>
<a name="t13.2.4"$class><h2>13.2.4 Nativecall can't find libfoo.so and I only have libfoo.so.1.2!</h2></a>
<p>This is commonly seen on Debian-like systems. You need to install "libfoo-dev" to set a sym link for the missing file.</p>
<a name="t13.2.5"$class><h2>13.2.5 Where have all the traditional UNIX library functions gone?</h2></a>
<p>It's very easy to use Nativecall to access them.</p>
<p>A ecosystem module <a href="https://github.com/cspencer/perl6-posix">POSIX</a> is also available.</p>
<a name="t13.2.6"$class><h2>13.2.6 Does Rakudo have a core standard library?</h2></a>
<p>Rakudo is a compiler release with minimal batteries included (Test and Nativecall etc.) rather like the linux kernel itself.</p>
<p>Rakudo Star is a distribution of rakudo which ships with some useful modules and many more can be installed from the ecosystem.</p>
<a name="t13.3"$class><h1>13.3 Language Features</h1></a>
<a name="t13.3.1"$class><h2>13.3.1 How can I dump Perl 6 data structures (like Perl 5 Data::Dumper and similar)?</h2></a>
<p>Examples:</p>
<pre class="code">my $foo="bar"
dd $foo # Str $foo = "bar"
say :$foo.perl # :foo("bar")
say :$foo.gist # foo => bar</pre>
<p>There are also modules in the ecosystem to do this, like <a href="https://github.com/tony-o/perl6-data-dump/">Data::Dump</a> , which uses color.</p>
<a name="t13.3.2"$class><h2>13.3.2 How can I get command line history in the Perl 6 prompt (REPL)?</h2></a>
<p>Install <a href="https://github.com/hoelzro/p6-linenoise/">Linenoise</a> from the ecosystem.</p>
<p>An alternative on UNIX like systems is to install rlwrap. This can be done on Debian-ish systems by "apt-get install rlwrap".</p>
<a name="t13.3.3"$class><h2>13.3.3 Why is the Rakudo compiler sometimes more apologetic?</h2></a>
<p>If SORRY! is present in the output the error is a compile time error otherwise it's runtime.</p>
<p>Example:</p>
<pre class="code">say 1/0 # Attempt to divide 1 by zero using div
sub foo ( Int $a, Int $b ) {...}
foo(1) # ===SORRY!=== Error while compiling ...</pre>
<a name="t13.3.4"$class><h2>13.3.4 What is <span class="code">(Any) </span> ?</h2></a>
<p> <a href="type/Any">Any</a> 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.</p>
<p>Example:</p>
<pre class="code">my $foo
say $foo # (Any) note the parens indicate type object
say $foo.^name # Any</pre>
<p>(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.</p>
<pre class="code">say 1.defined # True
say (Any).defined # False</pre>
<a name="t13.3.5"$class><h2>13.3.5 What is <span class="code">so </span> ?</h2></a>
<p> <span class="code">so </span> is a loose precedence operator that coerces to <a href="/type/Bool">Bool</a> .</p>
<p>It has the same semantics as the <span class="code">? </span> prefix operator, just like <span class="code">and </span> is the low-precedence version of <span class="code">&amp;&amp; </span> .</p>
<p>Example usage:</p>
<pre class="code">say so 1|2 == 2; # Bool::True</pre>
<p>In this example, the result of the comparison (which is a <a href="/type/Junction">Junction</a> ), is converted to Bool before being printed.</p>
<a name="t13.3.6"$class><h2>13.3.6 What are those <span class="code">:D </span> and <span class="code">:U </span> things in signatures?</h2></a>
<p>In Perl 6, classes and other types are objects, and pass type checks of their own type.</p>
<p>For example if you declare a variable</p>
<pre class="code">my Int $x = 42;</pre>
<p>then not only can you assign integers (that is, instances of class Int) to it, but the <span class="code">Int </span> type object itself:</p>
<pre class="code">$x = Int</pre>
<p>If you want to exclude type objects, you can append the <span class="code">:D </span> type smiley, which stands for "definite":</p>
<pre class="code">my Int:D $x = 42;
$x = Int; # dies with:
# Type check failed in assignment to $x;
# expected Int:D but got Int</pre>
<p>Likewise <span class="code">:U </span> constrains to undefined values, that is, type objects.</p>
<p>To explicitly allow either type objects or instances, you can use <span class="code">:_ </span> .</p>
<a name="t13.3.7"$class><h2>13.3.7 What is the <span class="code">--> </span> thing in the signature?</h2></a>
<p> <span class="code">--> </span> is a return constraint, either a type or a definite value.</p>
<p>Example of a type constraint:</p>
<pre class="code">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</pre>
<p>Example of a definite return value:</p>
<pre class="code">sub discard-random-number( --> 42 ) { rand }
say discard-random-number
# 42</pre>
<p>In this case the final value is thrown away because the return value is already specified.</p>
<a name="t13.3.8"$class><h2>13.3.8 How can I extract the values from a Junction?</h2></a>
<p>If you want to extract the values (eigenstates) from a <a href="/type/Junction">Junction</a> , you are probably doing something wrong, and should be using a <a href="/type/Set">Set</a> instead.</p>
<p>Junctions are meant as matchers, not for doing algebra with them.</p>
<p>If you want to do it anyway, you can abuse autothreading for that:</p>
<pre class="code">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</pre>
<a name="t13.3.9"$class><h2>13.3.9 If Str is immutable, how does <span class="code">s/// </span> work? if Int is immutable, how does <span class="code">$i++ </span> work?</h2></a>
<p>In Perl 6, many basic types are immutable, but the variables holding them are not. The <span class="code">s/// </span> operator works on a variable, into which it puts a newly created string object. Likewise <span class="code">$i++ </span> works on the <span class="code">$i </span> variable, not just on the value in it.</p>
<p>See the documentation on <a href="/language/containers">containers</a> for more information.</p>
<a name="t13.3.10"$class><h2>13.3.10 What's up with array references and automatic dereferencing? Do I still need the <span class="code">@ </span> sigil?</h2></a>
<p>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:</p>
<pre class="code">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)</pre>
<p>The big difference is that arrays inside a scalar act as one value in list context, whereas arrays will be happily iterated over.</p>
<pre class="code">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</pre>
<p>You can force flattening with <span class="code">@( ... ) </span> or by calling the <span class="code">.list </span> method on an expression, and item context (not flattening) with <span class="code">$( ... ) </span> or by calling the <span class="code">.item </span> method on an expression.</p>
<a name="t13.3.11"$class><h2>13.3.11 Why sigils? Couldn't you do without them?</h2></a>
<p>There are several reasons:</p>
<ul><li><p>they make it easy to interpolate variables into strings</p>
</li></ul> <ul><li><p>they form micro-namespaces for different variables and twigils, thus avoiding name clashes</p>
</li></ul> <ul><li><p>they allow easy single/plural distinction</p>
</li></ul> <ul><li><p>they work like natural languages that use mandatory noun markers, so our brains are built to handle it</p>
</li></ul> <ul><li><p>they aren't mandatory, since you can declare sigilless names (if you don't mind the ambiguity)</p>
</li></ul> <a name="t13.3.12"$class><h2>13.3.12 Does Perl 6 have coroutines? What about <span class="code">yield </span> ?</h2></a>
<p>Perl 6 has no <span class="code">yield </span> 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:</p>
<pre class="code"># 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² });</pre>
<a name="t13.3.13"$class><h2>13.3.13 Why can't I initialize private attributes from the new method, and how can I fix this?</h2></a>
<p>Code like</p>
<pre class="code">class A {
has $!x;
method show-x {
say $!x;
}
}
A.new(x => 5).show-x;</pre>
<p>does not print 5. Private attributes are <i>private</i> , which means invisible to the outside. If the default constructor could initialize them, they would leak into the public API.</p>
<p>If you still want it to work, you can add a <span class="code">submethod BUILD </span> that initializes them:</p>
<pre class="code">class B {
has $!x;
submethod BUILD(:$!x) { }
method show-x {
say $!x;
}
}
A.new(x => 5).show-x;</pre>
<p> <span class="code">BUILD </span> is called by the default constructor (indirectly, see <a href="/language/objects#Object_Construction">Object Construction</a> for more details) with all the named arguments that the user passes to the constructor. <span class="code">:$!x </span> is a named parameter with name <span class="code">x </span> , and when called with a named argument of name <span class="code">x </span> , its value is bound to the attribute <span class="code">$!x </span> .</p>
<p>But don't do that. If the name is public, there is no downside to declaring it that way with <span class="code">$.x </span> since the external view is readonly by default, and you can still access it internally with <span class="code">$!x </span> .</p>
<a name="t13.3.14"$class><h2>13.3.14 How and why do <span class="code">say </span> , <span class="code">put </span> and <span class="code">print </span> differ?</h2></a>
<p>The most obvious difference is that <span class="code">say </span> and <span class="code">put </span> append a newline at the end of the output, and <span class="code">print </span> does not.</p>
<p>But there is another difference: <span class="code">print </span> and <span class="code">put </span> converts its arguments to a string by calling the <span class="code">Str </span> method on each item passed to, <span class="code">say </span> uses the <span class="code">gist </span> method instead. The former is meant for computers, the latter for human interpretation.</p>
<p>Or phrased differently, <span class="code">$obj.Str </span> gives a string representation, <span class="code">$obj.gist </span> a short summary of that object suitable for fast recognition by the programmer, and <span class="code">$obj.perl </span> gives a Perlish representation.</p>
<p>Example: type objects, also known as "undefined values", stringify to an empty string and warn, whereas the <span class="code">gist </span> 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).</p>
<pre class="code">my Date $x; # $x now contains the Date type object
print $x; # empty string plus warning
say $x; # (Date)\n</pre>
<p>So <span class="code">say </span> is optimized for debugging and display to people, <span class="code">print </span> and <span class="code">put </span> is more suitable for producing output for other programs to consume.</p>
<p> <span class="code">put </span> is thus sort of a hybrid between <span class="code">print </span> and <span class="code">say </span> ; like <span class="code">print </span> , its output is suitable for other programs, and like <span class="code">say </span> , it adds a newline at the end of the output.</p>
<a name="t13.3.15"$class><h2>13.3.15 What's the difference between <span class="code">token </span> and <span class="code">rule </span> ?</h2></a>
<p> <span class="code">regex </span> , <span class="code">token </span> and <span class="code">rule </span> all three introduce regexes, but with slightly different semantics.</p>
<p> <span class="code">token </span> implies the <span class="code">:ratchet </span> or <span class="code">:r </span> modifier, which prevents the rule from backtracking.</p>
<p> <span class="code">rule </span> implies both the <span class="code">:ratchet </span> and <span class="code">:sigspace </span> (short <span class="code">:s </span> ) modifier, which means a rule doesn't backtrace, and it treats whitespace in the text of the regex as <span class="code">&lt;.ws> </span> 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.</p>
<p> <span class="code">regex </span> declares a plain regex without any implied modifiers.</p>
<a name="t13.3.16"$class><h2>13.3.16 What's the difference between <span class="code">die </span> and <span class="code">fail </span> ?</h2></a>
<p> <span class="code">die </span> throws an exception.</p>
<p> <span class="code">fail </span> returns a <span class="code">Failure </span> object. (If the caller has declared <span class="code">use fatal; </span> in the calling lexical scope, <span class="code">fail </span> throws an exception instead of returning.)</p>
<p>A <span class="code">Failure </span> is an "unthrown" or "lazy" exception. It is an object that contains the exception, and throws the exception if you try to use the <span class="code">Failure </span> as an ordinary object, or ignore it in sink context.</p>
<p>A <span class="code">Failure </span> returns <span class="code">False </span> from a <span class="code">defined </span> check, and you can extract the exception with the <span class="code">exception </span> method.</p>
<a name="t13.3.17"$class><h2>13.3.17 Why is <span class="code">wantarray </span> or <span class="code">want </span> gone? Can I return different things in different contexts?</h2></a>
<p>Perl 5 has the <span class="code">wantarray </span> 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.</p>
<p>For example, Perl 6 has multiple dispatch, so in a code example like</p>
<pre class="code">multi w(Int $x) { say 'Int' }
multi w(Str $x) { say 'Str' }
w(f());</pre>
<p>there is no way to determine if the caller of sub <span class="code">f </span> 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.</p>
<p>The 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.</p>
<p>For example regex matches return <a href="/type/Match">Match objects that know how to respond to list indexing, hash indexing, and that can turn into the matched string</a> .</p>
<a name="t13.4"$class><h1>13.4 Meta Questions and Advocacy</h1></a>
<a name="t13.4.1"$class><h2>13.4.1 When will Perl 6 be ready? Is it ready now?</h2></a>
<p>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.</p>
<p>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.</p>
<a name="t13.4.2"$class><h2>13.4.2 Why should I learn Perl 6? What's so great about it?</h2></a>
<p>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.</p>
<ul><li><p>Perl 6 offers procedural, object-oriented AND functional programming methodologies.</p>
</li></ul> <ul><li><p>Easy to use consistent syntax, using invariable sigils for data-structures.</p>
</li></ul> <ul><li><p>Full grapheme based Unicode support, including Annex #29.</p>
</li></ul> <ul><li><p>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.</p>
</li></ul> <ul><li><p>Junctions allowing easy checking of multiple possibilities, e.g. $a == 1|3|42 (meaning is $a equal to 1 or 3 or 42).</p>
</li></ul> <ul><li><p>Dynamic variables provide a lexically scoped alternative to global variables.</p>
</li></ul> <ul><li><p>Emphasis on composability and lexical scoping to prevent “action at a distance”. For example, imports are always lexically scoped.</p>
</li></ul> <ul><li><p>Easy to understand consistent scoping rules and closures.</p>
</li></ul> <ul><li><p>Powerful object orientation, with classes and roles (everything can be seen as an object). Inheritance. Subtyping. Code-reuse.</p>
</li></ul> <ul><li><p>Introspection into objects and meta-objects (turtles all the way down).</p>
</li></ul> <ul><li><p>Meta Object Protocol allowing for meta-programming without needing to generate / parse code.</p>
</li></ul> <ul><li><p>Subroutine and method signatures for easy unpacking of positional and named parameters.</p>
</li></ul> <ul><li><p>Multi dispatch on identically named subroutines/methods with different signatures, based on arity, types and optional additional code.</p>
</li></ul> <ul><li><p>Compile time error reporting on unknown subroutines / impossible dispatch.</p>
</li></ul> <ul><li><p>Optional gradual type-checking at no additional runtime cost. With optional type annotations.</p>
</li></ul> <ul><li><p>Advanced error reporting based on introspection of the compiler/runtime state. This means more useful, more precise error messages.</p>
</li></ul> <ul><li><p>Phasers (like BEGIN / END) allow code to be executed at scope entry / exit, loop first / last / next and many more special contexts.</p>
</li></ul> <ul><li><p>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.</p>
</li></ul> <ul><li><p>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.</p>
</li></ul> <ul><li><p>Structured language support is provided to enable programming for asynchronous execution of code.</p>
</li></ul> <ul><li><p>Supplies allow code to be executed when something happens (like a timer, or a signal, or a file-system event).</p>
</li></ul> <ul><li><p>react / whenever / supply keywords allows easy construction of interactive, event driven applications.</p>
</li></ul> <ul><li><p>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.</p>
</li></ul> <ul><li><p>Native data types for faster, closer to the metal, processing.</p>
</li></ul> <ul><li><p>Interfacing to external libraries in C / C++ are trivially simple with NativeCall.</p>
</li></ul> <ul><li><p>Interfacing with Perl 5 (CPAN) / Python modules trivially simple with Inline::Perl5 resp. Inline::Python.</p>
</li></ul> <ul><li><p>Can have multiple versions of a module installed and loaded simultaneously.</p>
</li></ul> <ul><li><p>System administration simplified due to simpler update/upgrade policies.</p>
</li></ul> <ul><li><p>Floating point math without precision loss because of Rats (rational numbers).</p>
</li></ul> <ul><li><p>Extensible grammars for parsing data or code (which Perl 6 uses to parse itself).</p>
</li></ul> <ul><li><p>Perl 6 is a very mutable language (define your own functions, operators, traits and data-types, which modify the parser for you).</p>
</li></ul> <ul><li><p>Large selection of data-types, plus the possibility to create your own types.</p>
</li></ul> <ul><li><p>Multi-dimensional shaped and/or native arrays with proper bounds checking.</p>
</li></ul> <ul><li><p>Execute code at any time during parsing of a grammar, or when a certain match occurred.</p>
</li></ul> <ul><li><p>Adding a custom operator or adding a trait is as simple as writing a subroutine.</p>
</li></ul> <ul><li><p>Automatic generation of hyper-operators on any operator (system or custom added).</p>
</li></ul> <ul><li><p>Runs on a variety of back-ends. Currently MoarVM &amp; JVM, JavaScript in development, more may follow.</p>
</li></ul> <ul><li><p>Runtime optimization of hot code paths during execution (JIT).</p>
</li></ul> <ul><li><p>Runs on small (e.g. Raspberry Pi) and large multi-processor hardware.</p>
</li></ul> <ul><li><p>Garbage collect based: no timely destruction, so no ref-counting necessary. Use phasers for timely actions.</p>
</li></ul> <ul><li><p>Methods can be mixed into any instantiated object at runtime, e.g. to allow adding out-of-band data.</p>
</li></ul> <ul><li><p>Easy command-line interface accessible by MAIN subroutine with multiple dispatch and automated usage message generation.</p>
</li></ul> <ul><li><p>Fewer lines of code allow for more compact program creation. Huffman-coding of names allows for better readability.</p>
</li></ul> <ul><li><p>Lazy lists defined with a simple iterator interface, which any class can supply by minimally supplying a single method.</p>
</li></ul> <ul><li><p>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.</p>
</li></ul> <p>Please see the <a href="https://perl6.org/compilers/features">feature comparison matrix</a> for an overview of implemented features.</p>
<a name="t13.4.3"$class><h2>13.4.3 Is Perl 6 fast enough for me?</h2></a>
<p>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. After the Christmas 2015 release stabilizes the definition of the language, we'll be 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.</p>
<p>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.</p>
<p>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.</p>
<p>Try it on your system you may be pleasantly surprised!</p>
<p>Examples:</p>
<pre class="code"># 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;</pre>
<a name="t14"><h1 class="title">14 Functions</h1></a> <p class="subtitle">Functions and Functional Programming in Perl 6</p></a> <p>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 <i>subroutines</i> or short <i>sub</i> s, which exist independently of objects.</p>
<p>Subroutines default to lexical ( <span class="code">my </span> ) scoping, and calls to them are generally resolved at compile time.</p>
<p>Subroutines can have a <a href="/type/Signature">signature</a> , also called <i>parameter list</i> , 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.</p>
<a name="t14.1"$class><h1>14.1 Defining/Creating/Using Functions</h1></a>
<a name="t14.1.1"$class><h2>14.1.1 Subroutines </h2></a>
<p>To create a function, often all that's needed is to define a subroutine using the <span class="code">sub </span> declarator:</p>
<pre class="code">sub my-func { say "Look ma, no args!" }
my-func;</pre>
<p>To have the subroutine take arguments, a <a href="Signature">signature</a> goes between the subroutine's name and its body, in parentheses:</p>
<pre class="code">sub exclaim <b>($phrase)</b> {
say $phrase <a href="">~</a> "!!!!"
}
exclaim "Howdy, World";
</pre>
<p>By default, subroutines are <a href="/syntax/my">lexically scoped</a> . That is <span class="code">sub foo {...} </span> is the same as <span class="code">my sub foo {...} </span> and is only defined within the current scope.</p>
<pre class="code">sub escape ($str) {
<a href="">$_</a> = $str;
# Puts a slash before non-alphanumeric characters
<a href="">s</a> :g[&lt;-alpha-digit>] = "\\$/";
}
say escape "foo#bar?" # foo\#bar\?
{
sub escape ($str) {
$_ = $str;
# Writes each non-alphanumeric character in its hexadecimal escape
s:g|&lt;-alpha-digit>| = "\\x[{ $/.base(16) }]";
}
say escape "foo#bar?" # foo\x[23]bar\x[3F]
}
# Back to original escape function
say escape "foo#bar?" # foo\#bar\?
</pre>
<p>Subroutines don't have to be named; in this case they're called anonymous.</p>
<pre class="code">say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # 25</pre>
<p>But in this case, it's often desirable to use the more succinct <a href="Block">block</a> syntax.</p>
<a name="t14.1.2"$class><h2>14.1.2 Blocks and Lambdas </h2></a>
<p>Whenever you see something like <span class="code">{ $_ + 42 } </span> , <span class="code">-> $a, $b { $a ** $b } </span> , or <span class="code">{ $^text.indent($:spaces) } </span> , that's <a href="">Block</a> syntax. It's used after every <span class="code">if </span> , <span class="code">for </span> , <span class="code">while </span> , etc.</p>
<pre class="code">for 1, 2, 3, 4 -> $a, $b {
say $a ~ $b;
}
12
34</pre>
<p>They can also be used on their own as anonymous blocks of code.</p>
<pre class="code">say { $^a ** 2 + $^b ** 2}(3, 4) # 25</pre>
<p>For details about the syntax of blocks, see the documentation for the <a href="">Block</a> type.</p>
<a name="t14.1.3"$class><h2>14.1.3 Signatures</h2></a>
<p>The parameters that a function accepts are described in its <i>signature</i> .</p>
<pre class="code">sub format <b>(Str $s)</b> { ... }
-> <b>$a, $b</b> { ... }
</pre>
<p>Details about the syntax and use of signatures can be found in the <a href="Signature">documentation on the <span class="code">Signature </span> class</a> .</p>
capture, destructuring,
<a name="t14.1.4"$class><h2>14.1.4 Arguments</h2></a>
<p>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:</p>
<pre class="code">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</pre>
<p>Arguments passed to a function are conceptually first collected in a <span class="code">Capture </span> container. Details about the syntax and use of these containers can be found in the <a href="Capture">documentation on the <span class="code">Capture </span> class</a> .</p>
<p>When using named arguments, note that normal List "pair-chaining" allows one to skip commas between named arguments.</p>
<pre class="code">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.</pre>
<a name="t14.1.5"$class><h2>14.1.5 Multi-dispatch </h2></a>
<p>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 <i>candidate</i> . You declare each candidate with the <span class="code">multi </span> declarator.</p>
<pre class="code">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</pre>
<p>Dispatch can happen on the number of arguments (the <i>arity</i> ), but also on the type:</p>
<pre class="code">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]</pre>
<p> <span class="code">multi </span> without any specific routine type always defaults to a <span class="code">sub </span> , but you can use it on methods as well. The candidates are all the multi methods of the object:</p>
<pre class="code">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</pre>
<a name="t14.1.5.1"$class><h3>14.1.5.1 proto </h3></a>
<p> <span class="code">proto </span> is a way to formally declare commonalities between <span class="code">multi </span> candidates. It acts as a wrapper that can validate but not modify arguments. Consider this basic example:</p>
<pre class="code">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</pre>
<p>All <span class="code">multi congratulate </span> will conform to the basic signature of two strings, optionally followed by further parameters. The <span class="code">| </span> is an un-named <span class="code">Capture </span> parameter, allowing a <span class="code">multi </span> which takes additional arguments. The third call fails at compile time because the proto's <span class="code">signature </span> becomes the common signature of all three, and <span class="code">42 </span> doesn't match <span class="code">Str </span> .</p>
<pre class="code">say &amp;congratulate.signature #-> (Str $reason, Str $name, | is raw)</pre>
<p>You can give the <span class="code">proto </span> a function body, and place the <span class="code">{*} </span> where you want the dispatch to be done.</p>
<pre class="code"># 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;
}
}</pre>
<p> <span class="code">{*} </span> always dispatches to candidates with the parameters it's called with. Parameter defaults and type coercions will work but are not be passed on.</p>
<pre class="code">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</pre>
only
<a name="t14.2"$class><h1>14.2 Conventions and Idioms</h1></a>
<p>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.</p>
<a name="t14.2.1"$class><h2>14.2.1 Slurpy Conventions</h2></a>
<p>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, <a href="routine/chrs">chrs</a> , or where there is a conflict with an established idiom, like <a href="routine/pop">pop</a> being the inverse of <span class="code">push|routine/push </span> .</p>
<p>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:</p>
<ul><li><p>An Iterable inside a <a href="containers#Scalar_containers|">Scalar container</a> does not count.</p>
</li></ul> <ul><li><p>Lists created with a <a href="routine/,"> <span class="code">, </span> </a> at the top level only count as one Iterable.</p>
</li></ul> <p>This can be achieved by using a slurpy with a <span class="code">+ </span> or <span class="code">+@ </span> instead of <span class="code">** </span> :</p>
<pre class="code">sub grab (+@a) { "grab $_".say for @a }</pre>
<p>...which is shorthand for something very close to:</p>
<pre class="code">multi sub grab (**@a) { "grab $_".say for @a }
multi sub grab (\a) {
a ~~ Iterable and a.VAR !~~ Scalar ?? nextwith(|a) !! nextwith(a,)
}</pre>
<p>This results in the following behavior, which is known as the "single argument rule" and is important to understand when invoking slurpy functions:</p>
<pre class="code">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</pre>
<p>This also makes user-requested flattening feel consistent whether there is one sublist, or many:</p>
<pre class="code">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</pre>
<p>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.</p>
<pre class="code">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</pre>
<a name="t14.3"$class><h1>14.3 Functions are First-Class Objects</h1></a>
<p>Functions and other code objects can be passed around as values, just like any other object.</p>
<p>There are several ways to get hold of a code object. You can assign it to a variable at the point of declaration:</p>
<pre class="code">my $square = sub (Numeric $x) { $x * $x }
# and then use it:
say $square(6); # 36
</pre>
<p>Or you can reference an existing named function by using the <span class="code">&amp; </span> in front of it.</p>
<pre class="code">sub square ($x) { $x * $x };
# get hold of a reference to the function:
my $func = &amp;square
</pre>
<p>This is very useful for <i>higher order functions</i> , that is, functions that take other functions as input. A simple one is <a href="/type/List#routine_map">map</a> , which applies a function to each input element:</p>
<pre class="code">sub square ($x) { $x * $x };
my @squared = map &amp;square, 1..5;
say join ', ', @squared; # 1, 4, 9, 16, 25</pre>
<a name="t14.3.1"$class><h2>14.3.1 Closures</h2></a>
<p>All code objects in Perl 6 are <i>closures</i> , which means they can reference lexical variables from an outer scope.</p>
<pre class="code">sub generate-sub($x) {
my $y = 2 * $x;
return sub { say $y };
# ^^^^^^^^^^^^^^ inner sub, uses $y
}
my $generated = generate-sub(21);
$generated(); # 42
</pre>
<p>Here <span class="code">$y </span> is a lexical variable inside <span class="code">generate-sub </span> , and the inner subroutine that is returned uses it. By the time that the inner sub is called, <span class="code">generate-sub </span> has already exited. Yet the inner sub can still use <span class="code">$y </span> , because it <i>closed</i> over the variable.</p>
<p>A less obvious but useful example for closures is using <a href="/type/List#routine_map">map</a> to multiply a list of numbers:</p>
<pre class="code">my $multiply-by = 5;
say join ', ', map { $_ * $multiply-by }, 1..5; # 5, 10, 15, 20, 25</pre>
<p>Here the block passed to <span class="code">map </span> references the variable <span class="code">$multiply-by </span> from the outer scope, making the block a closure.</p>
<p>Languages without closures cannot easily provide higher-order functions that are as easy to use and powerful as <span class="code">map </span> .</p>
<a name="t14.3.2"$class><h2>14.3.2 Routines</h2></a>
<p>Routines are code objects that conform to <a href="/type/Routine">type Routine</a> , most notably <a href="/type/Sub">Sub</a> , <a href="/type/Method">Method</a> , <a href="/type/Regex">Regex</a> and <a href="/type/Submethod">Submethod</a> .</p>
<p>They carry additional functionality in addition to what <a href="/type/Block">Block</a> supplies: they can come as <a href="#Multi-dispatch">multis</a> , you can <a href="/type/Routine#method wrap">wrap</a> them, and exit early with <span class="code">return </span> :</p>
<pre class="code">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
</pre>
<p>Here <span class="code">return </span> does not just leave the block inside which it was called, but the whole routine. In general, blocks are transparent to <span class="code">return </span> , they attach to the outer routine.</p>
Important ones: candidates, wrap, unwrap, assuming, arity, count
<a name="t14.4"$class><h1>14.4 Defining Operators</h1></a>
<p>Operators are just subroutines with funny names. The funny names are composed of the category name ( <span class="code">infix </span> , <span class="code">prefix </span> , <span class="code">postfix </span> , <span class="code">circumfix </span> , <span class="code">postcircumfix </span> ), followed by a colon, and a list of the operator name or names (two components in the case of circumfix and postcircumfix).</p>
<p>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 <span class="code">use </span> or <span class="code">import </span> also makes it available.</p>
<pre class="code"># 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
</pre>
<p>The operator declaration becomes available as soon as possible, so you can even recurse into a just-defined operator, if you really want to:</p>
<pre class="code">sub postfix:&lt;!>(Int $x where { $x >= 0 }) {
$x == 0 ?? 1 !! $x * ($x - 1)!
}
say 6!; # 720
</pre>
<p>Circumfix and postcircumfix operators are made of two delimiters, one opening and one closing.</p>
<pre class="code">sub circumfix:&lt;START END>(*@elems) {
"start", @elems, "end"
}
say START 'a', 'b', 'c' END; # start a b c end
</pre>
<p>Postcircumfixes also receive the term after which they are parsed as an argument:</p>
<pre class="code">sub postcircumfix:&lt;!! !!>($left, $inside) {
"$left -> ( $inside )"
}
say 42!! 1 !!; # 42 -> ( 1 )
</pre>
<a name="t14.4.1"$class><h2>14.4.1 Precedence</h2></a>
<p>Operator precedence in Perl 6 is specified relatively to existing operators. With <span class="code">is tighter(&amp;other-operator) </span> you can squeeze in an operator with a tighter precedence than the one you specified, but looser than the next-tighter precedence level.</p>
<p>For example <span class="code">infix:&lt;*> </span> has a tighter precedence than <span class="code">infix:&lt;+> </span> , and squeezing one in between works like this:</p>
<pre class="code">sub infix:&lt;!!>($a, $b) is tighter(&amp;infix:&lt;+>) {
2 * ($a + $b)
}
say 1 + 2 * 3 !! 4; # 29
</pre>
<p>Here the <span class="code">1 + 2 * 3 !! 4 </span> is parsed as <span class="code">1 + ((2 * 3) !! 4) </span> , because the precedence of the new <span class="code">!! </span> operator is between that of <span class="code">+ </span> and <span class="code">* </span> .</p>
<p>The same effect could have been achieved with</p>
<pre class="code">sub infix:&lt;!!>($a, $b) is looser(&amp;infix:&lt;*>) { ... }</pre>
<p>To put a new operator on the same precedence level as an existing operator, use <span class="code">is equiv(&amp;other-operator) </span> instead.</p>
<a name="t14.4.2"$class><h2>14.4.2 Associativity</h2></a>
<p>When the same operator appears several times in a row, there are multiple possible interpretations. For example</p>
<pre class="code">1 + 2 + 3</pre>
<p>could be parsed as</p>
<pre class="code">(1 + 2) + 3 # left associative</pre>
<p>or as</p>
<pre class="code">1 + (2 + 3) # right associative</pre>
<p>or as single call to an operator with three operands</p>
<pre class="code">infix:&lt;+>(1, 2, 3); # list associative</pre>
<p>For addition of real numbers, the distinction is somewhat moot, because <span class="code">+ </span> is <a href="https://en.wikipedia.org/wiki/Associative_property">mathematically associative</a> .</p>
<p>But for other operators it matters a great deal. For example for the exponentiation/power operator, <span class="code">infix:&lt;**> </span> :</p>
<pre class="code">say 2 ** (2 ** 3); # 256
say (2 ** 2) ** 3; # 64</pre>
<p>Perl 6 has the following possible associativity configurations:</p>
<table>
<tr><th>A</th> <th>Assoc</th> <th>Meaning of $a ! $b ! $c</th></tr>
<tr><td>L</td> <td>left</td> <td>($a ! $b) ! $c</td></tr>
<tr><td>R</td> <td>right</td> <td>$a ! ($b ! $c)</td></tr>
<tr><td>N</td> <td>non</td> <td>ILLEGAL</td></tr>
<tr><td>C</td> <td>chain</td> <td>($a ! $b) and ($b ! $c)</td></tr>
<tr><td>X</td> <td>list</td> <td>infix:&lt;!>($a; $b; $c)</td></tr>
</table> <p>You can specify the associativity of an operator with the <span class="code">is assoc </span> trait, where <span class="code">left </span> is the default associativity.</p>
<pre class="code">sub infix:&lt;§>(*@a) is assoc&lt;list> {
'(' ~ @a.join('|') ~ ')';
}
say 1 § 2 § 3; # (1|2|3)
</pre>
<a name="t14.5"$class><h1>14.5 Traits</h1></a>
<p> <i>Traits</i> are subroutines are run at compile time to modify the behavior of a type, variable, routine, attribute, or other language object.</p>
<p>Examples of traits are:</p>
<pre class="code">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</pre>
<p>... and also <span class="code">is tighter </span> , <span class="code">is looser </span> , <span class="code">is equiv </span> and <span class="code">is assoc </span> from the previous section.</p>
<p>Traits are subs of the form <span class="code">trait_mod&lt;VERB> </span> , where <span class="code">VERB </span> stands for the name like <span class="code">is </span> , <span class="code">does </span> or <span class="code">handles </span> . It receives the modified thing as argument, and the name as a named argument.</p>
<pre class="code">multi sub trait_mod:&lt;is>(Routine $r, :$doubles!) {
$r.wrap({
2 * callsame;
});
}
sub square($x) is doubles {
$x * $x;
}
say square 3; # 18
</pre>
<p>See <a href="/type/Routine">type Routine</a> for the documentation of built-in routine traits.</p>
<a name="t14.6"$class><h1>14.6 Re-dispatching</h1></a>
<p>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 <span class="code">wrap </span> .</p>
<p>In all those cases, you can use <span class="code">callwith </span> to call the next routine in the chain with arguments of your own choice.</p>
<p>For example</p>
<pre class="code">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;
</pre>
<p>produces this output:</p>
<pre class="code">Int 1
Any 2
Back in Int with 5
</pre>
<p>Here <span class="code">a 1 </span> calls the most specific <span class="code">Int </span> candidate first, and <span class="code">callwith </span> re-dispatches to the less specific <span class="code">Any </span> candidate.</p>
<p>Very often, a re-dispatch passes the same argument along that the caller received, so there is a special routine for that: <span class="code">callsame </span> .</p>
<pre class="code">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
</pre>
<p>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 <span class="code">nextwith </span> and <span class="code">nextsame </span> , which call the next routine with arbitrary arguments ( <span class="code">nextwith </span> ) or with the same argument as the caller received ( <span class="code">nextsame </span> ), but never return to the caller. Or to phrase it differently, the <span class="code">nextsame </span> and <span class="code">nextwith </span> variants replace the current callframe with the next candidate.</p>
<pre class="code">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
</pre>
<p>As mentioned earlier, multi subs are not the only situation in which <span class="code">callwith </span> , <span class="code">callsame </span> , <span class="code">nextwith </span> and <span class="code">nextsame </span> can be helpful. One is is for dispatching to wrapped routines:</p>
<pre class="code"># enable wrapping:
use soft;
# function to be wrapped:
sub square-root($x) { $x.sqrt }
&amp;square-root.wrap(-> $num {
nextsame if $num >= 0;
1i * callwith(abs($num));
});
say square-root(4); # 2
say square-root(-4); # 0+2i
</pre>
<p>The final use case is to re-dispatch to methods from parent classes.</p>
<pre class="code">class LoggedVersion is Version {
method new(|c) {
note "New version object created with arguments " ~ c.perl;
nextsame;
}
}
say LoggedVersion.new('1.0.2');
</pre>
<a name="t14.7"$class><h1>14.7 Coercion Types</h1></a>
<p>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.</p>
<pre class="code">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'
</pre>
<p>Here the <span class="code">Int </span> is the target type to which the argument will be coerced, and <span class="code">Cool </span> is the type that the routine accepts as input.</p>
<p>If the accepted input type is <a href="/type/Any">Any</a> , you can abbreviate <span class="code">Int(Any) </span> to <span class="code">Int() </span> .</p>
<p>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:</p>
<pre class="code">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;</pre>
<p>Coercion types are supposed to work wherever types work, but Rakudo currently (2015.02) only implements them for subroutine parameters.</p>
<a name="t15"><h1 class="title">15 Glossary</h1></a> <p class="subtitle">Glossary of Perl 6 terminology</p></a> <a name="t15.1"$class><h1>15.1 Anonymous</h1></a>
<p>A subroutine, method or submethod is called <i>anonymous</i> if it can't be called by name.</p>
<pre class="code"># named subroutine
sub double($x) { 2 * $x };
# anonymous subroutine, stored in a named scalar
my $double = sub ($x) { 2 * $x };</pre>
<p>Note that it is still allowed to have a name</p>
<pre class="code"># anonymous, but knows its own name
my $s = anon sub triple($x) { 3 * $x }
say $s.name; # triple</pre>
<a name="t15.2"$class><h1>15.2 Adverb</h1></a>
<p>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:</p>
<pre class="code">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</pre>
<p>Adverbs are usually expressed with colon pair notation, and for this reason colon pair notation is also known as the adverbial pair form:</p>
<pre class="code">:a(4) # Same as "a" => 4</pre>
<p>Some other forms that use a colon in ways that have adverb-like semantics are called adverbial forms.</p>
<a name="t15.3"$class><h1>15.3 Autothreading</h1></a>
<p>Autothreading is what happens if you pass a junction to a sub that expects a parameter of type <span class="code">Any </span> or a subtype thereof. The call is executed multiple times, each time with a different eigenstate of the junction. The result of these calls is assembled in a junction of the same type as the original junction.</p>
<pre class="code">sub f($x) { 2 * $x };
if f(1|2|3) == 4 {
say 'success';
}</pre>
<p>Here <span class="code">f() </span> is a sub with one parameter, and since it has no explicit type, it is implicitly typed as <span class="code">Any </span> . The <span class="code">Junction </span> argument causes the <span class="code">f(1|2|3) </span> call to be internally executed as <span class="code">f(1)|f(2)|f(3) </span> , and the resulting junction is <span class="code">2|4|6 </span> . This process of separating junction arguments into multiple calls to a function is called <i>autothreading</i> .</p>
<a name="t15.4"$class><h1>15.4 Colon Pair and Colon List</h1></a>
<p>A colon pair is a shorthand syntax used to create or visually present a Pair object. The two most common forms are:</p>
<pre class="code">:a(4) # Same as "a" => 4, same as Pair.new(:key&lt;a>,:value(4))
:a&lt;4> # Same as "a" => "4", same as Pair.new(:key&lt;a>,:value&lt;4>)</pre>
<p>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.</p>
<p>Two other common forms are:</p>
<pre class="code">:a # Same as :a(True)
:!a # Same as :a(False)</pre>
<p>A colon list just means that a list that contains only colon pairs, does not need commas, or even spaces:</p>
<pre class="code">:a(4):c:!d:c # Same as a => 4, c => True, d => False, c => True</pre>
<a name="t15.5"$class><h1>15.5 Constraint</h1></a>
<p>Constraints are a restriction placed on acceptable types for a parameter or subset type. They are introduced with the word <span class="code">where </span> . In the following example, a constraint is used to make sure an error occurs if anyone ever calls a subroutine named <span class="code">abbreviate </span> with a string which is shorter than 10 characters:</p>
<pre class="code">sub abbreviate (Str $thing where { .chars >= 10 }) { ... }</pre>
<p>The <span class="code">Str </span> in the above example is also a constraint, but is usually referred to as a "type constraint."</p>
<a name="t15.6"$class><h1>15.6 Instance</h1></a>
<p>An <i>instance</i> of a class is also called an <i>object</i> in some other programming languages. It has storage for attributes and is often the return value of a call to a method called <span class="code">new </span> , or a literal.</p>
<p>Instances of most types are defined to be <span class="code">True </span> e.g., <span class="code">defined($instance) </span> is <span class="code">True </span> .</p>
<pre class="code">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.</pre>
<p>To put things another way, a class contains the blueprints of methods and attributes, and an instance carries it into the real world.</p>
<a name="t15.7"$class><h1>15.7 Invocant</h1></a>
<p>The object upon which a method is called, is referred to as the <i>invocant</i> in Perl 6. It is what <span class="code">self </span> refers to in a method.</p>
<pre class="code">say 'str'.uc; # 'str' is the invocant of method uc</pre>
<a name="t15.8"$class><h1>15.8 Literal</h1></a>
<p>A <i>literal</i> is a piece of code that directly stands for an (often built-in) object and also refers to the object itself.</p>
<pre class="code">my $x = 2; # the 2 is a literal
say $x; # $x is not a literal, but a variable</pre>
<a name="t15.9"$class><h1>15.9 lvalue</h1></a>
<p>An <i>lvalue</i> , or a <i>left value</i> , is anything that can appear on the left hand side of the assignment operator <span class="code">= </span> . It is anything you can assign to.</p>
<p>Typical lvalues are variables, private and <span class="code">is rw </span> attributes, lists of variables and lvalue subroutines.</p>
<p>Examples of lvalues:</p>
<pre class="code">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()</pre>
<p>Examples of things that are not lvalues:</p>
<pre class="code">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</pre>
<a name="t15.10"$class><h1>15.10 Mainline</h1></a>
<p>The <span class="code">mainline </span> is the program text that is not part of any kind of block.</p>
<pre class="code">use v6; # mainline
sub f {
# not in mainline, in sub f
}
f(); # in mainline again</pre>
<a name="t15.11"$class><h1>15.11 Slurpy</h1></a>
<p>A parameter of a sub or method is said to be <i>slurpy</i> if it can consume an arbitrary number of arguments. It is indicated by an asterisk <span class="code">* </span> in front of the parameter name.</p>
<pre class="code">sub sum (*@numbers) {
return [+] @numbers;
}</pre>
<a name="t15.12"$class><h1>15.12 Type Object</h1></a>
<p>A <i>type object</i> is an object representing a class, role, package, grammar or enum. It is generally accessible with the same name as the type.</p>
<pre class="code">class A { };
say A; # A is the type object
my $x = A.new(); # same here
my $x = class {
method greet() {
say "hi";
}
}
# $x now holds a type object returned from the
# anonymous class definition</pre>
<p>If a variable is declared to be of a certain type, but never defined, then it will evaluate to the type object of that type. As such, type objects can often turn up in places where "undefined" or "null" would in other languages:</p>
<pre class="code"># perl6 -e 'my Int $a; sub f(Int $x) { $x + 1 }; f($a);'
Invocant requires an instance, but a type object was passed</pre>
<a name="t16"><h1 class="title">16 Grammars</h1></a> <p class="subtitle">Parsing and interpreting text</p></a> <p>Grammars are a powerful tool used to destructure text and often to return data structures that have been created by interpreting that text.</p>
<p>For example, Perl 6 is parsed and executed using a Perl 6-style grammar.</p>
<p>An example that's more practical to the common Perl 6 user is the <a href="https://github.com/moritz/json">JSON::Tiny module</a> , which can deserialize any valid JSON file, however the deserializing code is written in less than 100 lines of simple, extensible code.</p>
<p>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.</p>
<a name="t16.1"$class><h1>16.1 Named Regexes </h1></a>
<p>The main ingredient of grammars is named <a href="/language/regexes">regexes</a> . While the syntax of <a href="/language/regexes">Perl 6 Regexes</a> is outside the scope of this document, <i>named</i> regexes have a special syntax, similar to subroutine definitions: <div class="marginale">In fact, named regexes can even take extra arguments, using the same syntax as subroutine parameter lists</div> </p>
<pre class="code">my <b>regex number {</b> \d+ [ \. \d+ ]? <b>}</b>
</pre>
<p>In this case, we have to specify that the regex is lexically scoped using the <span class="code">my </span> keyword, because named regexes are normally used within grammars.</p>
<p>Being named gives us the advantage of being able to easily reuse the regex elsewhere:</p>
<pre class="code">say "32.51" ~~ <b>&amp;number</b> ;
say "15 + 4.5" ~~ / <b> &lt;number> </b> \s* '+' \s* <b> &lt;number> </b> /
</pre>
<p> <b> <span class="code">regex </span> </b> isn't the only declarator for named regexes -- in fact, it's the least common. Most of the time, the <b> <span class="code">token </span> </b> or <b> <span class="code">rule </span> </b> declarators are used. These are both <i>ratcheting</i> , 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:</p>
<pre class="code">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 .+
</pre>
<p>The only difference between the <span class="code">token </span> and <span class="code">rule </span> declarators is that the <span class="code">rule </span> declarator causes <a href="/language/regexes#Sigspace"> <span class="code">:sigspace </span> </a> to go into effect for the Regex:</p>
<pre class="code">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;
</pre>
<a name="t16.2"$class><h1>16.2 Creating Grammars </h1></a>
<p class="subtitle">Group of named regexes that form a formal grammar</p></a> <p> <a href="/type/Grammar">Grammar</a> is the superclass that classes automatically get when they are declared with the <span class="code">grammar </span> keyword instead of <span class="code">class </span> . Grammars should only be used to parse text; if you wish to extract complex data, an <a href="/language/grammars#Action_Objects">action object</a> is recommended to be used in conjunction with the grammar.</p>
<a name="t16.3"$class><h1>16.3 Action Objects</h1></a>
<p>A successful grammar match gives you a parse tree of <a href="/type/Match">Match</a> 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.</p>
<p>To avoid the need for diving deep into a match tree, you can supply an <i>actions</i> 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 <a href="/type/Match">Match</a> object as a positional argument. If no such method exists, it is skipped.</p>
<p>Here is a contrived example of a grammar and actions in action:</p>
<pre class="code">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
</pre>
<p>An instance of <span class="code">TestActions </span> is passed as named argument <span class="code">actions </span> to the <a href="">parse</a> call, and when token <span class="code">TOP </span> has matched successfully, it automatically calls method <span class="code">TOP </span> , passing the match object as an argument.</p>
<p>To make it clear that the argument is a match object, the example uses <span class="code">$/ </span> as a parameter name to the action method, though that's just a handy convention, nothing intrinsic. <span class="code">$match </span> would have worked too. (Though using <span class="code">$/ </span> does give the advantage of providing <span class="code">$&lt;capture> </span> as a shortcut for <span class="code">$/&lt;capture> </span> ).</p>
<p>A slightly more involved example follows:</p>
<pre class="code">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()";
}
</pre>
<p>This produces the following output:</p>
<pre class="code">Key: second Value: b
Key: hits Value: 42
Key: perl Value: 6
</pre>
<p>Rule <span class="code">pair </span> , which parsed a pair separated by an equals sign, aliases the two calls to token <span class="code">identifier </span> to separate capture names to make them available more easily and intuitively. The corresponding action method constructs a <a href="/type/Pair">Pair</a> object, and uses the <span class="code">.made </span> property of the sub match objects. So it (like the action method <span class="code">TOP </span> too) exploits the fact that action methods for submatches are called before those of the calling/outer regex. So action methods are called in <a href="https://en.wikipedia.org/wiki/Tree_traversal#Post-order">post-order</a> .</p>
<p>The action method <span class="code">TOP </span> simply collects all the objects that were <span class="code">.made </span> by the multiple matches of the <span class="code">pair </span> rule, and returns them in a list.</p>
<p>Also note that <span class="code">KeyValuePairsActions </span> was passed as a type object to method <span class="code">parse </span> , which was possible because none of the action methods use attributes (which would only be available in an instance).</p>
<p>In other cases, action methods might want to keep state in attributes. Then of course you must pass an instance to method parse.</p>
<p>Note that <span class="code">token </span> <span class="code">ws </span> is special: when <span class="code">:sigspace </span> is enabled (and it is when we are using <span class="code">rule </span> ), it replaces certain whitespace sequences. This is why the spaces around the equals sign in <span class="code">rule pair </span> work just fine and why the whitespace before closing <span class="code">} </span> does not gobble up the newlines looked for in <span class="code">token TOP </span> .</p>
<a name="t17"><h1 class="title">17 Input/Output</h1></a> <p class="subtitle">File-related operations</p></a> <p>Here we present a quick overview of the file-related input/output operations, detailed documentation can be found in the documentation for the <a href="/type/IO">IO</a> role, as well as the <a href="/type/IO::Handle">IO::Handle</a> and <a href="/type/IO::Path">IO::Path</a> types.</p>
<a name="t17.1"$class><h1>17.1 Reading from files</h1></a>
<p>One way to read the contents of a file is to open the file via the <span class="code">open </span> function with the <span class="code">:r </span> (read) file mode option and slurp in the contents:</p>
<pre class="code">my $fh = open "testfile", :r;
my $contents = $fh.slurp-rest;
$fh.close;</pre>
<p>Here we explicitly close the file handle using the <span class="code">close </span> method on the <span class="code">IO::Handle </span> 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:</p>
<pre class="code">my $contents = "testfile".IO.slurp;
# or in procedural form:
my $contents = slurp "testfile"</pre>
<p>By adding the <span class="code">IO </span> 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 <span class="code">slurp </span> takes care of opening and closing the file for you.</p>
<a name="t17.1.1"$class><h2>17.1.1 Line by line</h2></a>
<p>Of course, we also have the option to read a file line-by-line. The new line separator (e.g. $*IN.nl-in) will be excluded.</p>
<pre class="code">for 'huge-csv'.IO.lines -> $line {
# Do something with $line
}
# or if you'll be processing later
my @lines = 'huge-csv'.IO.lines;</pre>
<a name="t17.2"$class><h1>17.2 Writing to files</h1></a>
<p>To write data to a file, again we have the choice of the traditional method of calling the <span class="code">open </span> function -- this time with the <span class="code">:w </span> (write) option -- and printing the data to the file:</p>
<pre class="code">my $fh = open "testfile", :w;
$fh.print("data and stuff\n");
$fh.close;</pre>
<p>Or equivalently with <span class="code">say </span> , thus the explicit newline is no longer necessary:</p>
<pre class="code">my $fh = open "testfile", :w;
$fh.say("data and stuff");
$fh.close;</pre>
<p>We can simplify this by using <span class="code">spurt </span> to open the file in write mode, writing the data to the file and closing it again for us:</p>
<pre class="code">spurt "testfile", "data and stuff\n";</pre>
<p>By default all (text) files are written as UTF-8, however if necessary, an explicit encoding can be specified via the <span class="code">:enc </span> option:</p>
<pre class="code">spurt "testfile", "latin1 text: äöüß", enc => "latin1";</pre>
<p>To append to a file, specify the <span class="code">:a </span> option when opening the file handle explicitly,</p>
<pre class="code">my $fh = open "testfile", :a;
$fh.print("more data\n");
$fh.close;</pre>
<p>or equivalently with <span class="code">say </span> , thus the explicit newline is no longer necessary,</p>
<pre class="code">my $fh = open "testfile", :a;
$fh.say("more data");
$fh.close;</pre>
<p>or even simpler with the <span class="code">:append </span> option in the call to <span class="code">spurt </span> :</p>
<pre class="code">spurt "testfile", "more data\n", :append;</pre>
<p>To explicitly write binary data to a file, open it with the <span class="code">:bin </span> option. The input/output operations then will take place using the <span class="code">Buf </span> type instead of the <span class="code">Str </span> type.</p>
<a name="t17.3"$class><h1>17.3 Checking files and directories</h1></a>
<p>Use the <span class="code">e </span> method on an <span class="code">IO::Handle </span> object to test whether the file or directory exists.</p>
<pre class="code">if "nonexistent_file".IO.e {
say "file exists";
}
else {
say "file doesn't exist";
}</pre>
<p>It is also possible to use the colon pair syntax to achieve the same thing:</p>
<pre class="code">if "path/to/file".IO ~~ :e {
say 'file exists';
}
my $file = "path/to/file";
if $file.IO ~~ :e {
say 'file exists';
}</pre>
<p>Similarly to the file existence check, one can also check to see if a path is a directory. For instance, assuming that the file <span class="code">testfile </span> and the directory <span class="code">lib </span> exist, we would obtain from the existence test method <span class="code">e </span> the same result, namely that both exist:</p>
<pre class="code">say "testfile".IO.e; # True
say "lib".IO.e; # True</pre>
<p>However, since only one of them is a directory, the directory test method <span class="code">d </span> will give a different result:</p>
<pre class="code">say "testfile".IO.d; # False
say "lib".IO.d; # True</pre>
<p>Naturally the tables are turned if we check to see if the path is a file via the file test method <span class="code">f </span> :</p>
<pre class="code">say "testfile".IO.f; # True
say "lib".IO.f; # False</pre>
<a name="t17.4"$class><h1>17.4 Getting a directory listing</h1></a>
<p>To list the contents of the current directory, use the <span class="code">dir </span> function. It returns a list of <a href="">IO::Path</a> objects.</p>
<pre class="code">say dir; # "/path/to/testfile".IO "/path/to/lib".IO</pre>
<p>To list the files and directories in a given directory, simply pass a path as an argument to <span class="code">dir </span> :</p>
<pre class="code">say dir "/etc/"; # "/etc/ld.so.conf".IO "/etc/shadow".IO ....</pre>
<a name="t17.5"$class><h1>17.5 Creating and removing directories</h1></a>
<p>To create a new directory, simply call the <span class="code">mkdir </span> function with the directory name as its argument:</p>
<pre class="code">mkdir "newdir";</pre>
<p>The function returns the name of the created directory on success and <span class="code">Nil </span> on failure. Thus the standard Perl idiom works as expected:</p>
<pre class="code">mkdir "newdir" or die "$!";</pre>
<p>Use <span class="code">rmdir </span> to remove <i>empty</i> directories:</p>
<pre class="code">rmdir "newdir" or die "$!";</pre>
TODO: base on https://github.com/perl6/specs/blob/master/S32-setting-library/IO.pod?
TODO: http://doc.perl6.org/type/IO::Handle has close but no open
<a name="t18"><h1 class="title">18 Modules</h1></a> <p class="subtitle">How to create, use and distribute Perl 6 modules</p></a> <a name="t18.1"$class><h1>18.1 Creating and Using Modules</h1></a>
<p>A module is usually a source file or set of source files <div class="marginale">Technically a module is a set of <i>compunits</i> which are usually files but could come from anywhere as long as there is a <i>compunit repository</i> that can provide it. See <a href="https://design.perl6.org/S11.html">S11</a> .</div> that expose Perl 6 constructs. These are typically packages ( <a href="/language/objects#Classes">classes</a> , <a href="/language/objects#Roles">roles</a> , <a href="Grammar">grammars</a> ), <a href="/language/functions">subroutines</a> , and sometimes <a href="/language/variables">variables</a> . In Perl 6 <i>module</i> can also refer to a type of package declared with the <span class="code">module </span> keyword (see example below) but here we mostly mean "module" as a set of source files in a namespace.</p>
<a name="t18.1.1"$class><h2>18.1.1 Basic Structure</h2></a>
<p>Module distributions (in the <i>set of related source files</i> 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 <span class="code">README </span> and a <span class="code">LICENSE </span> file, a <span class="code">lib </span> directory for the source files &mdash; which may be individually referred to as modules and/or may themselves define modules with the <span class="code">module </span> keyword <div class="marginale">As <a href="https://design.perl6.org/S11.html#Units">synopsis S11</a> says: Confusing? Yes it is.</div> , a <span class="code">t </span> directory for tests, and possibly a <span class="code">bin </span> directory for executable programs and scripts.</p>
<p>Source files generally use the standard <span class="code">.pm </span> extension, and scripts or executables use <span class="code">.pl </span> . However, if you wish to highlight that the file is written in Perl 6 you can use the <span class="code">.pm6 </span> extension for modules, and the <span class="code">.p6 </span> extension for scripts. Test files still use the normal <span class="code">.t </span> extension.</p>
<a name="t18.1.2"$class><h2>18.1.2 Loading and Basic Importing</h2></a>
<p>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.</p>
<a name="t18.1.2.1"$class><h3>18.1.2.1 need </h3></a>
<p> <span class="code">need </span> loads a <span class="code">compunit </span> at compile time.</p>
<pre class="code">need MyModule;</pre>
<p>Any packages in the namespace defined within will also be available.</p>
<pre class="code"># MyModule.pm
unit module MyModule;
class MyModule::Class { ... }</pre>
<p> <span class="code">MyModule::Class </span> will be defined when <span class="code">MyModule </span> is loaded.</p>
class Class { ... } won't get exported automatically on loading...not sure if bug or..
<a name="t18.1.2.2"$class><h3>18.1.2.2 use </h3></a>
<p> <span class="code">use </span> loads and then imports from a compunit at compile time.</p>
<pre class="code">use MyModule;</pre>
<p>It is equivalent to:</p>
<pre class="code"> <a href="/language/modules#need">need</a> MyModule;
import MyModule;
</pre>
<a name="t18.1.2.3"$class><h3>18.1.2.3 require </h3></a>
<p> <span class="code">require </span> loads a compunit and imports definite symbols at runtime.</p>
<pre class="code">sub load-mymodule {
say "loading MyModule";
require MyModule;
}
load-mymodule();</pre>
<p>The compunit name can be in a runtime variable if you put it inside an indirect lookup.</p>
<pre class="code">sub load-a-module($name){
require ::($name);
}
load-a-module('MyModule');</pre>
<p>To import symbols you must define them at compile time.</p>
<pre class="code">sub do-something {
require MyModule &lt;&amp;something>;
something() # &amp;something will be defined here
}
do-something();
# &amp;something will not be defined here</pre>
<p>If <span class="code">MyModule </span> doesn't export <span class="code">&amp;something </span> then it will fail.</p>
<a name="t18.1.3"$class><h2>18.1.3 Exporting and Selective Importing</h2></a>
<a name="t18.1.3.1"$class><h3>18.1.3.1 is export</h3></a>
<p>Packages, subroutines, variables, constants and enums are exported by marking them with the <a href="">is export</a> trait.</p>
<pre class="code">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 {};
</pre>
<p>As with all traits, if applied to a routine, "is export" should appear after any argument list.</p>
<pre class="code">sub foo (Str $string) is export { ... }
</pre>
<p>You can pass named parameters to <span class="code">is export </span> to group symbols for exporting then the importer can pick and choose. There are three predefined tags: <span class="code">ALL </span> , <span class="code">DEFAULT </span> and <span class="code">MANDATORY </span> .</p>
<pre class="code"># 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) { ... }
</pre>
<pre class="code"># 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
</pre>
<a name="t18.1.3.2"$class><h3>18.1.3.2 UNIT::EXPORT::*</h3></a>
<p>Beneath the surface <span class="code">is export </span> is adding the symbols to a <span class="code">UNIT </span> scoped package in the <span class="code">EXPORT </span> namespace. For example, <span class="code">is export(:FOO) </span> will add the target to the <span class="code">UNIT::EXPORT::FOO </span> package. This is what Perl 6 is really using to decide what to import.</p>
<pre class="code">unit module MyModule;
sub foo is export { ... }
sub bar is export(:other) { ... }
</pre>
<p>Is the same as:</p>
<pre class="code">unit module MyModule;
my package EXPORT::DEFAULT {
our sub foo { ... }
}
my package EXPORT::other {
our sub bar { ... }
}
</pre>
<p>For most purposes <span class="code">is export </span> is sufficient but the <span class="code">EXPORT </span> packages are useful when you want to produce the exported symbols dynamically. For example:</p>
<pre class="code"># 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"() };
}
}
}
</pre>
<pre class="code"># main.pl
use MyModule;
say sqrt-of-four; #-> 2
say log-of-zero; #-> -Inf
</pre>
<a name="t18.1.3.3"$class><h3>18.1.3.3 EXPORT</h3></a>
<p>You can export arbitrary symbols with an <span class="code">EXPORT </span> sub. <span class="code">EXPORT </span> must return a <a href="">Map</a> , 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.</p>
<pre class="code"># 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
}
}
</pre>
<pre class="code"># main.pl
use lib 'lib';
use MyModule;
say $var;
say @array;
say %hash;
doit();
say ShortName.new; #-> MyModule::Class.new
</pre>
<p>Note, <span class="code">EXPORT </span> can't be declared inside a package because presently rakudo (2015.09) seems to treat <span class="code">EXPORT </span> as part of the compunit rather than the package.</p>
<p>Whereas <span class="code">UNIT::EXPORT </span> packages deal with the named parameters passed to <span class="code">use </span> , the <span class="code">EXPORT </span> sub handles positional parameters. If you pass positional parameters to <span class="code">use </span> they will be passed to <span class="code">EXPORT </span> . If a positional is passed the module no longer exports default symbols. You may still import them explicitly by passing <span class="code">:DEFAULT </span> to <span class="code">use </span> along with your positional parameters.</p>
<pre class="code"># 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!" }
</pre>
<pre class="code"># main.pl
use lib 'lib';
use MyModule 'foo';
say foo.new(); #MyModule::Class.new
always(); #OK - is imported
shy(); #FAIL - won't be imported
</pre>
<a name="t18.2"$class><h1>18.2 Distributing Modules</h1></a>
<p>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 <a href="https://modules.perl6.org">Perl 6 modules directory</a> . <span class="code">:) </span> </p>
<p>For now, the process requires that you use git for your module's version control.</p>
<p>The instructions herein require that you have a <a href="https://www.github.com">GitHub</a> account so that your module can be shared from its GitHub repository.</p>
<p>To share your module, do the following:</p>
<ul><li><p>Create a project directory named after your module. For example, if your module is <span class="code">Vortex::TotalPerspective </span> , then create a project directory named <span class="code">Vortex-TotalPerspective </span> . This project directory name will also be used as the GitHub repo name.</p>
</li></ul> <ul><li><p>Make your project directory look like this:</p>
<pre class="code">Vortex-TotalPerspective/
|-- lib
| `-- Vortex
| `-- TotalPerspective.pm
|-- LICENSE
|-- META.info
|-- README.md
`-- t
`-- basic.t</pre>
<p>If your project contains other modules that help the main module do its job, they should go in your lib directory like so:</p>
<pre class="code">lib
`-- Vortex
|-- TotalPerspective.pm
`-- TotalPerspective
|-- FairyCake.pm
`-- Gargravarr.pm</pre>
</li></ul> <ul><li><p>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 <span class="code">resources </span> sub-directory of your project. </p>
</li></ul> <ul><li><p>The <span class="code">README.md </span> file is a <a href="https://help.github.com/articles/markdown-basics/">markdown-formatted</a> text file, which will later be automatically rendered as HTML by GitHub.</p>
</li></ul> <ul><li><p>Regarding the <span class="code">LICENSE </span> 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 <a href="https://github.com/rakudo/rakudo/blob/nom/LICENSE">its license</a> into your own <span class="code">LICENSE </span> file.</p>
</li></ul> <ul><li><p>If you don't yet have any tests, you can leave out the <span class="code">t </span> directory and <span class="code">basic.t </span> file for now. For more info on how to write tests (for now), you might have a look at how other modules use <span class="code">Test </span> . It's quite similar to Perl 5's <span class="code">Test::More </span> .</p>
</li></ul> <ul><li><p>To document your modules, use <a href="https://design.perl6.org/S26.html">Perl 6 Pod</a> 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. <div class="marginale"> 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 <span class="code">bin </span> directory. If you have extra docs (in addition to the Pod docs in your module(s)), create a <span class="code">doc </span> directory for them. If you'd like a graphical logo to appear next to your module at the module directory, create a <span class="code">logotype </span> directory and put into it a <span class="code">logo_32x32.png </span> file. At some point, you might also consider adding <span class="code">CONTRIBUTORS </span> , <span class="code">NEWS </span> , <span class="code">TODO </span> , or other files. </div> </p>
</li></ul> <ul><li><p>Make your <span class="code">META.info </span> file look something like this:</p>
<pre class="code"> {
"perl" : "6.*",
"name" : "Vortex::TotalPerspective",
"version" : "0.1.0",
"description" : "Wonderful simulation to get some perspective.",
"authors" : [ " R<Your Name> " ],
"provides" : {
"Vortex::TotalPerspective" : "lib/Vortex/TotalPerspective.pm"
},
"depends" : [ ],
"resources" : [ ],
"source-url" : "git://github.com/ R<you> /Vortex-TotalPerspective.git"
}
</pre>
<p>For choosing a version numbering scheme, perhaps use "major.minor.patch" (see <a href="https://design.perl6.org/S11.html#Versioning">the spec on versioning</a> 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.</p>
<p>The <span class="code">authors </span> section includes a list of all the module authors. In the case there is only one author, a single element list must be supplied. </p>
<p>In the <span class="code">provides </span> section, include all the namespaces provided by your distribution and set <span class="code">perl </span> version to the minimum perl version your module works with</p>
<p>The <span class="code">resources </span> section is optional, but, if present, should contain a list of the files in your <span class="code">resources </span> 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 <span class="code">%?RESOURCES </span> Hash indexed on the name provided.</p>
<p>The <a href="https://github.com/jonathanstowe/Test-META/">Test::META module</a> can help you check the correctness of the META.info file.</p>
</li></ul> <ul><li><p>Put your project under git version control if you haven't done so already.</p>
</li></ul> <ul><li><p>Once you're happy with your project, create a repo for it at GitHub. See <a href="https://help.github.com/">GitHub's help docs</a> 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.</p>
</li></ul> <ul><li><p>Push your project to GitHub.</p>
</li></ul> <ul><li><p>Create a PR on <a href="https://github.com/perl6/ecosystem">ecosystem</a> adding your module to META.list, or Ping someone on IRC (#perl6 at freenode) to get help having it added.</p>
</li></ul> <ul><li><p>After the pull request has been accepted, wait for an hour. If your module doesn't show up on <a href="">https://modules.perl6.org/</a> , please view the log file at <a href="">https://modules.perl6.org/log/update.log</a> to see if it identifies an error with your module or meta file.</p>
</li></ul> <p> <b>That's it! Thanks for contributing to the Perl 6 community!</b> </p>
<p>If you'd like to try out installing your module, use the panda module installer tool which is included with Rakudo Star Perl 6:</p>
<pre class="code">panda install Vortex::TotalPerspective
</pre>
<p>This will download your module to its own working directory ( <span class="code">~/.panda </span> ), build it there, and install the module into <span class="code">~/.perl6 </span> .</p>
<p>To use <span class="code">Vortex::TotalPerspective </span> from your scripts, just write <span class="code">use Vortex::TotalPerspective </span> , and your Perl 6 implementation will know where to look for the module file(s).</p>
<a name="t19"><h1 class="title">19 Meta-Object Protocol</h1></a> <p class="subtitle">Introspection and the Perl 6 Object System</p></a> <p>Perl 6 is built on a meta object layer. That means that there are objects (the <i>meta objects</i> ) that control how various object-oriented constructs (such as classes, roles, methods, attributes, enums, ...) behave.</p>
<p>To get a feeling for the meta object for <span class="code">class </span> , here is the same example twice: once as normal declarations in Perl 6, and once expressed through the meta model:</p>
<pre class="code">class A {
method x() { say 42 }
}
A.x();</pre>
<p>corresponds to:</p>
<pre class="code">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();</pre>
<p>(except that the declarative form runs at compile time, and the latter form does not).</p>
<p>The meta object behind an object can be obtained with <span class="code">$obj.HOW </span> , where HOW stands for Higher Order Workings (or, <i>HOW the *%@$ does this work?</i> ).</p>
<p>Here, the calls with <span class="code">.^ </span> are calls to the meta object, so <span class="code">A.^compose </span> is a shortcut for <span class="code">A.HOW.compose(A) </span> . 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).</p>
<p>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.</p>
<a name="t19.1"$class><h1>19.1 Metamethods</h1></a>
<p>These are introspective macros that resemble method calls.</p>
<p>Metamethods are generally named with ALLCAPS, and it is considered good style to avoid using 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:</p>
<pre class="code">#| 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"</pre>
<a name="t19.1.1"$class><h2>19.1.1 WHAT </h2></a>
<p>The type object of the type.</p>
<p>For example <span class="code">42.WHAT </span> returns the <span class="code">Int </span> type object.</p>
<a name="t19.1.2"$class><h2>19.1.2 WHICH </h2></a>
<p>The object's identity value. This can be used for hashing and identity comparison, and is how the <span class="code">=== </span> infix operator is implemented.</p>
<a name="t19.1.3"$class><h2>19.1.3 WHO </h2></a>
<p>The package supporting the object.</p>
<a name="t19.1.4"$class><h2>19.1.4 WHERE </h2></a>
<p>The memory address of the object. Note that this is not stable in implementations with moving/compacting garbage collectors. Use <span class="code">WHICH </span> for a stable identity indicator.</p>
<a name="t19.1.5"$class><h2>19.1.5 HOW </h2></a>
<p>The metaclass object: "Higher Order Workings".</p>
<a name="t19.1.6"$class><h2>19.1.6 WHY </h2></a>
<p>The attached Pod value.</p>
<a name="t19.1.7"$class><h2>19.1.7 DEFINITE </h2></a>
<p>The object has a valid concrete representation.</p>
<p>Returns <span class="code">True </span> for instances and <span class="code">False </span> for type objects.</p>
<a name="t19.1.8"$class><h2>19.1.8 VAR </h2></a>
<p>Returns the underlying <span class="code">Scalar </span> object, if there is one.</p>
<p>The presence of a <span class="code">Scalar </span> object indicates that the object is "itemized".</p>
<pre class="code">.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</pre>
<a name="t19.2"$class><h1>19.2 Structure of the meta object system</h1></a>
<p> <b>Note:</b> this documentation largely reflects the meta object system as implemented by the <a href="http://rakudo.org/">Rakudo Perl 6 compiler</a> , since the <a href="http://design.perl6.org/">design documents</a> are very light on details.</p>
<p>For each type declarator keyword, such as <span class="code">class </span> , <span class="code">role </span> , <span class="code">enum </span> , <span class="code">module </span> , <span class="code">package </span> , <span class="code">grammar </span> or <span class="code">subset </span> , there is a separate meta class in the <span class="code">Metamodel:: </span> namespace. (Rakudo implements them in the <span class="code">Perl6::Metamodel:: </span> namespace, and then maps <span class="code">Perl6::Metamodel </span> to <span class="code">Metamodel </span> ).</p>
<p>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 <a href="/type/Metamodel::RoleContainer">role Metamodel::RoleContainer</a> implements the functionality that a type can hold roles and <a href="/type/Metamodel::ClassHOW">Metamodel::ClassHOW</a> , which is the meta class behind the <span class="code">class </span> keyword, does this role.</p>
<a name="t19.2.1"$class><h2>19.2.1 Bootstrapping concerns</h2></a>
<p>You might wonder how <span class="code">Metamodel::ClassHOW </span> can be a class, when being a class is defined in terms of <span class="code">Metamodel::ClassHOW </span> , or how the roles responsible for role handling can be roles. The answer is <i>by magic</i> .</p>
<p>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 <span class="code">knowhow </span> , which is used to bootstrap its own classes and roles implementation. <span class="code">knowhow </span> is built on primitives that the virtual machine under NQP provides.</p>
<p>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 a NQP-level routine instead of normal <a href="/type/Routine">Routine</a> object, or a bootstrap-attribute instead of <a href="/type/Attribute">Attribute</a> .</p>
<a name="t19.2.2"$class><h2>19.2.2 Composition time and static reasoning</h2></a>
<p>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.</p>
<p>So to get the best of both worlds, there is a time when a type transitions from mutable to immutable. This is called <i>composition</i> , and for syntactically declared types, it happens when the type declaration is fully parsed (so usually when the closing curly brace is parsed).</p>
<p>If you create types through the meta-object system directly, you must call <span class="code">.^compose </span> on them before they become fully functional.</p>
<p>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.</p>
<a name="t19.2.3"$class><h2>19.2.3 Power and Responsibility</h2></a>
<p>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.</p>
<p>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.</p>
<p>So be extra careful and thoughtful when writing meta types.</p>
<a name="t19.2.4"$class><h2>19.2.4 Power, Convenience and Pitfalls</h2></a>
<p>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.</p>
<p>For example, when you write <span class="code">my $x = 42 </span> and then proceed to call methods on <span class="code">$x </span> , most of these methods end up acting on the <a href="/type/Int">integer</a> 42, not on the <a href="/type/Scalar">scalar container</a> 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 <span class="code">my $t = MyType; ... ; $t.^compose </span> you are composing the Scalar that the <span class="code">$ </span> -sigiled variable implies, not <span class="code">MyType </span> .</p>
<p>The consequence is that you need to have a rather detailed understanding of the subleties 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.</p>
<a name="t20"><h1 class="title">20 Native Calling Interface</h1></a> <p class="subtitle">Call into dynamic libraries that follow the C calling convention</p></a> <a name="t20.1"$class><h1>20.1 Getting Started</h1></a>
<p> <span class="indexed$additional-class"><a name="r68"></a></span> </p>
<p>The simplest imaginable use of NativeCall would look something like this:</p>
<pre class="code">use NativeCall;
sub some_argless_function() is native('something') { * }
some_argless_function();</pre>
<p>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) will be added for you.</p>
<p>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.</p>
<p>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.</p>
<a name="t20.2"$class><h1>20.2 Changing names</h1></a>
<p>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.</p>
<p>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.</p>
<pre class="code">module Foo;
use NativeCall;
our sub init() is native('foo') is symbol('FOO_INIT') { * }</pre>
<p>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 <span class="code">Foo::init </span> , 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).</p>
<a name="t20.3"$class><h1>20.3 Passing and Returning Values</h1></a>
<p>Normal Perl 6 signatures and the <span class="code">returns </span> trait are used in order to convey the type of arguments a native function expects and what it returns. Here is an example.</p>
<pre class="code">sub add(int32, int32) returns int32 is native("calculator") { * }</pre>
<p>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).</p>
<pre class="code">int8 (char in C)
int16 (short in C)
int32 (int in C)
int64 (64-bit explicited int in C like int64_t in C99)
long (32- or 64-bit, depends what long means locally)
longlong (at least 64bits, what long long means locally)
num32 (float in C)
num64 (double in C)
Str (C string)
CArray[int32] (int* in C, an array of integers)
Pointer[void] (void* in C, can point to all other types)
bool (bool from C99)
size_t (size_t in C)</pre>
<p>Don't use Perl 6 native type like <span class="code">int </span> or <span class="code">num </span> they could lead you to unwanting boundary issue between 32 bits and 64 bits system.</p>
<p>Note that the lack of a <span class="code">returns </span> trait is used to indicate void return type. Do <i>not</i> use the 'void' type anywhere except in the Pointer parameterization.</p>
<p>For strings, there is an additional "encoded" trait to give some extra hints on how to do the marshalling.</p>
<pre class="code">sub message_box(Str is encoded('utf8')) is native('gui') { * }</pre>
<p>To specify how to marshal string return types, just apply this trait to the routine itself.</p>
<pre class="code">sub input_box() returns Str is encoded('utf8') is native('gui') { * }</pre>
<p>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.</p>
<p>For string arguments that are specified as <span class="code">const char * </span> it is necessary to tell Perl not to free the memory allocated to the C string after the function returns using <span class="code">explicitly-manage </span> :</p>
<pre class="code"># C prototype is set_foo(const char * foo)</pre>
<pre class="code">sub set_foo(Str) is native('foo') { * }</pre>
<pre class="code">my $string = "FOO";
explicitly-manage($string);
set_foo($string);</pre>
<a name="t20.4"$class><h1>20.4 Basic use of Pointers</h1></a>
<p>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.</p>
<pre class="code">sub Foo_init() returns Pointer is native("foo") { * }
sub Foo_free(Pointer) is native("foo") { * }</pre>
<p>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:</p>
<pre class="code">class FooHandle is repr('CPointer') {
# 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() }
method free() { Foo_free(self) }
}</pre>
<p>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.</p>
<p>Of course, you can always have an empty class:</p>
<pre class="code">class DoorHandle is repr('CPointer') { }</pre>
<p>And just use the class as you would use Pointer, but with potential for better type safety and more readable code.</p>
<p>Once again, type objects are used to represent nulls.</p>
<a name="t20.5"$class><h1>20.5 Arrays</h1></a>
<p>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.</p>
<p>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.</p>
<p>Here is an example of passing a C array.</p>
<pre class="code">sub RenderBarChart(Str, int, 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);</pre>
<p>Note that binding was used to <span class="code">@titles </span> , <i>not</i> 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 <span class="code">@ </span> sigil and just use <span class="code">$ </span> all the way when using NativeCall. :-)</p>
<pre class="code">my $titles = CArray[Str].new;
$titles[0] = 'Me';
$titles[1] = 'You';
$titles[2] = 'Hagrid';</pre>
<p>Getting return values for arrays works out just the same.</p>
<p>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:</p>
<pre class="code">sub get_n_ints(CArray[int], int) returns Int is native('ints');</pre>
<p>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:</p>
<pre class="code">my $ints = CArray[int].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);</pre>
<p>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.</p>
<p>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! :-)</p>
<a name="t20.6"$class><h1>20.6 Structs</h1></a>
<p>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:</p>
<pre class="code">class Point is repr('CStruct') {
has num64 $.x;
has num64 $.y;
}</pre>
<p>The attributes can only be of the types that NativeCall knows how to marshall 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!</p>
<p>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.</p>
<p>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: <span class="code">$!struct-member := StructObj.new; </span> </p>
<p>As you may have predicted by now, a null is represented by the type object of the struct type.</p>
<a name="t20.6.1"$class><h2>20.6.1 CUnions</h2></a>
<p>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 <span class="code">union </span> definition; using the <span class="code">CUnion </span> representation:</p>
<pre class="code">class MyUnion is repr('CUnion') {
has int32 $.flags32;
has int64 $.flags64;
}
say nativesizeof(MyUnion.new); # 8, ie. max(sizeof(MyUnion.flags32), sizeof(MyUnion.flags64))</pre>
<a name="t20.6.2"$class><h2>20.6.2 Embedding CStructs and CUnions</h2></a>
<p>CStructs and CUnions can be in turn referenced by -- or embedded into -- a surrounding CStruct and CUnion. To say the former we use <span class="code">has </span> as usual, and to do the latter we use use the <span class="code">HAS </span> declarator instead:</p>
<pre class="code">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)</pre>
<a name="t20.7"$class><h1>20.7 Typed Pointers</h1></a>
TODO
<p>TBD more</p>
<p>You can type your <span class="code">Pointer </span> with passing the type as parameter. It works with native type but also <span class="code">CArray </span> and <span class="code">CStruct </span> defined type. 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 embeded in a <span class="code">CStruct </span> .</p>
<p>You have to call <span class="code">.deref </span> on it to access the embeded type.</p>
<pre class="code">my Pointer[int32] $p; #For a pointer on int32;
my Pointer[MyCstruct] $p2 = some_c_routine();
my MyCstruct $mc = $p2.deref;
say $mc.field1;</pre>
<a name="t20.8"$class><h1>20.8 Buffers and Blobs</h1></a>
TODO
<p>TBD</p>
<a name="t20.9"$class><h1>20.9 Function arguments</h1></a>
<p>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:</p>
<pre class="code"># void SetCallback(int (*callback)(const char *))
my sub SetCallback(&amp;callback (Str --> int32)) is native('mylib') { * }</pre>
<p>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.</p>
<a name="t20.10"$class><h1>20.10 Library Paths and Names</h1></a>
TODO
<p>TBD more</p>
<p>The <span class="code">native </span> trait accept simple lib name or a full path. It's common to have the lib parameter defined as a constant than can be modified via an environment variable. This is an example from the mysql binding in <span class="code">DBIIsh </span> </p>
<pre class="code">constant LIB = %*ENV&lt;DBIISH_MYSQL_LIB> || 'mysqlclient';
# and later
sub mysql_affectied_rows( .. ) returns int32 is native(LIB)</pre>
<p>You can also put incomplete path like './foo', NativeCall will automaticly put the right extension according to the plateform specification.</p>
<a name="t20.10.1"$class><h2>20.10.1 ABI/API Version</h2></a>
<p>If you write <span class="code">native('libfoo') </span> NativeCall will search libfoo.so under Unix like system (libfoo.dynlib on Os X). In most modern system it will requiere you or the user of your module to install the develepment package because it's recommanded 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.</p>
<p>To avoid that, the <span class="code">native </span> trait allow 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 does not care for minor)</p>
<pre class="code">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
#From DBIish Pg driver
constant LIB = %*ENV&lt;DBIISH_PG_LIB> || ('pq', v5);</pre>
<a name="t20.10.2"$class><h2>20.10.2 Routine</h2></a>
<p>the <span class="code">native </span> trait also accept a <span class="code">Callable </span> as argument, allowing you to provide your own way to handle the way it will find the library file to load.</p>
<pre class="code">sub foo is native(sub {'libfoo.so.42'});</pre>
<a name="t20.10.3"$class><h2>20.10.3 Calling into the standard library</h2></a>
<p>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 <span class="code">Str </span> type object as the argument to <span class="code">is native </span> , so <span class="code">is native(Str) </span> .</p>
<p>For example on a UNIX-like operating system, you could use the following code to print the home directory of the current user:</p>
<pre class="code">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(int $uid) returns PwStruct is native(Str) {};
say getpwuid(getuid()).pw_dir;</pre>
<p>Though of course <span class="code">$*HOME </span> is a much easier way :-)</p>
<a name="t20.11"$class><h1>20.11 Exported variables</h1></a>
<p>Variables exported by a library -- also named "global" or "extern" variables -- can be accessed using <span class="code">cglobal </span> . For example:</p>
<pre class="code">my $var := cglobal('libc.so.6', 'errno', int)</pre>
<p>This code binds to <span class="code">$var </span> a new <a href="/type/Proxy">Proxy</a> object that redirects all its accesses to the integer variable named "errno" as exported by the "libc.so.6" library.</p>
<a name="t20.12"$class><h1>20.12 C++ Support</h1></a>
<p>NativeCall offer a support to use class and method from C++ as show in <a href="">https://github.com/rakudo/rakudo/blob/nom/t/04-nativecall/13-cpp-mangling.t</a> (and it associated cpp file) But it's not as tested and developped than the C support for now.</p>
<a name="t20.13"$class><h1>20.13 Examples</h1></a>
<p>The <a href="https://github.com/jnthn/zavolaj">zavolaj</a> git repository (where NativeCall was originaly developed) hosts <a href="https://github.com/jnthn/zavolaj/tree/master/examples">various examples</a> of how to use NativeCall.</p>
<p>More examples can be found <a href="https://github.com/perl6/DBIish/tree/master/lib/DBDish">in the DBIsh repository</a> .</p>
<a name="t20.13.1"$class><h2>20.13.1 MySQL</h2></a>
TODO Do we really need this here? Seems like this info should just go
along-side that example in the git repo, rathern than replicated
on p6doc.
<p>There is an example of using the MySQL client library. There is a project <a href="">http://github.com/mberends/minidbi</a> 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:</p>
<pre class="code">sudo apt-get install libmysqlclient</pre>
<p>Prepare your system along these lines before trying out the examples:</p>
<pre class="code">$ 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';</pre>
<p>You can look at the results via a normal mysql connection:</p>
<pre class="code">$ mysql -utestuser -ptestpass
USE zavolaj;
SHOW TABLES;
SELECT * FROM nom;</pre>
<a name="t20.13.2"$class><h2>20.13.2 Microsoft Windows</h2></a>
<p>The win32-api-call.p6 script shows an example Windows API call done from Perl 6. See <a href="">http://github.com/jnthn/zavolaj/tree/master/examples</a> </p>
<a name="t21"><h1 class="title">21 Object Orientation</h1></a> <p class="subtitle">Object Orientation in Perl 6</p></a> <p>Perl 6 is an object oriented language at its core, even though it allows you to write programs in other programming styles.</p>
<p>Perl 6 comes with a wealth of predefined types, which can be classified in two categories: normal and <i>native</i> types.</p>
<p>Native types are used for low-level types (like <span class="code">uint64 </span> ). They do not have the same capabilities as objects, though if you call methods on them, they are <i>boxed</i> into normal objects.</p>
<p>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.</p>
<a name="t21.1"$class><h1>21.1 Using Objects</h1></a>
<p>You can use objects by calling methods on them. To call a method on an expression, add a dot, followed by the method name:</p>
<pre class="code"> <a href="">say</a> "abc" <b>. <a href="">uc</a> </b> ;
# ABC
</pre>
<p>This calls the <a href="uc"> <span class="code">uc </span> </a> method on <span class="code">"abc" </span> , which is an object of type <a href="Str"> <span class="code">Str </span> </a> . If you need to supply arguments to the method, add parentheses after the method name with the arguments inside the parentheses:</p>
<pre class="code">my $formatted-text = "Fourscore and seven years ago...". <a href="">indent</a> <b>(8)</b> ;
</pre>
<p> <span class="code">$formatted-text </span> now contains the above text, but indented 8 spaces.</p>
<p>Multiple arguments simply require a comma between them:</p>
<pre class="code">my @words = "Abe", "Lincoln";
@words. <a href="">push</a> ("said" <b>,</b> $formatted-text. <a href="">comb</a> ( <a href="/language/regexes">/\w+/</a> ));
</pre>
<p>Another method call syntax separates the method name and the argument list with a colon:</p>
<pre class="code">say @words. <a href="">join</a> : '--';
# Abe--Lincoln--said--Fourscore--and--seven--years--ago
</pre>
<p>Since you have to put a <span class="code">: </span> 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:</p>
<pre class="code">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 )</pre>
<p>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.</p>
<p>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:</p>
<pre class="code">$*IN. <a href="">nl-in</a> = "\r\n";
</pre>
<p>Here, we are calling method <span class="code">nl-in </span> on the <span class="code">$*IN </span> object, without arguments, and assign to the container it returned with the <a href="="> <span class="code">= </span> </a> operator.</p>
<p>All objects support methods from class <a href="">Mu</a> , which is the root of the type hierarchy. In other words, all objects are derived from <span class="code">Mu </span> .</p>
<a name="t21.1.1"$class><h2>21.1.1 Type Objects</h2></a>
<p>Types themselves are objects and you can get the <i>type object</i> simply by writing its name:</p>
<pre class="code">my $int-type-obj = Int;</pre>
<p>You can ask any object for its type object by calling the <span class="code">WHAT </span> method (which is actually a macro in method form):</p>
<pre class="code">my $int-type-obj = 1.WHAT;</pre>
<p>Type objects (other than <a href="">Mu</a> ) can be compared for equality with the <a href="==="> <span class="code">=== </span> </a> identity operator:</p>
<pre class="code">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';
}
}
</pre>
<p>Although, in most cases, the <a href="isa"> <span class="code">.isa </span> </a> method will suffice:</p>
<pre class="code">sub f($x) {
if $x <b>. <a href="">isa</a> </b> (Int) {
...
}
...
}
</pre>
<p>Subtype checking is done by smart-matching:</p>
<pre class="code">if $type <b> <a href="">~~</a> </b> <a href="">Real</a> {
say '$type contains Real or a subtype thereof';
}
</pre>
<a name="t21.2"$class><h1>21.2 Classes </h1></a>
<p>Classes are declared using the <span class="code">class </span> keyword, typically followed by a name.</p>
<pre class="code">class Journey {
}</pre>
<p>This declaration results in a type object being created and installed in the current package and current lexical scope under the name <span class="code">Journey </span> . You can also declare classes lexically:</p>
<pre class="code">my class Journey {
}</pre>
<p>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.</p>
<a name="t21.2.1"$class><h2>21.2.1 Attributes</h2></a>
<p>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 <span class="code">has </span> declarator and the <span class="code">! </span> twigil.</p>
<pre class="code">class Journey {
has $!origin;
has $!destination;
has @!travellers;
has $!notes;
}</pre>
<p>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 <span class="code">! </span> twigil with the <span class="code">. </span> twigil (the <span class="code">. </span> should remind you of a method call).</p>
<pre class="code">class Journey {
has $.origin;
has $.destination;
has @!travellers;
has $.notes;
}</pre>
<p>This defaults to providing a read-only accessor. In order to allow changes to the attribute, add the <a href="">is rw</a> trait:</p>
<pre class="code">class Journey {
has $.origin;
has $.destination;
has @!travellers;
has $.notes is rw;
}</pre>
<p>Now, after a <span class="code">Journey </span> object is created, its <span class="code">.origin </span> , <span class="code">.destination </span> , and <span class="code">.notes </span> will all be accessible from outside the class, but only <span class="code">.notes </span> can be modified.</p>
<p>The above allows creation of <span class="code">Journey </span> 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 <a href="">is required</a> .</p>
<pre class="code">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;
}</pre>
<p>Since classes inherit a default constructor from <span class="code">Mu </span> and we have requested that some accessor methods are generated for us, our class is already somewhat functional.</p>
<pre class="code"># Create a new instance of the class.
my $vacation = Journey.new(
origin <a href="">=></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!';
</pre>
<p>Note that the default constructor will only set attributes that have an accessor method, but it can initialize read-only attributes.</p>
<a name="t21.2.2"$class><h2>21.2.2 Methods</h2></a>
<p>Methods are declared with the <span class="code">method </span> keyword inside a class body.</p>
<pre class="code">class Journey {
has $.origin;
has $.destination;
has @!travellers;
has $.notes is rw;
<b>method</b> add_traveller($name) {
if $name <a href="">ne</a> <a href="">any</a> (@!travellers) {
<a href="">push</a> @!travellers, $name;
}
else {
<a href="">warn</a> "$name is already going on the journey!";
}
}
<b>method</b> describe() {
"From $!origin to $!destination"
}
}
</pre>
<p>A method can have a signature, just like a subroutine. Attributes can be used in methods and can always be used with the <span class="code">! </span> twigil, even if they are declared with the <span class="code">. </span> twigil. This is because really, the <span class="code">. </span> twigil declares a <span class="code">! </span> twigil and then additionally generates an accessor method.</p>
<p>Looking at the code above, there is a subtle but important difference between using <span class="code">$!origin </span> and <span class="code">$.origin </span> in the method <span class="code">describe </span> . 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 <span class="code">$.origin </span> if you explicitly want to allow overriding.</p>
<a name="t21.2.3"$class><h2>21.2.3 self</h2></a>
<p>Inside a method, the term <span class="code">self </span> is available, which is bound to the invocant, i.e. the object that the method was called on. <span class="code">self </span> can be used to call further methods on the invocant. Within methods, something like <span class="code">$.origin </span> is the same thing as <span class="code">self.origin </span> .</p>
<a name="t21.2.4"$class><h2>21.2.4 Private Methods</h2></a>
<p>Methods strictly for use inside the class and that are not to be called from anywhere else are declared with an exclamation mark <span class="code">! </span> before the method name. They are called with an exclamation mark instead of a dot:</p>
<pre class="code">method !do-something-private($x) {
...
}
method public($x) {
if self.precondition {
self!do-something-private(2 * $x)
}
}</pre>
<p>Private methods are not inherited to subclasses.</p>
<a name="t21.2.5"$class><h2>21.2.5 Submethods</h2></a>
<p>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.</p>
<p>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.</p>
<p>For example the <a href="/type/Mu#method new">default method new</a> calls submethod <span class="code">BUILD </span> on each class in an <a href="#Inheritance">inheritance</a> chain:</p>
<pre class="code">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);
</pre>
<p>This produces the following output:</p>
<pre class="code">Initializing Point2D
Initializing InvertiblePoint2D
InvertiblePoint2D.new(x => 1, y => 2)
</pre>
<p>See also: <a href="">#Object Construction</a> .</p>
<a name="t21.2.6"$class><h2>21.2.6 Inheritance</h2></a>
<p>Classes can have <i>parent classes</i> .</p>
<pre class="code">class Child <b> <a href="">is</a> Parent1 is Parent2</b> { }
</pre>
<p>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 <i>method resolution order</i> (MRO). Perl 6 uses the <a href="https://en.wikipedia.org/wiki/C3_linearization">C3 method resolution order</a> . You can ask a type for its MRO through a call to its meta class:</p>
<pre class="code">say List&lt;.^ <a href="">mro</a> >; # List() Cool() Any() Mu()
</pre>
<p>If a class does not specify a parent class, <a href="">Any</a> is assumed by default. All classes directly or indirectly derive from <a href="">Mu</a> , the root of the type hierarchy.</p>
<p>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:</p>
<pre class="code">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
</pre>
<p>This produces the output:</p>
<pre class="code">the child's somewhat more fancy frob is called</pre>
<a name="t21.2.7"$class><h2>21.2.7 Object Construction</h2></a>
<p>Objects are generally created through method calls, either on the type object or on another object of the same type.</p>
<p>Class <a href="">Mu</a> provides a constructor method called <a href="">new</a> , which takes named arguments and uses them to initialize public attributes.</p>
<pre class="code">class Point {
has $.x;
has $.y = 2 * $!x;
}
my $p = Point <b>. <a href="">new</a> </b> ( x <a href="">=></a> 1, y => 2);
# ^^^ inherited from class Mu
say "x: ", $p.x;
say "y: ", $p.y;
</pre>
<p>This outputs:</p>
<pre class="code">x: 1
y: 2</pre>
<pre class="code">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;
</pre>
<p>This outputs:</p>
<pre class="code">x: 5
y: 10</pre>
<p> <span class="code">Mu.new </span> calls method <a href="">bless</a> on its invocant, passing all the named arguments. <span class="code">bless </span> creates the new object and then calls method <span class="code">BUILDALL </span> on it. <span class="code">BUILDALL </span> walks all subclasses in reverse method resolution order (i.e. from <a href="">Mu</a> to most derived classes) and in each class checks for existence of a method named <span class="code">BUILD </span> . If it exists, it is called, again passing all named arguments from method <span class="code">new </span> to it. If not, the public attributes from this class are initialized from named arguments of the same name. In either case, if neither <span class="code">BUILD </span> nor the default mechanism has initialized the attribute, default values are applied (the <span class="code">2 * $!x </span> in the example above).</p>
<p>Due to the nature of the default behavior of <span class="code">BUILDALL </span> and custom <span class="code">BUILD </span> submethods, named arguments to the constructor <span class="code">new </span> derived from <span class="code">Mu </span> can correspond directly to public attributes of any of the classes in the method resolution order, or to any named parameter to any <span class="code">BUILD </span> submethod.</p>
<p>This object construction scheme has several implications for customized constructors. First, custom <span class="code">BUILD </span> methods should always be submethods, otherwise they break attribute initialization in subclasses. Second, <span class="code">BUILD </span> submethods can be used to run custom code at object construction time. They can also be used for creating aliases for attribute initialization:</p>
<pre class="code">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
</pre>
<p>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:</p>
<pre class="code"> submethod BUILD(:encoding(:$ <b>!</b> enc), :$ <b>!</b> data) {
# nothing to do here anymore, the signature binding
# does all the work for us.
}
</pre>
<p>The third implication is that if you want a constructor that accepts positional arguments, you must write your own <span class="code">new </span> method:</p>
<pre class="code"> class Point {
has $.x;
has $.y;
method new($x, $y) {
self. <a href="">bless</a> (:$x, :$y);
}
}
</pre>
<p>However this is considered poor practice, because it makes correct initialization of objects from subclasses harder.</p>
<p>Another thing to note is that the name <span class="code">new </span> is not special in Perl 6. It is merely a common convention. You can call <span class="code">bless </span> from any method at all, or use <span class="code">CREATE </span> to fiddle around with low-level workings.</p>
<p>Another pattern of hooking into object creation is by writing your own method <span class="code">BUILDALL </span> . To make sure that initialization of superclasses works fine, you need to <span class="code">callsame </span> to invoke the parent classes <span class="code">BUILDALL </span> .</p>
<pre class="code">class MyClass {
method BUILDALL(|) {
# initial things here
callsame; # call the parent classes (or default) BUILDALL
# you can do final checks here.
}
}
</pre>
TODO: better example for BUILDALL overriding
<a name="t21.2.8"$class><h2>21.2.8 Object Cloning</h2></a>
<p>The <span class="code">Mu </span> parent class, from which all classes inherit, supplies a method named <a href="">clone</a> 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.</p>
<p>As with <span class="code">new </span> , one may provide initial values for public attributes. These override values received from the original instance. (See the documentation for Mu's <a href="">clone</a> for an example.)</p>
<p>Note that since <span class="code">clone </span> is not a <span class="code">submethod </span> , a class which provides its own <span class="code">clone </span> method will replace the <span class="code">Mu </span> method. There is no automatic mechanism like <span class="code">BUILDALL </span> for cloning. For example, if one wished to make clone deeper for a particular class, one would will probably want to use <span class="code">callwith </span> or <span class="code">nextwith </span> to push the deeper copies to superclasses:</p>
<pre class="code">class A {
has $.a;
#...
method clone {
nextwith(:a($.a.clone))
}
}</pre>
<p>This works well for simple classes, but in some cases one might need to follow <span class="code">BUILDALL </span> 's lead and work in reverse method resolution order:</p>
<pre class="code">class B is A {
has $.b;
#...
method clone {
my $obj = callsame;
$obj.b = $!b.clone(:seed($obj.a.generate_seed));
$obj
}
}</pre>
<a name="t21.3"$class><h1>21.3 Roles </h1></a>
<p>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.</p>
<pre class="code">role Serializable {
method serialize() {
self. <a href="">perl</a> ; # very primitive serialization
}
method deserialize($buf) {
<a href="">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
</pre>
<p>Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.</p>
<a name="t21.3.1"$class><h2>21.3.1 <!-- --> Role Application</h2></a>
<p>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.</p>
<p>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 or might not be what the programmer wanted.</p>
<p>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 <span class="code">Bull </span> , for all the bulls you keep around the house, and a class <span class="code">Automobile </span> , for things that you can drive.</p>
<pre class="code">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</pre>
<p>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:</p>
<pre class="code">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 { }</pre>
<p>This code will die with something like:</p>
<pre class="code">===SORRY!===
Method 'steer' must be resolved by class Taurus because it exists in
multiple roles (Steerable, Bull-Like)</pre>
<p>This check will save you and your customers a lot of headaches and you can simply define your class instead as:</p>
<pre class="code">class Taurus does Bull-Like does Steerable {
method steer ($direction?) {
self.Steerable::steer($direction?)
}
}</pre>
<p>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</p>
<pre class="code">role R1 {
# methods here
}
role R2 does R1 {
# methods here
}
class C does R2 { }</pre>
<p>produces the same class <span class="code">C </span> as</p>
<pre class="code">role R1 {
# methods here
}
role R2 {
# methods here
}
class C does R1 does R2 { }</pre>
<a name="t21.3.2"$class><h2>21.3.2 Stubs</h2></a>
<p>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.</p>
<pre class="code">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)" }
}
</pre>
<p>The implementation of the stubbed method may also be provided by another role.</p>
<a name="t21.3.3"$class><h2>21.3.3 Automatic Role Punning</h2></a>
<p>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.</p>
<pre class="code">role Point {
has $.x;
has $.y;
method abs { sqrt($.x * $.x + $.y * $.y) }
}
say Point.new(x => 6, y => 8).abs;
</pre>
<p>We call this automatic creating of classes <i>punning</i> , and the generated class a <i>pun</i> .</p>
<a name="t21.3.4"$class><h2>21.3.4 Parameterized Roles</h2></a>
<p>Roles can be parameterized, by giving them a signature in square brackets:</p>
<pre class="code">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
</pre>
<p>Here the signature consists only of a type capture, but any signature will do:</p>
<pre class="code">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
</pre>
<p>You can have multiple roles of the same name, but with different signatures; the normal rules of multi dispatch apply for choosing multi candidates.</p>
<a name="t21.3.5"$class><h2>21.3.5 Mixins of Roles</h2></a>
<p>Roles can be mixed into objects. A roles given attributes and methods will be added to the methods and attributes the object already got. Multiple mixins and anonymous roles are supported.</p>
<pre class="code">role R { method Str() {'hidden!'} };
my $i = 2 but R;
sub f(\bound){ put bound };</pre>
<pre class="code">f($i); # hidden!</pre>
<p>Note that the object got the role mixed in, not the objects class or the container. Thus @-sigiled containers will require binding to make the role stick. Some operators will return a new value, resulting in the mixin to be stripped as well.</p>
<p>Mixins can happen at any time of your objects life.</p>
<pre class="code"># 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)</pre>
<p>Roles can by anonymous.</p>
<pre class="code">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</pre>
<a name="t21.4"$class><h1>21.4 Meta-Object Programming and Introspection</h1></a>
<p>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 <i>meta objects</i> . Meta objects are, like ordinary objects, instances of classes, in this case we call them <i>meta classes</i> .</p>
<p>For each object or class you can get the meta object by calling <span class="code">.HOW </span> 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.</p>
<p>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:</p>
<pre class="code">say 1.HOW === 2.HOW; # True
say 1.HOW === Int.HOW; # True
say 1.HOW === Num.HOW; # False</pre>
<p>Perl 6 uses the word <i>HOW</i> , 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 <span class="code">Perl6::Metamodel::ClassHOW </span> . For each class there is one instance of <span class="code">Perl6::Metamodel::ClassHOW </span> .</p>
<p>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:</p>
<pre class="code">my $object = 1;
my $metaobject = 1.HOW;
say $metaobject.name($object); # Int
# or shorter:
say 1.HOW.name(1); # Int</pre>
<p>(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).</p>
<p>To get rid of using the same object twice, there is a shortcut:</p>
<pre class="code">say 1.^name; # Int
# same as
say 1.HOW.name(1); # Int</pre>
<p>See <a href="/type/Metamodel::ClassHOW">Metamodel::ClassHOW</a> for documentation of the meta class of <span class="code">class </span> and also the <a href="/language/mop">general documentation on the meta object protocol</a> .</p>
<a name="t22"><h1 class="title">22 Operators</h1></a> <p class="subtitle">Common Perl 6 infixes, prefixes, postfixes, and more!</p></a> <a name="t22.1"$class><h1>22.1 Operator Precedence</h1></a>
<p>In an expression like <span class="code">1 + 2 * 3 </span> , the <span class="code">2 * 3 </span> is evaluated first because the infix <span class="code">* </span> has tighter <b>precedence</b> than the <span class="code">+ </span> .</p>
<p>The following table summarizes the precedence levels in Perl 6, from tightest to loosest:</p>
<table>
<tr><th>A</th> <th>Level</th> <th>Examples</th></tr>
<tr><td>N</td> <td>Terms</td> <td>42 3.14 "eek" qq["foo"] $x :!verbose @$array</td></tr>
<tr><td>L</td> <td>Method postfix</td> <td>.meth .+ .? .* .() .[] .{} .&lt;> .«» .:: .= .^ .:</td></tr>
<tr><td>N</td> <td>Autoincrement</td> <td>++ --</td></tr>
<tr><td>R</td> <td>Exponentiation</td> <td>**</td></tr>
<tr><td>L</td> <td>Symbolic unary</td> <td>! + - ~ ? | || +^ ~^ ?^ ^</td></tr>
<tr><td>L</td> <td>Multiplicative</td> <td>* / % %% +&amp; +&lt; +> ~&amp; ~&lt; ~> ?&amp; div mod gcd lcm</td></tr>
<tr><td>L</td> <td>Additive</td> <td>+ - +| +^ ~| ~^ ?| ?^</td></tr>
<tr><td>L</td> <td>Replication</td> <td>x xx</td></tr>
<tr><td>X</td> <td>Concatenation</td> <td>~</td></tr>
<tr><td>X</td> <td>Junctive and</td> <td>&amp;</td></tr>
<tr><td>X</td> <td>Junctive or</td> <td>| ^</td></tr>
<tr><td>L</td> <td>Named unary</td> <td>temp let</td></tr>
<tr><td>N</td> <td>Structural infix</td> <td>but does &lt;=> leg cmp .. ..^ ^.. ^..^</td></tr>
<tr><td>C</td> <td>Chaining infix</td> <td>!= == &lt; &lt;= > >= eq ne lt le gt ge ~~ === eqv !eqv</td></tr>
<tr><td>X</td> <td>Tight and</td> <td>&amp;&amp;</td></tr>
<tr><td>X</td> <td>Tight or</td> <td>|| ^^ // min max</td></tr>
<tr><td>R</td> <td>Conditional</td> <td>?? !! ff fff</td></tr>
<tr><td>R</td> <td>Item assignment</td> <td>= => += -= **= xx= .=</td></tr>
<tr><td>L</td> <td>Loose unary</td> <td>so not</td></tr>
<tr><td>X</td> <td>Comma operator</td> <td>, :</td></tr>
<tr><td>X</td> <td>List infix</td> <td>Z minmax X X~ X* Xeqv ...</td></tr>
<tr><td>R</td> <td>List prefix</td> <td>print push say die map substr ... [+] [*] any Z=</td></tr>
<tr><td>X</td> <td>Loose and</td> <td>and andthen</td></tr>
<tr><td>X</td> <td>Loose or</td> <td>or xor orelse</td></tr>
<tr><td>X</td> <td>Sequencer</td> <td>&lt;==, ==>, &lt;&lt;==, ==>></td></tr>
<tr><td>N</td> <td>Terminator</td> <td>; {...}, unless, extra ), ], }</td></tr>
</table> <p>Using two <span class="code">! </span> 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:</p>
<table>
<tr><th>A</th> <th>Assoc</th> <th>Meaning of $a ! $b ! $c</th></tr>
<tr><td>L</td> <td>left</td> <td>($a ! $b) ! $c</td></tr>
<tr><td>R</td> <td>right</td> <td>$a ! ($b ! $c)</td></tr>
<tr><td>N</td> <td>non</td> <td>ILLEGAL</td></tr>
<tr><td>C</td> <td>chain</td> <td>($a ! $b) and ($b ! $c)</td></tr>
<tr><td>X</td> <td>list</td> <td>infix:&lt;!>($a; $b; $c)</td></tr>
</table> <p>For unary operators this is interpreted as:</p>
<table>
<tr><th>A</th> <th>Assoc</th> <th>Meaning of !$a!</th></tr>
<tr><td>L</td> <td>left</td> <td>(!$a)!</td></tr>
<tr><td>R</td> <td>right</td> <td>!($a!)</td></tr>
<tr><td>N</td> <td>non</td> <td>ILLEGAL</td></tr>
</table> <p>In the operator descriptions below, a default associativity of <i>left</i> is assumed.</p>
<a name="t22.2"$class><h1>22.2 Operator classification</h1></a>
<p>Operators can occur in several positions relative to a term:</p>
<table>
<tr><td>+term</td> <td>prefix</td></tr>
<tr><td>term1 + term2</td> <td>infix</td></tr>
<tr><td>term++</td> <td>postfix</td></tr>
<tr><td>(term)</td> <td>circumfix</td></tr>
<tr><td>term1[term2]</td> <td>postcircumfix</td></tr>
</table> <p>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:</p>
<pre class="code">infix:&lt;+>(1, 2) # same as 1 + 2
circumfix:«( )»('a', 'b', 'c') # same as ('a', 'b', 'c')</pre>
<p>As a special case the <i>listop</i> (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 ( <span class="code">[+]| 1, 2, 3 </span> ) and the <a href="">#prefix ...</a> etc. stub operators.</p>
<p>Defining custom operators is covered in <a href="">/language/functions#Defining_Operators</a> .</p>
<a name="t22.3"$class><h1>22.3 Meta Operators</h1></a>
<p>Meta operators can be parameterized with other operators in the same way as functions can take functions as parameters. Perl 6 will generate the actual combinded 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.</p>
<a name="t22.3.1"$class><h2>22.3.1 Assignment Operators</h2></a>
<p>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.</p>
<pre class="code">my $a = 32;
$a += 10; # 42
my $a = 3;
$a min= 5; # still 3
$a min= 2; # 2</pre>
<p> <!-- blocked by #63642 my @a = 1,2; @a ,= 3,4; --> </p>
<p>This behavior is automatically extended to include custom-defined infix operators.</p>
<pre class="code">sub infix:&lt;space-concat> ($a,$b) { $a ~ " " ~ $b };
my $a = 'word1';
$a space-concat= 'word2'; # 'word1 word2'</pre>
<p>Although not strictly operators, methods can be used in the same fashion.</p>
<pre class="code">my Rat $a .= new;
my $a = 3.14;
$a .= Int; # 3</pre>
<a name="t22.3.2"$class><h2>22.3.2 Negated Relational Operators</h2></a>
<p>The result of a relational operator returning <span class="code">Bool </span> can be negated by prefixing with <span class="code">! </span> . To avoid visial confusion with the <span class="code">!! </span> operator, you may not modify any operator already beginning with <span class="code">! </span> .</p>
<p>There are shortcuts for <span class="code">!== </span> and <span class="code">!eq </span> , namely <span class="code">!= </span> and <span class="code">ne </span> .</p>
<pre class="code">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</pre>
<a name="t22.3.3"$class><h2>22.3.3 Reversed Operators</h2></a>
<p>Any infix operator may be called with its two arguments reversed by prefixing with <span class="code">R </span> . Associativity of operands is reversed as well.</p>
<pre class="code">say [R/] 2, 4, 16; # 2</pre>
<a name="t22.3.4"$class><h2>22.3.4 Hyper Operators</h2></a>
<p>Hyper operators apply a given operator enclosed by <span class="code">« </span> and <span class="code">» </span> to one or two lists, returning the resulting list. The pointy part of <span class="code">« </span> or <span class="code">» </span> 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.</p>
<pre class="code">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)</pre>
<p>Assignment meta operators can be hyped.</p>
<pre class="code">my @a = 1,2,3;
say @a »+=» 1; # [2 3 4]</pre>
<p>Hyper forms of unary opators have the pointy bit point to the operator and the blunt end at the list to be operated on.</p>
<pre class="code">my @wisdom = True, False, True;
say !« @wisdom; # [False True False]
my @a = 1,2,3;
@a»++; # (2,3,4)</pre>
<p>Hyper operators are defined recursivly on nested arrays.</p>
<pre class="code">say -« [[1, 2], 3]; # [[-1 -2] -3]</pre>
<p>Methods can be called too, in a out of order, cuncurrent 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, what is the reasion that they can not be defined by the user.</p>
<pre class="code">my CarefulClass @objs;
my @results = @objs».take-care();
my @slops; # May Contain Nuts
@slops».?this-method-may-not-exist();</pre>
<p>Hyper operatos 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.</p>
<table>
<tr><td>C&lt;%foo «+» %bar;></td> <td>intersection of keys</td></tr>
<tr><td>C&lt;%foo »+« %bar;></td> <td>union of keys</td></tr>
<tr><td>C&lt;%outer »+» %inner;></td> <td>only keys of %inner that exist in %outer will occur in the result</td></tr>
</table> <pre class="code">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"}</pre>
<a name="t22.3.5"$class><h2>22.3.5 Reduction Operators</h2></a>
<p>Reduction operators apply any infix operator, surrounded by <span class="code">[ </span> and <span class="code">] </span> , element by element and return the resulting value.</p>
<pre class="code">say [+] 1,2,3; # 6</pre>
<p>They can be defined as a list prefix operators or will be generated automatically. </p>
<pre class="code">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)</pre>
<p>For list infix operators, flattening is not done on the input list. This allowes list operators to become the reduction operator.</p>
<pre class="code">[X~] (1,2), &lt;a b> # 1,2 X~ &lt;a b></pre>
<p>By default reduction meta operators are eager. To lazily generate values, prefix the operater with a <span class="code">\ </span> . If the non-meta part contains a <span class="code">\ </span> already, quote it with <span class="code">[] </span> (e.g. <span class="code">[\[\x]] </span> ). </p>
<pre class="code">my $lazy := [\+] 1..*;
say $lazy[^10]; # (1 3 6 10 15 21 28 36 45 55)</pre>
<a name="t22.3.6"$class><h2>22.3.6 Cross Operators TODO</h2></a>
<a name="t22.3.7"$class><h2>22.3.7 Zip Operators</h2></a>
<p>The zip metaoperator, <span class="code">Z </span> , will apply a given infix operator to pairs taken one left, one right, from it's arguments. The resulting list is returned.</p>
<pre class="code">my @l = &lt;a b c> Z~ 1,2,3; # [a1 b2 c3]</pre>
<p>If one of the operands runs out of elements prematurely, the zip operator will stop. An infinite list can be used to repeat elements.</p>
<pre class="code">my @l = &lt;a b c d> Z~ ':' xx *; [a: b: c: d:] </pre>
<a name="t22.3.8"$class><h2>22.3.8 Sequential Operators</h2></a>
<p>The sequential metaoperator, <span class="code">S </span> , will suppress any concurrency, or reordering done by the optimizer. Most simple infix operators are supported.</p>
<pre class="code">say so 1 S&amp; 2 S&amp; 3; # True</pre>
<a name="t22.3.9"$class><h2>22.3.9 Nesting of Meta Operators</h2></a>
<p>To avoid ambiguity when chaining meta operators use square brackets to help the compiler to understand you.</p>
<pre class="code">my @a = 1,2,3;
my @b = 5,6,7;
@a X[+=] @b;
say @a; # [19 20 21]</pre>
<a name="t22.4"$class><h1>22.4 <!-- --> Term Precedence</h1></a>
<a name="t22.4.1"$class><h2>22.4.1 circumfix <span class="code">&lt; > </span> </h2></a>
<p>The quote-words construct. Breaks up the contents on whitespace, and returns a <a href="/type/List">List</a> of the words. If a word looks like a number literal or a <span class="code">Pair </span> literal, it is converted to the appropriate number.</p>
<pre class="code">say &lt;a b c>[1]; # b</pre>
<a name="t22.4.2"$class><h2>22.4.2 circumfix <span class="code">( ) </span> </h2></a>
<p>The grouping operator.</p>
<p>An empty group <span class="code">() </span> creates an empty <a href="">List</a> . Parens around non-empty expressions simply structure the expression, but not have additional semantics.</p>
<p>In an argument list, putting parenthesis around an argument prevents it from being interpreted as a named argument.</p>
<pre class="code">multi sub p(:$a!) { say 'named' }
multi sub p($a) { say 'positional' }
p a => 1; # named
p (a => 1); # positional</pre>
<a name="t22.4.3"$class><h2>22.4.3 circumfix <span class="code">{ } </span> </h2></a>
<p>Block or <a href="">Hash</a> constructor.</p>
<p>If the contents looks like a list of pairs and does not use <a href="">$_</a> or other placeholder parameters, returns an itemized <a href="">Hash</a> .</p>
<p>Otherwise it constructs a <a href="">Block</a> .</p>
<p>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 <a href="">Hash</a> .</p>
<a name="t22.4.4"$class><h2>22.4.4 circumfix <span class="code">[ ] </span> </h2></a>
<p>The <a href="">Array</a> constructor. Returns an itemized <a href="">Array</a> which does not flatten in list context.</p>
<a name="t22.5"$class><h1>22.5 Method Postfix Precedence</h1></a>
<a name="t22.5.1"$class><h2>22.5.1 postcircumfix <span class="code">[ ] </span> </h2></a>
<pre class="code">sub postcircumfix:&lt;[ ]>(@container, **@index,
:$k, :$v, :$kv, :$p, :$exists, :$delete)</pre>
<p>Universal interface for positional access to zero or more elements of a @container, a.k.a. "array indexing operator".</p>
<pre class="code">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")</pre>
<p>See <a href="/language/subscripts">Subscripts</a> for a more detailed explanation of this operator's behavior, and how to implement support for it in custom types.</p>
<a name="t22.5.2"$class><h2>22.5.2 postcircumfix <span class="code">{ } </span> </h2></a>
<pre class="code">sub postcircumfix:&lt;{ }>(%container, **@key,
:$k, :$v, :$kv, :$p, :$exists, :$delete)</pre>
<p>Universal interface for associative access to zero or more elements of a %container, a.k.a. "hash indexing operator".</p>
<pre class="code">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</pre>
<p>See <a href="/routine/[ ]#postcircumfix_<_>"> <span class="code">postcircumfix &lt; > </span> </a> and <a href="/routine/[ ]#postcircumfix_«_»"> <span class="code">postcircumfix « » </span> </a> for convenient shortcuts, and <a href="/language/subscripts">Subscripts</a> for a more detailed explanation of this operator's behavior, and how to implement support for it in custom types.</p>
<a name="t22.5.3"$class><h2>22.5.3 postcircumfix <span class="code">&lt; > </span> </h2></a>
<p>Shortcut for <a href="/routine/[ ]#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> that quotes its argument using the same rules as the <a href="/routine/< >#circumfix_<_>">quote-words operator</a> of the same name.</p>
<pre class="code">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</pre>
<p>This is not a real operator, just syntactic sugar that is turned into the <span class="code">{ } </span> postcircumfix operator at compile-time.</p>
<a name="t22.5.4"$class><h2>22.5.4 postcircumfix <span class="code">« » </span> </h2></a>
<p>Shortcut for <a href="/routine/[ ]#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> that quotes its argument using the same rules as the <a href="/routine/« »#circumfix_«_»">interpolating quote-words operator</a> of the same name.</p>
<pre class="code">my %color = kiwi => "green", banana => "yellow", cherry => "red";
my $fruit = "kiwi";
say %color«cherry $fruit».perl; #-> ("red", "green")</pre>
<p>This is not a real operator, just syntactic sugar that is turned into the <span class="code">{ } </span> postcircumfix operator at compile-time.</p>
<a name="t22.5.5"$class><h2>22.5.5 postcircumfix <span class="code">( ) </span> </h2></a>
<p>The call operator. Treats the invocant as a <a href="">Callable</a> and invokes it, using the expression between the parens as arguments.</p>
<p>Note that an identifier followed by a pair of parens is always parsed as a subroutine call.</p>
<p>If you want your objects to respond to the call operator, you need to implement a <span class="code">method CALL-ME </span> .</p>
<a name="t22.5.6"$class><h2>22.5.6 postfix <span class="code">. </span> </h2></a>
<p>The operator for calling one method, <span class="code">$invocant.method </span> .</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.7"$class><h2>22.5.7 postfix <span class="code">.= </span> </h2></a>
<p>A mutating method call. <span class="code">$invocant.=method </span> desugars to <span class="code">$invocant = $invocant.method </span> , similar to <a href=""> <span class="code">op= </span> </a> .</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.8"$class><h2>22.5.8 postfix <span class="code">.^ </span> </h2></a>
<p>A meta-method call. <span class="code">$invocant.^method </span> calls <span class="code">method </span> on <span class="code">$invocant </span> 's metaclass. It desugars to <span class="code">$invocant.HOW.method($invocant, ...) </span> . See <a href=""> <span class="code">HOW </span> </a> for more information.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.9"$class><h2>22.5.9 postfix <span class="code">.? </span> </h2></a>
<p>Potential method calls. <span class="code">$invocant.?method </span> calls method <span class="code">method </span> on <span class="code">$invocant </span> if it has a method of such name. Otherwise it returns <a href="">Nil</a> .</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.10"$class><h2>22.5.10 postfix <span class="code">.+ </span> </h2></a>
<p> <span class="code">$invocant.+method </span> calls all methods called <span class="code">method </span> from <span class="code">$invocant </span> , and returns a <a href="">List</a> of the results. Dies if no such method was found.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.11"$class><h2>22.5.11 postfix <span class="code">.* </span> </h2></a>
<p> <span class="code">$invocant.*method </span> calls all methods called <span class="code">method </span> from <span class="code">$invocant </span> , and returns a <a href="">List</a> of the results. If no such method was found, an empty <a href="">List</a> is returned.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.12"$class><h2>22.5.12 postfix <span class="code">». </span> / postfix <span class="code">>>. </span> </h2></a>
<p>Hyper method call operator will call a method on all elements of a <span class="code">List </span> out of order and return the list of return values in order.</p>
<pre class="code">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 obmitted for method calls.</pre>
<a name="t22.5.13"$class><h2>22.5.13 postfix <span class="code">.postfix </span> </h2></a>
<p>In most cases, a dot may be placed before a postfix or postcircumfix:</p>
<pre class="code">@a[1, 2, 3];
@a.[1, 2, 3]; # Same</pre>
<p>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.</p>
<pre class="code">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</pre>
<p>If the postfix is an identifier, however, it will be interpreted as a normal method call.</p>
<pre class="code">1.i # No such method 'i' for invocant of type 'Int'</pre>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.14"$class><h2>22.5.14 postfix <span class="code">.:&lt;prefix> </span> </h2></a>
<p>A prefix can be called like a method using colonpair notation. For example:</p>
<pre class="code">my $a = 1;
say ++$a; # 2
say $a.:&lt;++>; # 3</pre>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<a name="t22.5.15"$class><h2>22.5.15 postfix <span class="code">.:: </span> </h2></a>
<p>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.</p>
<pre class="code">class Bar {
method baz { 42 }
}
class Foo is Bar {
method baz { "nope" }
}
say Foo.Bar::baz; # 42</pre>
<a name="t22.6"$class><h1>22.6 Autoincrement Precedence</h1></a>
<a name="t22.6.1"$class><h2>22.6.1 prefix <span class="code">++ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;++>($x is rw) is assoc&lt;none></pre>
<p>Increments its argument by one, and returns the incremented value.</p>
<pre class="code">my $x = 3;
say ++$x; # 4
say $x; # 4</pre>
<p>It works by calling the <a href="">succ</a> method (for <i>successor</i> ) on its argument, which gives custom types the freedom to implement their own increment semantics.</p>
<a name="t22.6.2"$class><h2>22.6.2 prefix <span class="code">-- </span> </h2></a>
<pre class="code">multi sub prefix:&lt;-->($x is rw) is assoc&lt;none></pre>
<p>Decrements its argument by one, and returns the decremented value.</p>
<pre class="code">my $x = 3;
say --$x; # 2
say $x; # 2</pre>
<p>It works by calling the <a href="">pred</a> method (for <i>predecessor</i> ) on its argument, which gives custom types the freedom to implement their own decrement semantics.</p>
<a name="t22.6.3"$class><h2>22.6.3 postfix <span class="code">++ </span> </h2></a>
<pre class="code">multi sub postfix:&lt;++>($x is rw) is assoc&lt;none></pre>
<p>Increments its argument by one, and returns the unincremented value.</p>
<pre class="code">my $x = 3;
say $x++; # 3
say $x; # 4</pre>
<p>It works by calling the <a href="">succ</a> method (for <i>successor</i> ) on its argument, which gives custom types the freedom to implement their own incrementation semantics.</p>
<p>Note that this does not necessarily return its argument. For example for undefined values, it returns 0:</p>
<pre class="code">my $x;
say $x++; # 0
say $x; # 1</pre>
<a name="t22.6.4"$class><h2>22.6.4 postfix <span class="code">-- </span> </h2></a>
<pre class="code">multi sub postfix:&lt;-->($x is rw) is assoc&lt;none></pre>
<p>Decrements its argument by one, and returns the undecremented value.</p>
<pre class="code">my $x = 3;
say $x--; # 3
say $x; # 2</pre>
<p>It works by calling the <a href="">pred</a> method (for <i>predecessor</i> ) on its argument, which gives custom types the freedom to implement their own decrementation semantics.</p>
<p>Note that this does not necessarily return its argument. For example for undefined values, it returns 0:</p>
<pre class="code">my $x;
say $x--; # 0
say $x; # -1</pre>
<a name="t22.7"$class><h1>22.7 Exponentiation Precedence</h1></a>
<a name="t22.7.1"$class><h2>22.7.1 infix <span class="code">** </span> </h2></a>
<pre class="code">multi sub infix:&lt;**>(Any, Any) returns Numeric:D is assoc&lt;right></pre>
<p>The exponentiation operator coerces both arguments to <a href="">Numeric</a> and calculates the left-hand-side raised to the power of the right-hand side.</p>
<p>If the right-hand side is a non-negative integer and the left-hand side is an arbitrary precision type ( <a href="">Int</a> , <a href="">FatRat</a> ), then the calculation is carried out without loss of precision.</p>
<a name="t22.8"$class><h1>22.8 Symbolic Unary Precedence</h1></a>
<a name="t22.8.1"$class><h2>22.8.1 prefix <span class="code">? </span> </h2></a>
<pre class="code">multi sub prefix:&lt;?>(Mu) returns Bool:D</pre>
<p>Boolean context operator.</p>
<p>Coerces the argument to <a href="">Bool</a> by calling the <span class="code">Bool </span> method on it. Note that this collapses <a href="">Junction</a> s.</p>
<a name="t22.8.2"$class><h2>22.8.2 prefix <span class="code">! </span> </h2></a>
<pre class="code">multi sub prefix:&lt;!>(Mu) returns Bool:D</pre>
<p>Negated boolean context operator.</p>
<p>Coerces the argument to <a href="">Bool</a> by calling the <span class="code">Bool </span> method on it, and returns the negation of the result. Note that this collapses <a href="">Junction</a> s.</p>
<a name="t22.8.3"$class><h2>22.8.3 prefix <span class="code">+ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;+>(Any) returns Numeric:D</pre>
<p>Numeric context operator.</p>
<p>Coerces the argument to <a href="">Numeric</a> by calling the <span class="code">Numeric </span> method on it.</p>
<a name="t22.8.4"$class><h2>22.8.4 prefix <span class="code">- </span> </h2></a>
<pre class="code">multi sub prefix:&lt;->(Any) returns Numeric:D</pre>
<p>Negative numeric context operator.</p>
<p>Coerces the argument to <a href="">Numeric</a> by calling the <span class="code">Numeric </span> method on it, and then negates the result.</p>
<a name="t22.8.5"$class><h2>22.8.5 prefix <span class="code">~ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;->(Any) returns Str:D</pre>
<p>String context operator.</p>
<p>Coerces the argument to <a href="">Str</a> by calling the <span class="code">Str </span> method on it.</p>
<a name="t22.8.6"$class><h2>22.8.6 prefix <span class="code">| </span> </h2></a>
<p>Flattens objects of type <a href="">Capture</a> , <a href="">Enum</a> , <a href="">Pair</a> , <a href="">List</a> <a href="">Map</a> and <a href="">Hash</a> into an argument list.</p>
<p>Outside of argument lists, it returns a <a href="/type/Slip">Slip</a> , which makes it flatten into the outer list.</p>
<a name="t22.8.7"$class><h2>22.8.7 prefix <span class="code">+^ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;+^>(Any) returns Int:D</pre>
<p>Integer bitwise negation.</p>
<p>Coerces the argument to <a href="">Int</a> and does a bitwise negation on the result, assuming <a href="https://en.wikipedia.org/wiki/Two%27s_complement">two's complement</a> .</p>
<a name="t22.8.8"$class><h2>22.8.8 prefix <span class="code">?^ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;?^>(Mu) returns Bool:D</pre>
<p>Boolean bitwise negation.</p>
<p>Coerces the argument to <a href="">Bool</a> and then does a bit flip, which makes it the same as <span class="code">prefix:&lt;!> </span> .</p>
<a name="t22.8.9"$class><h2>22.8.9 prefix <span class="code">^ </span> </h2></a>
<pre class="code">multi sub prefix:&lt;^>(Any) returns Range:D</pre>
<p> <i>upto</i> operator.</p>
<p>Coerces the argument to <a href="">Numeric</a> , and generates a range from 0 up to (but excluding) the argument.</p>
<pre class="code">say ^5; # 0..^5
for ^5 { } # 5 iterations</pre>
<a name="t22.9"$class><h1>22.9 Multiplicative Precedence</h1></a>
<a name="t22.9.1"$class><h2>22.9.1 infix <span class="code">* </span> </h2></a>
<pre class="code">multi sub infix:&lt;*>(Any, Any) returns Numeric:D</pre>
<p>Coerces both arguments to <a href="">Numeric</a> and multiplies them. The result is of the wider type. See <a href="">Numeric</a> for details.</p>
<a name="t22.9.2"$class><h2>22.9.2 infix <span class="code">/ </span> </h2></a>
<pre class="code">multi sub infix:&lt;/>(Any, Any) returns Numeric:D</pre>
<p>Coerces both argument to <a href="">Numeric</a> and divides the left through the right number. Division of <a href="">Int</a> values returns <a href="">Rat</a> , otherwise the "wider type" rule described in <a href="">Numeric</a> holds.</p>
<a name="t22.9.3"$class><h2>22.9.3 infix <span class="code">div </span> </h2></a>
<pre class="code">multi sub infix:&lt;div>(Int:D, Int:D) returns Int:D</pre>
<p>Integer division. Rounds down.</p>
<a name="t22.9.4"$class><h2>22.9.4 infix <span class="code">% </span> </h2></a>
<pre class="code">multi sub infix:&lt;%>($x, $y) return Numeric:D</pre>
<p>Modulo operator. Coerces to <a href="">Numeric</a> first.</p>
<p>Generally the following identity holds:</p>
<pre class="code">$x % $y == $x - floor($x / $y) * $y</pre>
<a name="t22.9.5"$class><h2>22.9.5 infix <span class="code">%% </span> </h2></a>
<pre class="code">multi sub infix:&lt;%%>($a, $b) returns Bool:D</pre>
<p>Divisibility operator. Returns <span class="code">True </span> if <span class="code">$a % $b == 0 </span> .</p>
<a name="t22.9.6"$class><h2>22.9.6 infix <span class="code">mod </span> </h2></a>
<pre class="code">multi sub infix:&lt;mod>(Int:D $a, Int:D $b) returns Int:D</pre>
<p>Integer modulo operator. Returns the remainder of an integer modulo operation.</p>
<a name="t22.9.7"$class><h2>22.9.7 infix <span class="code">+&amp; </span> </h2></a>
<pre class="code">multi sub infix:&lt;+&amp;>($a, $b) returns Int:D</pre>
<p>Numeric bitwise <i>AND</i> . Coerces both arguments to <a href="">Int</a> and does a bitwise <i>AND</i> operation assuming two's complement.</p>
<a name="t22.9.8"$class><h2>22.9.8 infix <span class="code">+&lt; </span> </h2></a>
<pre class="code">multi sub infix:&lt;&lt; +&lt; >>($a, $b) returns Int:D</pre>
<p>Integer bit shift to the left.</p>
<a name="t22.9.9"$class><h2>22.9.9 infix <span class="code">+> </span> </h2></a>
<pre class="code">multi sub infix:&lt;&lt; +> >>($a, $b) returns Int:D</pre>
<p>Integer bit shift to the right.</p>
<a name="t22.9.10"$class><h2>22.9.10 infix <span class="code">gcd </span> </h2></a>
<pre class="code">multi sub infix:&lt;gcd>($a, $b) returns Int:D</pre>
<p>Coerces both arguments to <a href="">Int</a> and returns the greatest common denominator.</p>
<a name="t22.9.11"$class><h2>22.9.11 infix <span class="code">lcm </span> </h2></a>
<pre class="code">multi sub infix:&lt;lcm>($a, $b) returns Int:D</pre>
<p>Coerces both arguments to <a href="">Int</a> and returns the least common multiple, that is the smallest integer that is evenly divisible by both arguments.</p>
<a name="t22.10"$class><h1>22.10 Additive Precedence</h1></a>
<a name="t22.10.1"$class><h2>22.10.1 infix <span class="code">+ </span> </h2></a>
<pre class="code">multi sub infix:&lt;+>($a, $b) returns Numeric:D</pre>
<p>Coerces both arguments to <a href="">Numeric</a> and adds them.</p>
<a name="t22.10.2"$class><h2>22.10.2 infix <span class="code">- </span> </h2></a>
<pre class="code">multi sub infix:&lt;->($a, $b) returns Numeric:D</pre>
<p>Coerces both arguments to <a href="">Numeric</a> and subtracts the second from the first.</p>
<a name="t22.10.3"$class><h2>22.10.3 infix <span class="code">+| </span> </h2></a>
<pre class="code">multi sub infix:&lt;+|>($a, $b) returns Int:D</pre>
<p>Coerces both arguments to <a href="">Int</a> and does a bitwise <i>OR</i> (inclusive OR) operation.</p>
<a name="t22.10.4"$class><h2>22.10.4 infix <span class="code">+^ </span> </h2></a>
<pre class="code">multi sub infix:&lt;+^>($a, $b) returns Int:D</pre>
<p>Coerces both arguments to <a href="">Int</a> and does a bitwise <i>XOR</i> (exclusive OR) operation.</p>
<a name="t22.10.5"$class><h2>22.10.5 infix <span class="code">?| </span> </h2></a>
<pre class="code">multi sub infix:&lt;?|>($a, $b) returns Bool:D</pre>
<p>Coerces both arguments to <a href="">Bool</a> and does a logical <i>OR</i> (inclusive OR) operation.</p>
<a name="t22.11"$class><h1>22.11 Replication Precedence</h1></a>
<a name="t22.11.1"$class><h2>22.11.1 infix <span class="code">x </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces <span class="code">$a </span> to <a href="">Str</a> and <span class="code">$b </span> to <a href="">Int</a> and repeats the string <span class="code">$b </span> times. Return the empty string if <span class="code">$b &lt;= 0 </span> .</p>
<pre class="code">say 'ab' x 3; # ababab
say 42 x 3; # 424242</pre>
<a name="t22.11.2"$class><h2>22.11.2 infix <span class="code">xx </span> </h2></a>
<pre class="code">multi sub infix:&lt;xx>($a, $b) returns List:D</pre>
<p>Returns a list of <span class="code">$a </span> repeated and evaluated <span class="code">$b </span> times ( <span class="code">$b </span> is coerced to <a href="">Int</a> ). If <span class="code">$b &lt;= 0 </span> , the empty list is returned.</p>
<p>The left-hand side is evaluated for each repetition, so</p>
<pre class="code">[1, 2] xx 5</pre>
<p>returns five distinct arrays (but with the same content each time), and</p>
<pre class="code">rand xx 3</pre>
<p>returns three pseudo random numbers that are determined independently.</p>
<p>The right-hand side can be <span class="code">* </span> , in which case a lazy, infinite list is returned.</p>
<a name="t22.12"$class><h1>22.12 Concatenation</h1></a>
<a name="t22.12.1"$class><h2>22.12.1 infix <span class="code">~ </span> </h2></a>
<pre class="code">proto sub infix:&lt;~>(Any, Any) returns Str:D
multi sub infix:&lt;~>(Any, Any)
multi sub infix:&lt;~>(Str:D, Str:D)</pre>
<p>Coerces both arguments to <a href="">Str</a> and concatenates them.</p>
<pre class="code">say 'ab' ~ 'c'; # abc</pre>
<a name="t22.13"$class><h1>22.13 Junctive AND (all) Precedence</h1></a>
<a name="t22.13.1"$class><h2>22.13.1 infix <span class="code">&amp; </span> </h2></a>
<pre class="code">multi sub infix:&lt;&amp;>($a, $b) returns Junction:D is assoc&lt;list></pre>
<p>Creates an <i>all</i> <a href="">Junction</a> from its arguments. See <a href="">Junction</a> for more details.</p>
<a name="t22.14"$class><h1>22.14 Junctive OR (any) Precedence</h1></a>
<a name="t22.14.1"$class><h2>22.14.1 infix <span class="code">| </span> </h2></a>
<pre class="code">multi sub infix:&lt;|>($a, $b) returns Junction:D is assoc&lt;list></pre>
<p>Creates an <i>any</i> <a href="">Junction</a> from its arguments. See <a href="">Junction</a> for more details.</p>
<a name="t22.14.2"$class><h2>22.14.2 infix <span class="code">^ </span> </h2></a>
<pre class="code">multi sub infix:&lt;^>($a, $b) returns Junction:D is assoc&lt;list></pre>
<p>Creates a <i>one</i> <a href="">Junction</a> from its arguments. See <a href="">Junction</a> for more details.</p>
<a name="t22.15"$class><h1>22.15 Named Unary Precedence</h1></a>
<a name="t22.15.1"$class><h2>22.15.1 prefix <span class="code">temp </span> </h2></a>
<pre class="code">sub prefix:&lt;temp>(Mu $a is rw)</pre>
<p>"temporizes" the variable passed as the argument, which means it is reset to its old value on scope exit. (This is similar to the <a href="http://perldoc.perl.org/functions/local.html">local</a> operator in Perl 5, except that <span class="code">temp </span> does not reset the value).</p>
<a name="t22.15.2"$class><h2>22.15.2 prefix <span class="code">let </span> </h2></a>
<pre class="code">sub prefix:&lt;let>(Mu $a is rw)</pre>
<p>Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.</p>
<pre class="code">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;</pre>
<p>In the above case, if the <span class="code">Bool.pick </span> returns true, the answer will stay as 84 because the block returns a defined value ( <span class="code">say </span> returns true). Otherwise the <span class="code">die </span> statement will cause the block to exit unsuccessfully, resetting the answer to 42.</p>
this is duplicated in variables.pod
<a name="t22.16"$class><h1>22.16 Nonchaining Binary Precedence</h1></a>
<a name="t22.16.1"$class><h2>22.16.1 infix <span class="code">does </span> </h2></a>
<pre class="code">sub infix:&lt;does>(Mu $obj, Mu $role) is assoc&lt;none></pre>
<p>Mixes <span class="code">$role </span> into <span class="code">$obj </span> at run time. Requires <span class="code">$obj </span> to be mutable.</p>
<p> <span class="code">$role </span> doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.</p>
<a name="t22.16.2"$class><h2>22.16.2 infix <span class="code">but </span> </h2></a>
<pre class="code">sub infix:&lt;but>(Mu $obj, Mu $role) is assoc&lt;none></pre>
<p>Creates a copy of <span class="code">$obj </span> with <span class="code">$role </span> mixed in. Since <span class="code">$obj </span> is not modified, <span class="code">but </span> can be used to created immutable values with mixins.</p>
<p> <span class="code">$role </span> doesn't need to a be a role, it can be something that knows how to act like a role, for example enum values.</p>
<a name="t22.16.3"$class><h2>22.16.3 infix <span class="code">cmp </span> </h2></a>
<pre class="code">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>(Enum:D, Enum:D)
multi sub infix:&lt;cmp>(Version:D, Version:D)</pre>
<p>Generic, "smart" three-way comparator.</p>
<p>Compares strings with string semantics, numbers with number semantics, <a href="">Pair</a> objects first by key and then by value etc.</p>
<p>if <span class="code">$a eqv $b </span> , then <span class="code">$a cmp $b </span> always returns <span class="code">Order::Same </span> .</p>
<pre class="code">say (a => 3) cmp (a => 4); # Less
say 4 cmp 4.0; # Same
say 'b' cmp 'a'; # More</pre>
<a name="t22.16.4"$class><h2>22.16.4 infix <span class="code">leg </span> </h2></a>
<pre class="code">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)</pre>
<p>String three-way comparator. Short for <i>less, equal or greater?</i> .</p>
<p>Coerces both arguments to <a href="">Str</a> , and then does a lexicographic comparison.</p>
<pre class="code">say 'a' leg 'b'; Less
say 'a' leg 'a'; Same
say 'b' leg 'a'; More</pre>
<a name="t22.16.5"$class><h2>22.16.5 infix <span class="code">&lt;=> </span> </h2></a>
<pre class="code">multi sub infix:«&lt;=>»($a, $b) returns Order:D is assoc&lt;none></pre>
<p>Numeric three-way comparator.</p>
<p>Coerces both arguments to <a href="">Real</a> , and then does a numeric comparison.</p>
<a name="t22.16.6"$class><h2>22.16.6 infix <span class="code">.. </span> </h2></a>
<pre class="code">multi sub infix:&lt;..>($a, $b) returns Range:D is assoc&lt;none></pre>
<p>Constructs a <a href="">Range</a> from the arguments.</p>
<a name="t22.16.7"$class><h2>22.16.7 infix <span class="code">..^ </span> </h2></a>
<pre class="code">multi sub infix:&lt;..^>($a, $b) returns Range:D is assoc&lt;none></pre>
<p>Constructs a <a href="">Range</a> from the arguments, excluding the end point.</p>
<a name="t22.16.8"$class><h2>22.16.8 infix <span class="code">^.. </span> </h2></a>
<pre class="code">multi sub infix:&lt;^..>($a, $b) returns Range:D is assoc&lt;none></pre>
<p>Constructs a <a href="">Range</a> from the arguments, excluding the start point.</p>
<a name="t22.16.9"$class><h2>22.16.9 infix <span class="code">^..^ </span> </h2></a>
<pre class="code">multi sub infix:&lt;^..^>($a, $b) returns Range:D is assoc&lt;none></pre>
<p>Constructs a <a href="">Range</a> from the arguments, excluding both start and end point.</p>
<a name="t22.17"$class><h1>22.17 Chaining Binary Precedence</h1></a>
<a name="t22.17.1"$class><h2>22.17.1 infix <span class="code">== </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Numeric</a> if necessary, and returns <span class="code">True </span> if they are equal.</p>
<a name="t22.17.2"$class><h2>22.17.2 infix <span class="code">!= </span> </h2></a>
<pre class="code">proto sub infix:&lt;!=>(Mu, Mu) returns Bool:D is assoc&lt;chain></pre>
<p>Coerces both arguments to <a href="">Numeric</a> (if necessary), and returns <span class="code">True </span> if they are distinct.</p>
<a name="t22.17.3"$class><h2>22.17.3 infix <span class="code">&lt; </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Real</a> (if necessary), and returns <span class="code">True </span> if the first argument is smaller than the second.</p>
<a name="t22.17.4"$class><h2>22.17.4 infix <span class="code">&lt;= </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Real</a> (if necessary), and returns <span class="code">True </span> if the first argument is smaller than or equal to the second.</p>
<a name="t22.17.5"$class><h2>22.17.5 infix <span class="code">> </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Real</a> (if necessary), and returns <span class="code">True </span> if the first argument is larger than the second.</p>
<a name="t22.17.6"$class><h2>22.17.6 infix <span class="code">>= </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Real</a> (if necessary), and returns <span class="code">True </span> if the first argument is larger than or equal to the second.</p>
<a name="t22.17.7"$class><h2>22.17.7 infix <span class="code">eq </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">True </span> if both are equal.</p>
<p>Mnemonic: <i>equal</i> </p>
<a name="t22.17.8"$class><h2>22.17.8 infix <span class="code">ne </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">False </span> if both are equal.</p>
<p>Mnemonic: <i>not equal</i> </p>
<a name="t22.17.9"$class><h2>22.17.9 infix <span class="code">gt </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">True </span> if the first is larger than the second, as determined by lexicographic comparison.</p>
<p>Mnemonic: <i>greater than</i> </p>
<a name="t22.17.10"$class><h2>22.17.10 infix <span class="code">ge </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">True </span> if the first is equal to or larger than the second, as determined by lexicographic comparison.</p>
<p>Mnemonic: <i>greater or equal</i> </p>
<a name="t22.17.11"$class><h2>22.17.11 infix <span class="code">lt </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">True </span> if the first is smaller than the second, as determined by lexicographic comparison.</p>
<p>Mnemonic: <i>less than</i> </p>
<a name="t22.17.12"$class><h2>22.17.12 infix <span class="code">le </span> </h2></a>
<pre class="code">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)</pre>
<p>Coerces both arguments to <a href="">Str</a> (if necessary), and returns <span class="code">True </span> if the first is equal to or smaller than the second, as determined by lexicographic comparison.</p>
<p>Mnemonic: <i>less or equal</i> </p>
<a name="t22.17.13"$class><h2>22.17.13 infix <span class="code">before </span> </h2></a>
<pre class="code">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>(Enum:D, Enum:D)
multi sub infix:&lt;before>(Version:D, Version:D)</pre>
<p>Generic ordering, uses the same semantics as <a href="#infix cmp">cmp</a> . Returns <span class="code">True </span> if the first argument is smaller than the second.</p>
<a name="t22.17.14"$class><h2>22.17.14 infix <span class="code">after </span> </h2></a>
<pre class="code">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>(Enum:D, Enum:D)
multi sub infix:&lt;after>(Version:D, Version:D)</pre>
<p>Generic ordering, uses the same semantics as <a href="#infix cmp">cmp</a> . Returns <span class="code">True </span> if the first argument is larger than the second.</p>
<a name="t22.17.15"$class><h2>22.17.15 infix <span class="code">eqv </span> </h2></a>
<pre class="code">proto sub infix:&lt;eqv>(Any, Any) returns Bool:D is assoc&lt;chain>
proto sub infix:&lt;eqv>(Any, Any)</pre>
<p>Equivalence operator. Returns <span class="code">True </span> if the two arguments are structurally the same, i.e. from the same type and (recursively) contain the same values.</p>
<pre class="code">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</pre>
<p>For arbitrary objects this is not possible with the default <span class="code">eqv </span> operator. E.g., <span class="code">eqv </span> will not consider two instances of the same object as being structurally equivalent:</p>
<pre class="code">class A {
has $.a;
}
say A.new(a => 5) eqv A.new(a => 5); #=> False</pre>
<p>To get <span class="code">eqv </span> semantics for objects of this class, one would need to implement an appropriate infix <span class="code">eqv </span> operator:</p>
<pre class="code">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</pre>
<a name="t22.17.16"$class><h2>22.17.16 infix <span class="code">=== </span> </h2></a>
<pre class="code">proto sub infix:&lt;===>(Any, Any) returns Bool:D is assoc&lt;chain>
proto sub infix:&lt;===>(Any, Any)</pre>
<p>Value identity. Returns <span class="code">True </span> if both arguments are the same object.</p>
<pre class="code">class A { };
my $a = A.new;
say $a === $a; # True
say A.new === A.new; # False
say A === A; # True</pre>
<p>For value types, <span class="code">=== </span> behaves like <span class="code">eqv </span> :</p>
<pre class="code">say 'a' === 'a'; # True
say 'a' === 'b'; # False
# different types
say 1 === 1.0; # False</pre>
<p> <span class="code">=== </span> uses the <a href="">WHICH</a> method to obtain the object identity, so all value types must override method <span class="code">WHICH </span> .</p>
<a name="t22.17.17"$class><h2>22.17.17 infix <span class="code">=:= </span> </h2></a>
<pre class="code">proto sub infix:&lt;=:=>(Mu \a, Mu \b) returns Bool:D is assoc&lt;chain>
multi sub infix:&lt;=:=>(Mu \a, Mu \b)</pre>
<p>Container identity. Returns <a href="">True</a> if both arguments are bound to the same container. If it returns <span class="code">True </span> , it generally means that modifying one will also modify the other.</p>
<pre class="code">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</pre>
<a name="t22.17.18"$class><h2>22.17.18 infix <span class="code">~~ </span> </h2></a>
<p>The smart-match operator. Aliases the left-hand side to <span class="code">$_ </span> , then evaluates the right-hand side, and calls <span class="code">.ACCEPTS($_) </span> on it. The semantics are left to the type of the right-hand side operand.</p>
<p>Here is an excerpt of built-in smart-matching functionality:</p>
<table>
<tr><th>Right-hand side</th> <th>Comparison semantics</th></tr>
<tr><td>Mu:U</td> <td>type check</td></tr>
<tr><td>Str</td> <td>string equality</td></tr>
<tr><td>Numeric</td> <td>numeric equality</td></tr>
<tr><td>Regex</td> <td>regex match</td></tr>
<tr><td>Callable</td> <td>boolean result of invocation</td></tr>
<tr><td>Any:D</td> <td>object identity</td></tr>
</table> <a name="t22.18"$class><h1>22.18 Tight AND Precedence</h1></a>
<a name="t22.18.1"$class><h2>22.18.1 infix <span class="code">&amp;&amp; </span> </h2></a>
<p>Returns the first argument that evaluates to <span class="code">False </span> in boolean context, or otherwise the last argument.</p>
<p>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.</p>
<pre class="code">sub a { 1 }
sub b { 0 }
sub c { die "never called" };
say a() &amp;&amp; b() &amp;&amp; c(); # 0</pre>
<a name="t22.19"$class><h1>22.19 Tight OR Precedence</h1></a>
<a name="t22.19.1"$class><h2>22.19.1 infix <span class="code">|| </span> </h2></a>
<p>Returns the first argument that evaluates to <span class="code">True </span> in boolean context, or otherwise the last argument.</p>
<p>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.</p>
<pre class="code">sub a { 0 }
sub b { 1 }
sub c { die "never called" };
say a() || b() || c(); # 1</pre>
<a name="t22.19.2"$class><h2>22.19.2 infix <span class="code">^^ </span> </h2></a>
<p>Returns the first true argument if there is only one, and <a href="">Nil</a> otherwise. Short-circuits as soon as two true arguments are found.</p>
<pre class="code">say 0 ^^ 42; # 42
say 0 ^^ 42 ^^ 1 ^^ die 8; # (empty line)</pre>
<p>Note that the semantics of this operator may not be what you assume: infix <span class="code">^^ </span> flips to first true value it finds, and then flips to Nil <i>forever</i> 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.)</p>
<a name="t22.19.3"$class><h2>22.19.3 infix <span class="code">// </span> </h2></a>
<p>Defined-or operator. Returns the first defined operand, or else the last operand. Short-circuits.</p>
<pre class="code">say Any // 0 // 42; # 0</pre>
<a name="t22.19.4"$class><h2>22.19.4 infix <span class="code">min </span> </h2></a>
<p>Returns the smallest of the arguments, as determined by <a href="">cmp</a> semantics.</p>
<pre class="code">$foo min= 0 # read as: $foo decreases to 0</pre>
<a name="t22.19.5"$class><h2>22.19.5 infix <span class="code">max </span> </h2></a>
<p>Returns the largest of the arguments, as determined by <a href="">cmp</a> semantics.</p>
<pre class="code">$foo max= 0 # read as: $foo increases to 0</pre>
<a name="t22.20"$class><h1>22.20 Conditional Operator Precedence</h1></a>
<a name="t22.20.1"$class><h2>22.20.1 infix <span class="code">?? !! </span> </h2></a>
<p>Ternary operator, conditional operator.</p>
<p> <span class="code">$condition ?? $true !! $false </span> evaluates and returns the expression from the <span class="code">$true </span> branch if <span class="code">$condition </span> is a true value. Otherwise it evaluates and returns the <span class="code">$false </span> branch.</p>
<a name="t22.20.2"$class><h2>22.20.2 infix <span class="code">ff </span> </h2></a>
<pre class="code">sub infix:&lt;ff>(Mu $a, Mu $b)</pre>
<p>Flipflop operator.</p>
<p>Compares both arguments to <span class="code">$_ </span> (that is, <span class="code">$_ ~~ $a </span> and <span class="code">$_ ~~ $b </span> ). Evaluates to <span class="code">False </span> until the left-hand smartmatch is <span class="code">True </span> , at which point it evaluates to <span class="code">True </span> until the right-hand smartmatch is <span class="code">True </span> .</p>
<p>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:</p>
<pre class="code"> 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");
</pre>
<p>After matching the start condition, the operator will then match the same <span class="code">$_ </span> to the stop condition, and act accordingly if successful. In this example, only the first element is printed:</p>
<pre class="code">for &lt;AB C D B E F> {
say $_ if /A/ ff /B/; # prints only "AB"
}</pre>
<p>If you only want to test against a start condition, and have no stop condition, <span class="code">* </span> can be used as the "stop" condition.</p>
<pre class="code">for &lt;A B C D E> {
say $_ if /C/ ff *; # prints C, D, and E
}</pre>
<p>For the sed-like version, which does <i>not</i> try <span class="code">$_ </span> on the stop condition after succeeding on the start condition, see <a href=""> <span class="code">fff </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.3"$class><h2>22.20.3 infix <span class="code">^ff </span> </h2></a>
<pre class="code">sub infix:&lt;^ff>(Mu $a, Mu $b)</pre>
<p>Works like <a href=""> <span class="code">ff </span> </a> , except it does not return <span class="code">True </span> for items matching the start condition (including items also matching the stop condition).</p>
<p>A comparison:</p>
<pre class="code">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</pre>
<p>The sed-like version can be found in <a href=""> <span class="code">^fff </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.4"$class><h2>22.20.4 infix <span class="code">ff^ </span> </h2></a>
<pre class="code">sub infix:&lt;ff^>(Mu $a, Mu $b)</pre>
<p>Works like <a href=""> <span class="code">ff </span> </a> , except it does not return <span class="code">True </span> for items matching the stop condition (including items that first matched the start condition).</p>
<pre class="code">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</pre>
<p>The sed-like version can be found in <a href=""> <span class="code">fff^ </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.5"$class><h2>22.20.5 infix <span class="code">^ff^ </span> </h2></a>
<pre class="code">sub infix:&lt;^ff^>(Mu $a, Mu $b)</pre>
<p>Works like <a href=""> <span class="code">ff </span> </a> , except it does not return <span class="code">True </span> for items matching either the stop or start condition (or both).</p>
<pre class="code">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</pre>
<p>The sed-like version can be found in <a href=""> <span class="code">^fff^ </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.6"$class><h2>22.20.6 infix <span class="code">fff </span> </h2></a>
<pre class="code">sub infix:&lt;fff>(Mu $a, Mu $b)</pre>
<p>Performs a sed-like flipflop operation, wherein it returns <span class="code">False </span> until the left argument smartmatches against <span class="code">$_ </span> , and after that returns <span class="code">True </span> until the right argument smartmatches against <span class="code">$_ </span> .</p>
<p>Works similarly to <a href=""> <span class="code">ff </span> </a> , except that it only tries one argument per invocation. That is, if <span class="code">$_ </span> smartmatches the left argument, <span class="code">fff </span> will <b>not</b> then try to match that same <span class="code">$_ </span> against the right argument.</p>
<pre class="code">for &lt;AB C D B E F> {
say $_ if /A/ fff /B/; # Prints "AB", "C", "D", and "B"
}</pre>
<p>The non-sed-like flipflop (which after successfully matching the left argument against <span class="code">$_ </span> will try that same <span class="code">$_ </span> against the right argument and act accordingly), see <a href=""> <span class="code">ff </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.7"$class><h2>22.20.7 infix <span class="code">^fff </span> </h2></a>
<pre class="code">sub infix:&lt;^fff>(Mu $a, Mu $b)</pre>
<p>Like <a href=""> <span class="code">fff </span> </a> , except it does not return true for matches to the left argument.</p>
<pre class="code">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</pre>
<p>For the non-sed version, see <a href=""> <span class="code">^ff </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.8"$class><h2>22.20.8 infix <span class="code">fff^ </span> </h2></a>
<pre class="code">sub infix:&lt;fff^>(Mu $a, Mu $b)</pre>
<p>Like <a href=""> <span class="code">fff </span> </a> , except it does not return true for matches to the right argument.</p>
<pre class="code">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</pre>
<p>For the non-sed version, see <a href=""> <span class="code">ff^ </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.20.9"$class><h2>22.20.9 infix <span class="code">^fff^ </span> </h2></a>
<pre class="code">sub infix:&lt;^fff^>(Mu $a, Mu $b)</pre>
<p>Like <a href=""> <span class="code">fff </span> </a> , except it does not return true for matches to either the left or right argument.</p>
<pre class="code">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</pre>
<p>For the non-sed version, see <a href=""> <span class="code">^ff^ </span> </a> .</p>
<p>This operator cannot be overloaded, as it is handled specially by the compiler.</p>
<a name="t22.21"$class><h1>22.21 Item Assignment Precedence</h1></a>
<a name="t22.21.1"$class><h2>22.21.1 infix <span class="code">= </span> </h2></a>
<pre class="code">sub infix:&lt;=>(Mu $a is rw, Mu $b)</pre>
<p>Item assignment.</p>
<p>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.</p>
<p>(Note that item assignment and list assignment have different precedence levels, and the syntax of the left-hand side decides whether an equal sign <span class="code">= </span> is parsed as item assignment or list assignment operator).</p>
<a name="t22.21.2"$class><h2>22.21.2 infix <span class="code">=> </span> </h2></a>
<pre class="code">sub infix:«=>»($key, Mu $value) returns Pair:D</pre>
<p> <a href="">Pair</a> constructor.</p>
<p>Constructs a <a href="">Pair</a> object with the left-hand side as the key and the right-hand side as the value.</p>
<p>Note that the <span class="code">=> </span> operator is syntactically special-cased, in that it allows unquoted identifier on the left-hand side.</p>
<pre class="code">my $p = a => 1;
say $p.key; # a
say $p.value; # 1</pre>
<p>A <a href="">Pair</a> within an argument list with an unquoted identifier on the left is interpreted as a named argument.</p>
<p>See <a href="/language/terms#Pair">the Terms language documentation</a> for more ways to create <span class="code">Pair </span> objects.</p>
<a name="t22.22"$class><h1>22.22 Loose Unary Precedence</h1></a>
<a name="t22.22.1"$class><h2>22.22.1 prefix <span class="code">not </span> </h2></a>
<pre class="code">multi sub prefix:&lt;not>(Mu $x) returns Bool:D</pre>
<p>Evaluates its argument in boolean context (and thus collapses <a href="">Junction</a> s), and negates the result.</p>
<a name="t22.22.2"$class><h2>22.22.2 prefix <span class="code">so </span> </h2></a>
<pre class="code">multi sub prefix:&lt;so>(Mu $x) returns Bool:D</pre>
<p>Evaluates its argument in boolean context (and thus collapses <a href="">Junction</a> s), and returns the result.</p>
<a name="t22.23"$class><h1>22.23 Comma Operator Precedence</h1></a>
<a name="t22.23.1"$class><h2>22.23.1 infix <span class="code">, </span> </h2></a>
<pre class="code">sub infix:&lt;,>(*@a) is assoc&lt;list> returns List:D</pre>
<p>Constructs a <a href="">List</a> from its arguments. Also used syntactically as the separator of arguments in calls.</p>
<a name="t22.23.2"$class><h2>22.23.2 infix <span class="code">: </span> </h2></a>
<p>Used as an argument separator just like infix <span class="code">, </span> and marks the argument to its left as the invocant. That turns what would otherwise be a function call into a method call.</p>
<pre class="code">substr('abc': 1); # same as 'abc'.substr(1)</pre>
<p>Infix <span class="code">: </span> is only allowed after the first argument of a non-method call. In other positions it is a syntax error.</p>
<a name="t22.24"$class><h1>22.24 List Infix Precedence</h1></a>
<a name="t22.24.1"$class><h2>22.24.1 infix <span class="code">Z </span> </h2></a>
<pre class="code">sub infix:&lt;Z>(**@lists) returns List:D is assoc&lt;chain></pre>
<p>Zip operator.</p>
<p>Interleaves the lists passed to <span class="code">Z </span> like a zipper, stopping as soon as the first input list is exhausted:</p>
<pre class="code">say (1, 2 Z &lt;a b c> Z &lt;+ ->).perl; #=> ((1, "a", "+"), (2, "b", "-")).Seq</pre>
<p>The <span class="code">Z </span> 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:</p>
<pre class="code">say 100, 200 Z+ 42, 23; #=> (142 223)
say 1..3 Z~ &lt;a b c> Z~ 'x' xx 3; #=> (1ax 2bx 3cx)</pre>
<a name="t22.24.2"$class><h2>22.24.2 infix <span class="code">X </span> </h2></a>
<pre class="code">sub infix:&lt;X>(**@lists) returns List:D is assoc&lt;chain></pre>
<p>Creates a cross product from all the lists, order so that the rightmost elements vary most rapidly</p>
<pre class="code">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))</pre>
<p>The <span class="code">X </span> 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:</p>
<pre class="code">1..3 X~ &lt;a b c> X~ 9
# produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)</pre>
<a name="t22.24.3"$class><h2>22.24.3 infix <span class="code">... </span> </h2></a>
<pre class="code">multi sub infix:&lt;...>(**@) is assoc&lt;list>
multi sub infix:&lt;...^>(**@) is assoc&lt;list></pre>
<p>The sequence operator is a generic operator to produce lazy lists.</p>
<p>It can have initial elements and a generator on left-hand side, and an endpoint on the right-hand side.</p>
<p>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.</p>
<p>The default generator is <span class="code">*. </span> <a href="">succ</a> or <span class="code">*. </span> <a href="">pred</a> , depending on how the end points compare:</p>
<pre class="code">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</pre>
<p>An endpoint of <span class="code">* </span> ( <a href="">Whatever</a> ) generates an infinite sequence, with a default generator of *.succ</p>
<pre class="code">say (1 ... *)[^5]; # 1 2 3 4 5</pre>
<p>Custom generators are the last argument before the '...' operator. This one takes two arguments, and generates the Fibonacci numbers</p>
<pre class="code">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</pre>
<p>Of course the generator can also take only one argument.</p>
<pre class="code">say 5, { $_ * 2 } ... 40; # 5 10 20 40</pre>
<p>There must be at least as many initial elements as arguments to the generator.</p>
<p>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.</p>
<pre class="code">say 2, 4, 6 ... 12; # 2 4 6 8 10 12
say 1, 2, 4 ... 32; # 1 2 4 8 16 32</pre>
<p>If the endpoint is not <span class="code">* </span> , it is smart-matched against each generated element, and the sequence is terminated when the smart-match succeeded. For the <span class="code">... </span> operator, the final element is included, for the <span class="code">...^ </span> operator it is excluded.</p>
<p>This allows you to write</p>
<pre class="code">say 1, 1, *+* ...^ *>= 100;</pre>
<p>To generate all Fibonacci numbers up to but excluding 100.</p>
<p>The <span class="code">... </span> operators consider the initial values as "generated elements" as well, so the are also checked against the endpoint:</p>
<pre class="code">my $end = 4;
say 1, 2, 4, 8, 16 ... $end;
# outputs 1 2 4</pre>
<a name="t22.25"$class><h1>22.25 List Prefix Precedence</h1></a>
<a name="t22.25.1"$class><h2>22.25.1 infix <span class="code">= </span> </h2></a>
<p>List assignment. Its exact semantics are left to the container type on the left-hand side. See <a href="">Array</a> and <a href="">Hash</a> for common cases.</p>
<p>The distinction between item assignment and list assignment is determined by the parser depending on the syntax of the left-hand side.</p>
<a name="t22.25.2"$class><h2>22.25.2 infix <span class="code">:= </span> </h2></a>
<p>Binding. Whereas <span class="code">$x = $y </span> puts the value in <span class="code">$y </span> into <span class="code">$x </span> , <span class="code">$x := $y </span> makes <span class="code">$x </span> and <span class="code">$y </span> the same thing.</p>
<pre class="code"> my $a = 42;
my $b <b>=</b> $a;
$b <a href="">++</a> ;
say $a;
</pre>
<p>This will output 42, because <span class="code">$a </span> and <span class="code">$b </span> both contained the number <span class="code">42 </span> , but the <a href="/language/containers.html#Binding">containers</a> were different.</p>
<pre class="code"> my $a = 42;
my $b <b>:=</b> $a;
$b <a href="">++</a> ;
say $a;
</pre>
<p>This will output 43, since <span class="code">$b </span> and <span class="code">$a </span> both represented the same object.</p>
<a name="t22.25.3"$class><h2>22.25.3 infix <span class="code">::= </span> </h2></a>
<p>Read-only binding. See <a href=":="> <span class="code">infix := </span> </a> .</p>
<a name="t22.25.4"$class><h2>22.25.4 listop <span class="code">... </span> </h2></a>
<p>The <i>yada, yada, yada</i> operator or <i>stub</i> 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).</p>
<p>If the <span class="code">... </span> statement is executed, it calls <a href="">&amp;fail</a> , with the default message <span class="code">stub code executed </span> .</p>
<a name="t22.25.5"$class><h2>22.25.5 listop <span class="code">!!! </span> </h2></a>
<p>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).</p>
<p>If the <span class="code">!!! </span> statement is executed, it calls <a href="">&amp;die</a> , with the default message <span class="code">stub code executed </span> .</p>
<a name="t22.25.6"$class><h2>22.25.6 listop <span class="code">??? </span> </h2></a>
<p>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).</p>
<p>If the <span class="code">??? </span> statement is executed, it calls <a href="">&amp;warn</a> , with the default message <span class="code">stub code executed </span> .</p>
<a name="t22.25.7"$class><h2>22.25.7 Reduction operators</h2></a>
<p>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.</p>
<pre class="code"> [+] 1, 2, 3; # 1 + 2 + 3 = 6
my @a = (5,6);
[*] @a; # 5 * 6 = 30
</pre>
<p>Reduction operators have the same associativity as the operators they are based on.</p>
<pre class="code"> [-] 4, 3, 2; # 4-3-2 = (4-3)-2 = -1
[**] 4, 3, 2; # 4**3**2 = 4**(3**2) = 262144
</pre>
<a name="t22.26"$class><h1>22.26 Loose AND precedence</h1></a>
<a name="t22.26.1"$class><h2>22.26.1 infix <span class="code">and </span> </h2></a>
<p>Same as <a href="">#infix &amp;&amp;</a> , except with looser precedence.</p>
<p>Returns the first operand that evaluates to <span class="code">False </span> in boolean context, or otherwise the last operand. Short-circuits.</p>
<a name="t22.26.2"$class><h2>22.26.2 infix <span class="code">andthen </span> </h2></a>
<p>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.</p>
<a name="t22.27"$class><h1>22.27 Loose OR Precedence</h1></a>
<a name="t22.27.1"$class><h2>22.27.1 infix <span class="code">or </span> </h2></a>
<p>Same as <span class="code">infix || </span> , except with looser precedence.</p>
<p>Returns the first argument that evaluates to <span class="code">True </span> in boolean context, or otherwise the last argument. Short-circuits.</p>
<a name="t22.27.2"$class><h2>22.27.2 infix <span class="code">orelse </span> </h2></a>
<p>Same as <span class="code">infix // </span> , except with looser precedence.</p>
<p>Returns the first defined argument, or else the last argument. Short-circuits.</p>
<a name="t23"><h1 class="title">23 Packages</h1></a> <p class="subtitle">Organizing and referencing namespaced program elements</p></a> * Take a lot of stuff from S02 for this
* Document 'import'
<p>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.</p>
<a name="t23.1"$class><h1>23.1 Names</h1></a>
<p>A <i>name</i> is anything that is a legal part of a variable name (not counting the sigil). This includes:</p>
<pre class="code">$foo # simple identifiers
$Foo::Bar::baz # compound identifiers separated by ::
$Foo::($bar)::baz # compound identifiers that perform interpolations
$42 # numeric names
$! # certain punctuational variables</pre>
<p> <span class="code">:: </span> is used to separate nested package names.</p>
<a name="t23.1.1"$class><h2>23.1.1 Package-qualified names</h2></a>
<p>Ordinary package-qualified names look like:</p>
<pre class="code">$Foo::Bar::baz # the $baz variable in package Foo::Bar</pre>
<p>Sometimes it's clearer to keep the sigil with the variable name, so an alternate way to write this is:</p>
<pre class="code">Foo::Bar::&lt;$baz></pre>
<p>This is resolved at compile time because the variable name is a constant.</p>
<p>If the name part before <span class="code">:: </span> is null, it means the package is unspecified and must be searched for. Generally this means that an initial <span class="code">:: </span> following the main sigil is a no-op on names that are known at compile time, though <span class="code">::() </span> can also be used to introduce an interpolation. Also, in the absence of another sigil, <span class="code">:: </span> can serve as its own sigil indicating intentional use of a not-yet-declared package name.</p>
<a name="t23.2"$class><h1>23.2 Pseudo-packages</h1></a>
<p>The following pseudo-package names are reserved at the front of a name:</p>
<pre class="code">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</pre>
<p>The following relative names are also reserved but may be used anywhere in a name:</p>
<pre class="code">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</pre>
<p>The file's scope is known as <span class="code">UNIT </span> , 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 <span class="code">SETTING </span> scope is equivalent to <span class="code">UNIT::OUTERS </span> . For a standard Perl program <span class="code">SETTING </span> is the same as <span class="code">CORE </span> , but various startup options (such as <span class="code">-n </span> or <span class="code">-p </span> ) can put you into a domain specific language, in which case <span class="code">CORE </span> remains the scope of the standard language, while <span class="code">SETTING </span> 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, <span class="code">SETTING </span> includes all its outer scopes up to <span class="code">CORE </span> . To get <i>only</i> the setting's outermost scope, use <span class="code">UNIT::OUTER </span> instead.</p>
<a name="t23.3"$class><h1>23.3 Looking up names</h1></a>
<a name="t23.3.1"$class><h2>23.3.1 Interpolating into names</h2></a>
<p>You may interpolate a string into a package or variable name using <span class="code">::($expr) </span> where you'd ordinarily put a package or variable name. The string is allowed to contain additional instances of <span class="code">:: </span> , which will be interpreted as package nesting. You may only interpolate entire names, since the construct starts with <span class="code">:: </span> , and either ends immediately or is continued with another <span class="code">:: </span> outside the parens. Most symbolic references are done with this notation:</p>
<pre class="code">$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)</pre>
<p>An initial <span class="code">:: </span> doesn't imply global. Here as part of the interpolation syntax it doesn't even imply package. After the interpolation of the <span class="code">::() </span> 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 <span class="code">CORE </span> ). The current package is searched last.</p>
<p>Use the <span class="code">MY </span> pseudopackage to limit the lookup to the current lexical scope, and <span class="code">OUR </span> to limit the scopes to the current package scope.</p>
<a name="t23.3.2"$class><h2>23.3.2 Direct lookup</h2></a>
<p>To do direct lookup in a package's symbol table without scanning, treat the package name as a hash:</p>
<pre class="code">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</pre>
<p>Unlike <span class="code">::() </span> symbolic references, this does not parse the argument for <span class="code">:: </span> , 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.</p>
<p>The null pseudo-package is the same search list as an ordinary name search. That is, the following are all identical in meaning:</p>
<pre class="code">$foo
$::{'foo'}
::{'$foo'}
$::&lt;foo>
::&lt;$foo></pre>
<p>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).</p>
<p>As a result of these rules, you can write any arbitrary variable name as either of:</p>
<pre class="code">$::{'!@#$#@'}
::{'$!@#$#@'}</pre>
<p>You can also use the <span class="code">::&lt;> </span> form as long as there are no spaces in the name.</p>
<a name="t23.3.3"$class><h2>23.3.3 Package lookup</h2></a>
<p>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 <span class="code">:: </span> postfix:</p>
<pre class="code">MyType::&lt;$foo></pre>
<a name="t23.4"$class><h1>23.4 Globals</h1></a>
<p>Interpreter globals live in the <span class="code">GLOBAL </span> package. The user's program starts in the <span class="code">GLOBAL </span> package, so "our" declarations in the mainline code go into that package by default. Process-wide variables live in the <span class="code">PROCESS </span> package. Most predefined globals such as <span class="code">$*UID </span> and <span class="code">$*PID </span> are actually process globals.</p>
<a name="t24"><h1 class="title">24 Phasers</h1></a> <p class="subtitle">Program execution phases and corresponding phaser blocks</p></a> <p>The lifetime (execution timeline) of a program is broken up into phases. A <i>phaser</i> is a block of code called during a specific execution phase.</p>
<a name="t24.1"$class><h1>24.1 Phasers</h1></a>
<p>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 <i>phasers</i> , since they generally mark the transition from one phase of computing to another. For instance, a <span class="code">CHECK </span> 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.</p>
<p>Here is a summary:</p>
<pre class="code">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</pre>
<pre class="code">CONTROL {...} # catch control exceptions, before LEAVE
COMPOSE {...} # when a role is composed into a class</pre>
<p>Phasers marked with a <span class="code">* </span> 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:</p>
<pre class="code">my $compiletime = BEGIN { now };
our $temphandle = ENTER { maketemp() };</pre>
<p>As with other statement prefixes, these value-producing constructs may be placed in front of either a block or a statement:</p>
<pre class="code">my $compiletime = BEGIN now;
our $temphandle = ENTER maketemp();</pre>
<p>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.</p>
<p>These declare the same variables with the same scope as the preceding example, but run the statements as a whole at the indicated time:</p>
<pre class="code">BEGIN my $compiletime = now;
ENTER our $temphandle = maketemp();</pre>
<p>(Note, however, that the value of a variable calculated at compile time may not persist under run-time cloning of any surrounding closure.)</p>
<p>Most of the non-value-producing phasers may also be so used:</p>
<pre class="code">END say my $accumulator;</pre>
<p>Note, however, that</p>
<pre class="code">END say my $accumulator = 0;</pre>
<p>sets the variable to 0 at <span class="code">END </span> time, since that is when the "my" declaration is actually executed. Only argumentless phasers may use the statement form. This means that <span class="code">CATCH </span> and <span class="code">CONTROL </span> always require a block, since they take an argument that sets <span class="code">$_ </span> 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 <span class="code">$_ </span> would leak out past the end of the <span class="code">CATCH </span> or <span class="code">CONTROL </span> , with unpredictable and quite possibly dire consequences. Exception handlers are supposed to reduce uncertainty, not increase it.)</p>
<p>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:</p>
<pre class="code">our $h will enter { .rememberit() } will undo { .forgetit() };</pre>
<p>Only phasers that can occur multiple times within a block are eligible for this per-variable form.</p>
<p>The topic of the block outside a phaser is still available as <span class="code">OUTER::&lt;$_> </span> . 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 <span class="code">POST </span> phaser, but a <span class="code">LEAVE </span> phaser could be more liberal.</p>
<p>Any phaser defined in the lexical scope of a method is a closure that closes over <span class="code">self </span> as well as normal lexicals. (Or equivalently, an implementation may simply turn all such phasers into submethods whose primed invocant is the current object.)</p>
<p>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.</p>
<a name="t24.1.1"$class><h2>24.1.1 Execution Order</h2></a>
<pre class="code">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
Post-condition for block
POST {...} # assert postcondition at every block exit, after LEAVE
Program terminating
END {...} # at run time, ALAP, only ever runs once</pre>
<a name="t24.2"$class><h1>24.2 Program Execution Phasers</h1></a>
<a name="t24.2.1"$class><h2>24.2.1 BEGIN</h2></a>
<p>Runs at compile time, As Soon As Possible, only runs once.</p>
<p>Can have a return value that is provided even in later phases.</p>
<a name="t24.2.2"$class><h2>24.2.2 CHECK</h2></a>
<p>Runs at compile time, As Last As Possible, only runs once.</p>
<p>Can have a return value that is provided even in later phases.</p>
<p>Code that is generated at run time can still fire off <span class="code">CHECK </span> and <span class="code">INIT </span> phasers, though of course those phasers can't do things that would require travel back in time. You need a wormhole for that.</p>
<a name="t24.2.3"$class><h2>24.2.3 LINK</h2></a>
<p>Runs at link time, As Last As Possible, only runs once.</p>
<p>Can have a return value that is provided even in later phases.</p>
<p>The compiler is free to ignore <span class="code">LINK </span> phasers compiled at run time since they're too late for the application-wide linking decisions.</p>
<a name="t24.2.4"$class><h2>24.2.4 INIT</h2></a>
<p>Runs after compilation during main execution, As Soon As Possible, only runs once.</p>
<p>Can have a return value that is provided even in later phases.</p>
<p>When phasers are in different modules, the <span class="code">INIT </span> and <span class="code">END </span> phasers are treated as if declared at <span class="code">use </span> 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.)</p>
<p>Code that is generated at run time can still fire off <span class="code">CHECK </span> and <span class="code">INIT </span> phasers, though of course those phasers can't do things that would require travel back in time. You need a wormhole for that.</p>
<p>An <span class="code">INIT </span> only runs once for all copies of a cloned closure.</p>
<a name="t24.2.5"$class><h2>24.2.5 END</h2></a>
<p>Runs after compilation during main execution, As Last As Possible, only runs once.</p>
<p>When phasers are in different modules, the <span class="code">INIT </span> and <span class="code">END </span> phasers are treated as if declared at <span class="code">use </span> 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.)</p>
<a name="t24.3"$class><h1>24.3 Block Phasers</h1></a>
<p>Execution in the context of a block has it's own phases.</p>
<p>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.</p>
<p>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 <span class="code">ENTER </span> trait of a block, you'll find that it's really a list of phasers rather than a single phaser.</p>
<p>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.)</p>
<a name="t24.3.1"$class><h2>24.3.1 ENTER</h2></a>
<p>Runs at every block entry time, repeats on loop blocks.</p>
<p>Can have a return value that is provided even in later phases.</p>
<p>An exception thrown from an <span class="code">ENTER </span> phaser will abort the <span class="code">ENTER </span> queue, but one thrown from a <span class="code">LEAVE </span> phaser will not.</p>
<a name="t24.3.2"$class><h2>24.3.2 LEAVE</h2></a>
<p>Runs at every block exit time (even stack unwinds from exceptions).</p>
<p>So <span class="code">LEAVE </span> phasers for a given block are necessarily evaluated after any <span class="code">CATCH </span> and <span class="code">CONTROL </span> phasers. This includes the <span class="code">LEAVE </span> variants, <span class="code">KEEP </span> and <span class="code">UNDO </span> . <span class="code">POST </span> phasers are evaluated after everything else, to guarantee that even <span class="code">LEAVE </span> phasers can't violate postconditions.</p>
<p>An exception thrown from an <span class="code">ENTER </span> phaser will abort the <span class="code">ENTER </span> queue, but one thrown from a <span class="code">LEAVE </span> phaser will not.</p>
<p>If a <span class="code">POST </span> fails or any kind of <span class="code">LEAVE </span> 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.</p>
<a name="t24.3.3"$class><h2>24.3.3 KEEP</h2></a>
<p>Runs at every successful block exit, as part of the LEAVE queue (shares the same order of execution).</p>
<p>For phasers such as <span class="code">KEEP </span> and <span class="code">POST </span> 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.</p>
<a name="t24.3.4"$class><h2>24.3.4 UNDO</h2></a>
<p>Runs at every unsuccessful block exit, as part of the LEAVE queue (shares the same order of execution).</p>
<a name="t24.3.5"$class><h2>24.3.5 PRE</h2></a>
<p>Asserts a precondition at every block entry. Runs before the ENTER phase.</p>
<p> <span class="code">PRE </span> phasers fire off before any <span class="code">ENTER </span> or <span class="code">FIRST </span> .</p>
<p>The exceptions thrown by failing <span class="code">PRE </span> and <span class="code">POST </span> phasers cannot be caught by a <span class="code">CATCH </span> in the same block, which implies that <span class="code">POST </span> phaser are not run if a <span class="code">PRE </span> phaser fails.</p>
<a name="t24.3.6"$class><h2>24.3.6 POST</h2></a>
<p>Asserts a postcondition at every block entry. Runs after the LEAVE phase.</p>
<p>For phasers such as <span class="code">KEEP </span> and <span class="code">POST </span> 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.</p>
<p>The <span class="code">POST </span> block can be defined in one of two ways. Either the corresponding <span class="code">POST </span> is defined as a separate phaser, in which case <span class="code">PRE </span> and <span class="code">POST </span> share no lexical scope. Alternately, any <span class="code">PRE </span> phaser may define its corresponding <span class="code">POST </span> as an embedded phaser block that closes over the lexical scope of the <span class="code">PRE </span> .</p>
<p>If a <span class="code">POST </span> fails or any kind of <span class="code">LEAVE </span> 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.</p>
<p>The exceptions thrown by failing <span class="code">PRE </span> and <span class="code">POST </span> phasers cannot be caught by a <span class="code">CATCH </span> in the same block, which implies that <span class="code">POST </span> phaser are not run if a <span class="code">PRE </span> phaser fails.</p>
<a name="t24.4"$class><h1>24.4 Loop Phasers</h1></a>
<p> <span class="code">FIRST </span> , <span class="code">NEXT </span> , and <span class="code">LAST </span> are meaningful only within the lexical scope of a loop, and may occur only at the top level of such a loop block.</p>
<a name="t24.4.1"$class><h2>24.4.1 FIRST</h2></a>
<p>Runs at loop initialization, before ENTER.</p>
<p>Can have a return value that is provided even in later phases.</p>
<a name="t24.4.2"$class><h2>24.4.2 NEXT</h2></a>
<p>Runs when loop is continued (either through <span class="code">next </span> or because you got to the bottom of the loop and are looping back around), before LEAVE.</p>
<p>A <span class="code">NEXT </span> executes only if the end of the loop block is reached normally, or an explicit <span class="code">next </span> is executed. In distinction to <span class="code">LEAVE </span> phasers, a <span class="code">NEXT </span> phaser is not executed if the loop block is exited via any exception other than the control exception thrown by <span class="code">next </span> . In particular, a <span class="code">last </span> bypasses evaluation of <span class="code">NEXT </span> phasers.</p>
<a name="t24.4.3"$class><h2>24.4.3 LAST</h2></a>
<p>Runs when loop is aborted (either through <span class="code">last </span> , or <span class="code">return </span> , or because you got to the bottom of the loop and are done), after LEAVE.</p>
<a name="t24.5"$class><h1>24.5 Exception Handling Phasers</h1></a>
<a name="t24.5.1"$class><h2>24.5.1 CATCH</h2></a>
<p>Runs when an exception is raised by the current block, before the LEAVE phase.</p>
<a name="t24.5.2"$class><h2>24.5.2 CONTROL</h2></a>
<p>Runs when a control exception is raised by the current block, before the LEAVE phase.</p>
<a name="t24.6"$class><h1>24.6 Object Phasers</h1></a>
<a name="t24.6.1"$class><h2>24.6.1 COMPOSE</h2></a>
<p>Runs when a role is composed into a class.</p>
<a name="t25"><h1 class="title">25 Quoting Constructs</h1></a> <p class="subtitle">Writing strings, word lists, and regexes in Perl 6</p></a> <a name="t25.1"$class><h1>25.1 The Q Lang</h1></a>
<p>Strings are usually represented in Perl 6 code using some form of quoting construct. The most minimalistic of these is <span class="code">Q </span> , usable via the shortcut <span class="code">「…」 </span> , or via <span class="code">Q </span> followed by any pair of delimiters surrounding your text. Most of the time, though, the most you'll need is <span class="code">'…' </span> or <span class="code">"…" </span> , described in more detail in the following sections.</p>
<a name="t25.1.1"$class><h2>25.1.1 Literal strings: Q </h2></a>
<pre class="code"> <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>
</pre>
<p>Delimiters can be nested, but in the plain <span class="code">Q </span> form, backslash escapes aren't allowed. In other words, basic <span class="code">Q </span> strings are as literal as possible.</p>
<pre class="code">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> }
</pre>
<p>These examples produce:</p>
<pre class="code">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 → \</pre>
<p>The other quote forms add to this basic functionality:</p>
<a name="t25.1.2"$class><h2>25.1.2 Escaping: q </h2></a>
<pre class="code"> <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 culy 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>
</pre>
<p>The <span class="code">q </span> 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 <span class="code">'…' </span> or <span class="code">q </span> followed by a delimiter, but it's also available as an adverb on <span class="code">Q </span> , as in the fifth and last example above.</p>
<p>These examples produce:</p>
<pre class="code">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</pre>
<a name="t25.1.3"$class><h2>25.1.3 Interpolation: qq </h2></a>
<pre class="code">my $color = 'blue';
<a href="">say</a> <b>"</b> My favorite color is <b>$color</b> ! <b>"</b>
</pre>
<pre class="code">My favorite color is blue!</pre>
<p>The <span class="code">qq </span> 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 <span class="code">qq </span> -quoted string:</p>
<pre class="code">say <b>"</b> The <b>\</b> $color variable contains the value '$color' <b>"</b> ;
</pre>
<pre class="code">The $color variable contains the value 'blue'</pre>
<p>Another feature of <span class="code">qq </span> is the ability to interpolate Perl 6 code from within the string, using curly braces:</p>
<pre class="code">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³!"
</pre>
<pre class="code">This room is 4 m by 3.5 m by 3 m.
Therefore its volume should be 42 m³!</pre>
<p>By default, only variables with the <span class="code">$ </span> sigil are interpolated normally. This way, when you write <span class="code">"documentation@perl6.org" </span> , you aren't interpolating the <span class="code">@perl6 </span> variable. If that's what you want to do, append a <span class="code">[] </span> to the variable name:</p>
<pre class="code">my @neighbors = "Felix", "Danielle", "Lucinda";
say "@neighbors <b>[]</b> and I try our best to coexist peacefully."
</pre>
<pre class="code">Felix Danielle Lucinda and I try our best to coexist peacefully.</pre>
<p>Often a method call is more appropriate. These are allowed within <span class="code">qq </span> quotes as long as they have parentheses after the call. Thus the following code will work:</p>
<pre class="code">say "@neighbors <b>. <a href="">join</a> (', ')</b> and I try our best to coexist peacefully."
</pre>
<pre class="code">Felix, Danielle, Lucinda and I try our best to coexist peacefully.</pre>
<p>However, <span class="code">"@example.com" </span> produces <span class="code">@example.com </span> .</p>
<a name="t25.1.4"$class><h2>25.1.4 Word quoting: qw </h2></a>
<pre class="code"> <b>&lt;</b> a b c <b>></b> <a href="">eqv</a> ('a', 'b', 'c')
<b>qw|</b> ! @ # $ % ^ &amp; * \| &lt; > <b>|</b> eqv '! @ # $ % ^ &amp; | &lt; >'.words
<b>Q:w {</b> [ ] \{ \} <b>}</b> eqv ('[', ']', '{', '}')
</pre>
<p>The <span class="code">:w </span> form, usually written <span class="code">&lt;…> </span> or <span class="code">qw </span> , splits the string into "words". In this context, words are defined as sequences of non-whitespace characters separated by whitespace. The <span class="code">q:w </span> and <span class="code">qw </span> forms inherit the interpolation and escape semantics of the <span class="code">q </span> and single quote string delimiters, whereas <span class="code">Qw </span> and <span class="code">Q:w </span> inherit the non-escaping semantics of the <span class="code">Q </span> quoter.</p>
<p>This form is used in preference to using many quotation marks and commas for lists of strings. For example, where you could write:</p>
<pre class="code">my @directions = 'left', 'right,', 'up', 'down';</pre>
<p>It's easier to write and to read this:</p>
<pre class="code">my @directions = &lt;left right up down>;</pre>
<a name="t25.1.5"$class><h2>25.1.5 Word quoting with interpolation: qqw </h2></a>
<p>The <span class="code">qw </span> form of word quoting doesn't interpolate variables:</p>
<pre class="code">my $a = 42; say qw{$a b c}; # $a b c</pre>
<p>Thus, if you wish for variables to be interpolated within the quoted string, you need to use the <span class="code">qqw </span> variant:</p>
<pre class="code">my $a = 42;
my @list = qqw{$a b c};
say @list; # 42 b c</pre>
<p>or equivalently:</p>
<pre class="code">my $a = 42;
my @list = «$a b c»;
say @list; # 42 b c</pre>
<a name="t25.1.6"$class><h2>25.1.6 Shell quoting: qx </h2></a>
<p>To run a string as an external program, not only is it possible to pass the string to the <span class="code">shell </span> or <span class="code">run </span> functions but one can also perform shell quoting in a similar manner to the backticks a.k.a. <span class="code">qx </span> in Perl 5. There are some subtleties to consider, however. The backticks are no longer used for shell quoting in Perl 6 and the <span class="code">qx </span> quotes <i>don't</i> interpolate Perl variables. Thus</p>
<pre class="code">my $world = "there";
say qx{echo "hello $world"}</pre>
<p>prints simply <span class="code">hello </span> . Nevertheless, if you have declared an environment variable before calling <span class="code">perl6 </span> , this will be available within <span class="code">qx </span> , for instance</p>
<pre class="code">WORLD="there" perl6
> say qx{echo "hello $WORLD"}</pre>
<p>will now print <span class="code">hello there </span> .</p>
<p>The result of calling <span class="code">qx </span> is returned, so this information can be assigned to a variable for later use:</p>
<pre class="code">my $output = qx{echo "hello!"};
say $output; # hello!</pre>
<p>See also <a href="/routine/shell">shell</a> , <a href="/routine/run">run</a> and <a href="">Proc::Async</a> for other ways to execute external commands.</p>
<a name="t25.1.7"$class><h2>25.1.7 Shell quoting with interpolation: qqx </h2></a>
<p>If one wishes to use the content of a Perl variable within an external command, then the <span class="code">qqx </span> shell quoting construct should be used (this corresponds to Perl 5's <span class="code">qx </span> ):</p>
<pre class="code">my $world = "there";
say qqx{echo "hello $world"}; # hello there</pre>
<p>Again, the output of the external command can be kept in a variable:</p>
<pre class="code">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␤ ...</pre>
<p>See also <a href="/routine/shell">shell</a> and <a href="/routine/run">run</a> for other ways to execute external commands.</p>
<a name="t25.1.8"$class><h2>25.1.8 Heredocs: :to</h2></a>
<p>A convenient way to write multi-line string literals are <i>heredocs</i> , which let you choose the delimiter yourself:</p>
<pre class="code">say q:to/END/;
Here is
some multi-line
string
END
</pre>
<p>The contents of the heredoc only begin on the next line, so you can (and should) finish the line.</p>
<pre class="code">my $escaped = my-escaping-function(q:to/TERMINATOR/, language => 'html');
Here are the contents of the heredoc.
Potentially multiple lines.
TERMINATOR
</pre>
<p>If the terminator is indented, that amount of indention is removed from the string literals. Therefore this heredoc</p>
<pre class="code">say q:to/END/;
Here is
some multi line
string
END
</pre>
<p>produces this output:</p>
<pre class="code">Here is
some multi line
string
</pre>
<p>Heredocs include the newline from before the terminator.</p>
<a name="t25.2"$class><h1>25.2 Regexes</h1></a>
<p>For information about quoting as applied in regexes see the <a href="/language/regexes">regular expression documentation</a> .</p>
<a name="t26"><h1 class="title">26 Regexes</h1></a> <p class="subtitle">Pattern matching against strings</p></a> <p>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.</p>
<p>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 <i>regex</i> has stuck and continues to mean <i>regular expression-like pattern matching</i> .</p>
<p>In Perl 6, although they are capable of much more than regular languages, we continue to call them <i>regexes</i> .</p>
<a name="t26.1"$class><h1>26.1 Lexical conventions </h1></a>
<p>Perl 6 has special syntax for writing regexes:</p>
<pre class="code">m/abc/; # a regex that is immediately matched against $_
rx/abc/; # a Regex object
/abc/; # a Regex object</pre>
<p>The first two can use delimiters other than the slash:</p>
<pre class="code">m{abc};
rx{abc};</pre>
<p>Note that neither the colon <span class="code">: </span> nor round parentheses can be delimiters; the colon is forbidden because it clashes with adverbs, such as <span class="code">rx:i/abc/ </span> (case insensitive regexes), and round parentheses indicate a function call instead.</p>
<p>Whitespace in regexes is generally ignored (except with the <span class="code">:s </span> or <span class="code">:sigspace </span> adverb).</p>
<p>As in the rest of Perl 6, comments in regexes start with a hash character <span class="code"># </span> and go to the end of the current line.</p>
<a name="t26.2"$class><h1>26.2 Literals</h1></a>
<p>The simplest case of a regex is a constant string. Matching a string against that regex searches for that string:</p>
<pre class="code">if 'properly' ~~ m/ perl / {
say "'properly' contains 'perl'";
}</pre>
<p>Alphanumeric characters and the underscore <span class="code">_ </span> are literal matches. All other characters must either be escaped with a backslash (for example <span class="code">\: </span> to match a colon), or included in quotes:</p>
<pre class="code">/ 'two words' / # matches 'two words' including the blank
/ "a:b" / # matches 'a:b' including the colon
/ '#' / # matches a hash character</pre>
<p>Strings are searched left to right for the regex, thus it is sufficient if a substring matches the regex:</p>
<pre class="code">if 'abcdef' ~~ / de / {
say ~$/; # de
say $/.prematch; # abc
say $/.postmatch; # f
say $/.from; # 3
say $/.to; # 5
};</pre>
<p>Match results are stored in the <span class="code">$/ </span> variable and are also returned from the match. The result is of <a href="/type/Match">type Match</a> if the match was successful; otherwise it is <a href="/type/Nil">Nil</a> .</p>
<a name="t26.3"$class><h1>26.3 Wildcards and character classes</h1></a>
<a name="t26.3.1"$class><h2>26.3.1 Dot to match any character </h2></a>
<p>An unescaped dot <span class="code">. </span> in a regex matches any single character.</p>
<p>So these all match:</p>
<pre class="code">'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</pre>
<p>This doesn't match:</p>
<pre class="code">'perl' ~~ /. per /</pre>
<p>because there is no character to match before <span class="code">per </span> in the target string.</p>
<a name="t26.3.2"$class><h2>26.3.2 Backslashed, predefined character classes</h2></a>
<p>There are predefined character classes of the form <span class="code">\w </span> . Its negation is written with an upper-case letter, <span class="code">\W </span> .</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r81">\d and \D</a></span> </p>
</li></ul> <p> <span class="code">\d </span> matches a single digit (Unicode property <span class="code">N </span> ) and <span class="code">\D </span> matches a single character that is not a digit.</p>
<pre class="code">'ab42' ~~ /\d/ and say ~$/; # 4
'ab42' ~~ /\D/ and say ~$/; # a</pre>
<p>Note that not only the Arabic digits (commonly used in the Latin alphabet) match <span class="code">\d </span> , but also digits from other scripts.</p>
<p>Examples for digits are:</p>
<pre class="code">U+0035 5 DIGIT FIVE
U+07C2 ߂ NKO DIGIT TWO
U+0E53 ๓ THAI DIGIT THREE
U+1B56 ᭖ BALINESE DIGIT SIX</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r82">\h and \H</a></span> </p>
</li></ul> <p> <span class="code">\h </span> matches a single horizontal whitespace character. <span class="code">\H </span> matches a single character that is not a horizontal whitespace character.</p>
<p>Examples for horizontal whitespace characters are</p>
<pre class="code">U+0020 SPACE
U+00A0 NO-BREAK SPACE
U+0009 CHARACTER TABULATION
U+2001 EM QUAD</pre>
<p>Vertical whitespace like newline characters are explicitly excluded; those can be matched with <span class="code">\v </span> , and <span class="code">\s </span> matches any kind of whitespace.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r83">\n and \N</a></span> </p>
</li></ul> <p> <span class="code">\n </span> matches a single, logical newline character. <span class="code">\n </span> 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. <span class="code">\N </span> matches a single character that's not a logical newline.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r84">\s and \S</a></span> </p>
</li></ul> <p> <span class="code">\s </span> matches a single whitespace character. <span class="code">\S </span> matches a single character that is not whitespace.</p>
<pre class="code">if 'contains a word starting with "w"' ~~ / w \S+ / {
say ~$/; # word
}</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r85">\t and \T</a></span> </p>
</li></ul> <p> <span class="code">\t </span> matches a single tab/tabulation character, <span class="code">U+0009 </span> . (Note that exotic tabs like the <span class="code">U+000B VERTICAL TABULATION </span> character are not included here). <span class="code">\T </span> matches a single character that is not a tab.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r86">\v and \V</a></span> </p>
</li></ul> <p> <span class="code">\v </span> matches a single vertical whitespace character. <span class="code">\V </span> matches a single character that is not vertical whitespace.</p>
<p>Examples for vertical whitespace characters:</p>
<pre class="code">U+000A LINE FEED
U+000B VERTICAL TABULATION
U+000C CARRIAGE RETURN
U+0085 NEXT LINE
U+2029 PARAGRAPH SEPARATOR</pre>
<p>Use <span class="code">\s </span> to match any kind of whitespace, not just vertical whitespace.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r87">\w and \W</a></span> </p>
</li></ul> <p> <span class="code">\w </span> matches a single word character, i.e. a letter (Unicode category L), a digit or an underscore. <span class="code">\W </span> matches a single character that isn't a word character.</p>
<p>Examples of word characters:</p>
<pre class="code">0041 A LATIN CAPITAL LETTER A
0031 1 DIGIT ONE
03B4 δ GREEK SMALL LETTER DELTA
03F3 ϳ GREEK LETTER YOT
0409 Љ CYRILLIC CAPITAL LETTER LJE</pre>
<a name="t26.3.3"$class><h2>26.3.3 Unicode properties </h2></a>
<p>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 <span class="code"> &lt;:property> </span> , where <span class="code">property </span> can be a short or long Unicode property name.</p>
<p>The following list is stolen from the Perl 5 <a href="http://perldoc.perl.org/perlunicode.html">perlunicode</a> documentation:</p>
<table>
<tr><th>Short</th> <th>Long</th></tr>
<tr><td>L</td> <td>Letter</td></tr>
<tr><td>LC</td> <td>Cased_Letter</td></tr>
<tr><td>Lu</td> <td>Uppercase_Letter</td></tr>
<tr><td>Ll</td> <td>Lowercase_Letter</td></tr>
<tr><td>Lt</td> <td>Titlecase_Letter</td></tr>
<tr><td>Lm</td> <td>Modifier_Letter</td></tr>
<tr><td>Lo</td> <td>Other_Letter</td></tr>
<tr><td>M</td> <td>Mark</td></tr>
<tr><td>Mn</td> <td>Nonspacing_Mark</td></tr>
<tr><td>Mc</td> <td>Spacing_Mark</td></tr>
<tr><td>Me</td> <td>Enclosing_Mark</td></tr>
<tr><td>N</td> <td>Number</td></tr>
<tr><td>Nd</td> <td>Decimal_Number (also Digit)</td></tr>
<tr><td>Nl</td> <td>Letter_Number</td></tr>
<tr><td>No</td> <td>Other_Number</td></tr>
<tr><td>P</td> <td>Punctuation (also Punct)</td></tr>
<tr><td>Pc</td> <td>Connector_Punctuation</td></tr>
<tr><td>Pd</td> <td>Dash_Punctuation</td></tr>
<tr><td>Ps</td> <td>Open_Punctuation</td></tr>
<tr><td>Pe</td> <td>Close_Punctuation</td></tr>
<tr><td>Pi</td> <td>Initial_Punctuation</td></tr>
<tr><td></td> <td>(may behave like Ps or Pe depending on usage)</td></tr>
<tr><td>Pf</td> <td>Final_Punctuation</td></tr>
<tr><td></td> <td>(may behave like Ps or Pe depending on usage)</td></tr>
<tr><td>Po</td> <td>Other_Punctuation</td></tr>
<tr><td>S</td> <td>Symbol</td></tr>
<tr><td>Sm</td> <td>Math_Symbol</td></tr>
<tr><td>Sc</td> <td>Currency_Symbol</td></tr>
<tr><td>Sk</td> <td>Modifier_Symbol</td></tr>
<tr><td>So</td> <td>Other_Symbol</td></tr>
<tr><td>Z</td> <td>Separator</td></tr>
<tr><td>Zs</td> <td>Space_Separator</td></tr>
<tr><td>Zl</td> <td>Line_Separator</td></tr>
<tr><td>Zp</td> <td>Paragraph_Separator</td></tr>
<tr><td>C</td> <td>Other</td></tr>
<tr><td>Cc</td> <td>Control (also Cntrl)</td></tr>
<tr><td>Cf</td> <td>Format</td></tr>
<tr><td>Cs</td> <td>Surrogate</td></tr>
<tr><td>Co</td> <td>Private_Use</td></tr>
<tr><td>Cn</td> <td>Unassigned</td></tr>
</table> <p>For example <span class="code">&lt;:Lu> </span> matches a single, upper-case letter.</p>
<p>Negation works as <span class="code">&lt;:!category> </span> , so <span class="code">&lt;:!Lu> </span> matches a single character that isn't an upper-case letter.</p>
<p>Several categories can be combined with one of these infix operators:</p>
<table>
<tr><th>Operator</th> <th>Meaning</th></tr>
<tr><td>+</td> <td>set union</td></tr>
<tr><td>|</td> <td>set union</td></tr>
<tr><td>&amp;</td> <td>set intersection</td></tr>
<tr><td>-</td> <td>set difference (first minus second)</td></tr>
<tr><td>^</td> <td>symmetric set intersection / XOR</td></tr>
</table> <p>So, to match either a lower-case letter or a number, one can write <span class="code">&lt;:Ll+:N> </span> or <span class="code">&lt;:Ll+:Number> </span> or <span class="code">&lt;+ :Lowercase_Letter + :Number> </span> .</p>
<p>It is also possible to group categories and sets of categories with parentheses, e.g.:</p>
<pre class="code">'perl6' ~~ m{\w+(&lt;:Ll+:N>)} # 0 => 「6」</pre>
<a name="t26.3.4"$class><h2>26.3.4 Enumerated character classes and ranges </h2></a>
<p>Sometimes the pre-existing wildcards and character classes are not enough. Fortunately, defining your own is fairly simple. Between <span class="code">&lt;[ ]> </span> , you can put any number of single characters and ranges of characters (expressed with two dots between the end points), with or without whitespace.</p>
<pre class="code">"abacabadabacaba" ~~ / &lt;[ a .. c 1 2 3 ]> /</pre>
<p>Between the <span class="code">&lt; > </span> you can also use the same operators for categories ( <span class="code">+ </span> , <span class="code">| </span> , <span class="code">&amp; </span> , <span class="code">- </span> , <span class="code">^ </span> ) 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 <span class="code">[ ] </span> .</p>
<pre class="code">/ &lt;[\d] - [13579]> /
# not quite the same as
/ &lt;[02468]>
# because the first one also contains "weird" unicodey digits</pre>
<p>To negate a character class, put a <span class="code">- </span> after the opening angle:</p>
<pre class="code">say 'no quotes' ~~ / &lt;-[ " ]> + /; # matches characters except "</pre>
<p>A common pattern for parsing quote-delimited strings involves negated character classes:</p>
<pre class="code">say '"in quotes"' ~~ / '"' &lt;-[ " ]> * '"'/;</pre>
<p>This first matches a quote, then any characters that aren't quotes, and then a quote again. The meaning of <span class="code">* </span> and <span class="code">+ </span> in the examples above are explained in <a href="#Quantifier">section Quantifier</a> .</p>
<p>Just as you can use the <span class="code">- </span> for both set difference and negation of a single value, you can also explicitly put a <span class="code">+ </span> in front:</p>
<pre class="code">/ &lt;+[123]> / # same as &lt;[123]></pre>
<a name="t26.4"$class><h1>26.4 Quantifiers</h1></a>
<p>A quantifier makes a preceding atom match not exactly once, but rather a variable number of times. For example <span class="code">a+ </span> matches one or more <span class="code">a </span> characters.</p>
<p>Quantifiers bind tighter than concatenation, so <span class="code">ab+ </span> matches one <span class="code">a </span> followed by one or more <span class="code">b </span> s. This is different for quotes, so <span class="code">'ab'+ </span> matches the strings <span class="code">ab </span> , <span class="code">abab </span> , <span class="code">ababab </span> etc.</p>
<a name="t26.4.1"$class><h2>26.4.1 One or more: + </h2></a>
<p>The <span class="code">+ </span> quantifier makes the preceding atom match one or more times, with no upper limit.</p>
<p>For example to match strings of the form <span class="code">key=value </span> , you can write a regex like this:</p>
<pre class="code">/ \w+ '=' \w+ /</pre>
<a name="t26.4.2"$class><h2>26.4.2 Zero or more: * </h2></a>
<p>The <span class="code">* </span> quantifier makes the preceding atom match zero or more times, with no upper limit.</p>
<p>For example to allow optional whitespace between <span class="code">a </span> and <span class="code">b </span> you can write</p>
<pre class="code">/ a \s* b /</pre>
<a name="t26.4.3"$class><h2>26.4.3 Zero or one match: ? </h2></a>
<p>The <span class="code">? </span> quantifier makes the preceding atom match zero or once.</p>
<a name="t26.4.4"$class><h2>26.4.4 General quantifier: ** min..max </h2></a>
<p>To quantify an atom an arbitrary number of times, you can write e.g. <span class="code">a ** 2..5 </span> to match the character <span class="code">a </span> at least twice and at most 5 times.</p>
<pre class="code"> say Bool('a' ~~ /a ** 2..5/); #-> False
say Bool('aaa' ~~ /a ** 2..5/); #-> True
</pre>
<p>If the minimal and maximal number of matches are the same, a single integer is possible: <span class="code">a ** 5 </span> matches <span class="code">a </span> exactly five times.</p>
<pre class="code"> say Bool('aaaaa' ~~ /a ** 5/); #-> True
</pre>
<p>It is also posible to use non inclusive ranges using a caret:</p>
<pre class="code"> say Bool('a' ~~ /a ** 1^..^6); #-> False
say Bool('aaaa' ~~ /a ** 1^..^6); #-> True
</pre>
<p>This includes the numeric ranges staring from 0:</p>
<pre class="code"> say Bool('aaa' ~~ /a ** ^6/); #->true
</pre>
<p>or a Whatever operator for an infinite range with a non inclusive minimum:</p>
<pre class="code"> say Bool('aaaa' ~~ /a ~~ 1^..*/); #-> True
</pre>
<a name="t26.4.5"$class><h2>26.4.5 Modified quantifier: % </h2></a>
<p>To more easily match things like comma separated values, you can tack on a <span class="code">% </span> modifier to any of the above quantifiers to specify a separator than must occur between each of the matches. So, for example <span class="code">a+ % ',' </span> will match <span class="code">a </span> or <span class="code">a,a </span> or <span class="code">a,a,a </span> or so on, but it will not match <span class="code">a, </span> or <span class="code">a,a, </span> . To match those as well, you may use <span class="code">%% </span> instead of <span class="code">% </span> .</p>
<a name="t26.5"$class><h1>26.5 Alternation </h1></a>
<p>To match one of several possible alternatives, separate them by <span class="code">|| </span> ; the first matching alternative wins.</p>
<p>For example, <span class="code">ini </span> files have the following form:</p>
<pre class="code">[section]
key = value</pre>
<p>Hence, if you parse a single line of an <span class="code">ini </span> file, it can be either a section or a key-value pair and the regex would be (to a first approximation):</p>
<pre class="code">/ '[' \w+ ']' || \S+ \s* '=' \s* \S* /</pre>
<p>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 <span class="code">= </span> , followed again by optional whitespace, followed by another string of non-whitespace characters.</p>
<a name="t26.6"$class><h1>26.6 Longest Alternation </h1></a>
<p>In regexes branches separated by <span class="code">| </span> , the longest match wins, independent of the lexical ordering in the regexes.</p>
<pre class="code">say ('abc' ~~ / a | .b /).Str;</pre>
<a name="t26.7"$class><h1>26.7 Anchors</h1></a>
<p>The regex engine tries to find a match inside a string by searching from left to right.</p>
<pre class="code">say so 'properly' ~~ / perl/; # True
# ^^^^</pre>
<p>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. <i>Anchors</i> or <i>assertions</i> can help you with this by limiting where they match.</p>
<p>Anchors need to match successfully in order for the whole regex to match but they do not use up characters while matching.</p>
<a name="t26.7.1"$class><h2>26.7.1 <span class="code">^ </span> , Start of String </h2></a>
<p>The <span class="code">^ </span> assertion only matches at the start of the string.</p>
<pre class="code">say so 'properly' ~~ /perl/; # True
say so 'properly' ~~ /^ perl/; # False
say so 'perly' ~~ /^ perl/; # True
say so 'perl' ~~ /^ perl/; # True</pre>
<a name="t26.7.2"$class><h2>26.7.2 <span class="code">^^ </span> , Start of Line and <span class="code">$$ </span> , End of Line </h2></a>
<p>The <span class="code">^^ </span> assertion matches at the start of a logical line. That is, either at the start of the string, or after a newline character.</p>
<p> <span class="code">$$ </span> 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.</p>
<p>(To understand the following example, it is important to know that the <span class="code">q:to/EOS/...EOS </span> "heredoc" syntax removes leading indention to the same level as the <span class="code">EOS </span> marker, so that the first, second and last lines have no leading space and the third and fourth lines have two leading spaces each).</p>
<pre class="code"> 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)
</pre>
<a name="t26.7.3"$class><h2>26.7.3 <span class="code">&lt;&lt; </span> and <span class="code">>> </span> , left and right word boundary </h2></a>
<p> <span class="code">&lt;&lt; </span> 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.</p>
<p> <span class="code">>> </span> 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).</p>
<pre class="code">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</pre>
<a name="t26.8"$class><h1>26.8 Grouping and Capturing </h1></a>
<p>In regular (non-regex) Perl 6, you can use parentheses to group things together, usually to override operator precedence:</p>
<pre class="code">say 1 + 4 * 2; # 9, because it is parsed as 1 + (4 * 2)
say (1 + 4) * 2; # 10</pre>
<p>The same grouping facility is available in regexes:</p>
<pre class="code">/ a || b c / # matches 'a' or 'bc'
/ ( a || b ) c / # matches 'ac' or 'bc'</pre>
<p>The same grouping applies to quantifiers:</p>
<pre class="code">/ 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</pre>
<p>An unquantified capture produces a <a href="">Match</a> object. When a capture is quantified (except with the <span class="code">? </span> quantifier) the capture becomes a list of <a href="">Match</a> objects instead.</p>
<a name="t26.8.1"$class><h2>26.8.1 Capturing</h2></a>
<p>The round parentheses don't just group, they also <i>capture</i> ; that is, they make the string matched within the group available as a variable, and also as an element of the resulting <a href="/type/Match">Match</a> object:</p>
<pre class="code">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
}</pre>
<p>Pairs of parentheses are numbered left to right, starting from zero.</p>
<pre class="code">if 'abc' ~~ /(a) b (c)/ {
say "0: $0; 1: $1"; # 0: a; 1: c
}</pre>
<p>The <span class="code">$0 </span> and <span class="code">$1 </span> etc. syntax is actually just a shorthand; these captures are canonically available from the match object <span class="code">$/ </span> by using it as a list, so <span class="code">$0 </span> is actually syntax sugar for <span class="code">$/[0] </span> .</p>
<p>Coercing the match object to a list gives an easy way to programmatically access all elements:</p>
<pre class="code">if 'abc' ~~ /(a) b (c)/ {
say $/.list.join: ', ' # a, c
}</pre>
<a name="t26.8.2"$class><h2>26.8.2 Non-capturing grouping</h2></a>
<p>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.</p>
<p>To get only the grouping behavior, you can use square brackets <span class="code">[ ... ] </span> instead.</p>
<pre class="code">if 'abc' ~~ / [a||b] (c) / {
say ~$0; # c
}</pre>
<p>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.</p>
<a name="t26.8.3"$class><h2>26.8.3 Capture numbers</h2></a>
<p>It is stated above that captures are numbered from left to right. While true in principle, this is also overly simplistic.</p>
<p>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.</p>
<p>Alternations reset the capture count:</p>
<pre class="code">/ (x) (y) || (a) (.) (.) /
# $0 $1 $0 $1 $2</pre>
<p>Example:</p>
<pre class="code">if 'abc' ~~ /(x)(y) || (a)(.)(.)/ {
say ~$1; # b
}</pre>
<p>If two (or more) alternations have a different number of captures, the one with the most captures determines the index of the next capture:</p>
<pre class="code">$_ = 'abcd';
if / a [ b (.) || (x) (y) ] (.) / {
# $0 $0 $1 $2
say ~$2; # d
}
</pre>
<p>Captures can be nested, in which case they are numbered per level</p>
<pre class="code">if 'abc' ~~ / ( a (.) (.) ) / {
say "Outer: $0"; # Outer: abc
say "Inner: $0[0] and $0[1]"; # Inner: b and c
}</pre>
<a name="t26.8.4"$class><h2>26.8.4 Named captures</h2></a>
<p>Instead of numbering captures, you can also give them names. The generic -- and slightly verbose -- way of naming captures is like this:</p>
<pre class="code">if 'abc' ~~ / $&lt;myname> = [ \w+ ] / {
say ~$&lt;myname> # abc
}</pre>
<p>The access to the named capture, <span class="code">$&lt;myname> </span> , is a shorthand for indexing the match object as a hash, in other words: <span class="code">$/{ 'myname' } </span> or <span class="code">$/&lt;myname> </span> .</p>
<p>Named captures can also be nested using regular capture group syntax:</p>
<pre class="code">if 'abc-abc-abc' ~~ / $&lt;string>=( [ $&lt;part>=[abc] ]* % '-' ) / {
say ~$&lt;string> # abc-abc-abc
say ~$&lt;string>&lt;part> # [abc, abc, abc]
}</pre>
<p>Coercing the match object to a hash gives you easy programmatic access to all named captures:</p>
<pre class="code">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'
}
}</pre>
<p>There is a more convenient way to get named captures which is discussed in the next section.</p>
<a name="t26.9"$class><h1>26.9 Subrules </h1></a>
<p>Just like you can put pieces of code into subroutines, you can also put pieces of regex into named rules.</p>
<pre class="code">my regex line { \N*\n }
if "abc\ndef" ~~ /&lt;line> def/ {
say "First line: ", $&lt;line>.chomp; # First line: abc
}</pre>
<p>A named regex can be declared with <span class="code">my regex thename { body here } </span> , and called with <span class="code">&lt;thename> </span> . At the same time, calling a named regex installs a named capture with the same name.</p>
<p>If the capture should be of a different name, this can be achieved with the syntax <span class="code">&lt;capturename=regexname> </span> . If no capture at all is desired, a leading dot will suppress it: <span class="code">&lt;.regexname> </span> .</p>
<p>Here is a more complete (yet still fairly limited) code for parsing <span class="code">ini </span> files:</p>
<pre class="code">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</pre>
<p>Named regexes can and should be grouped in <a href="/language/grammars">grammars</a> . A list of predefined subrules is listed in <a href="http://design.perl6.org/S05.html#Predefined_Subrules">S05</a> .</p>
<a name="t26.10"$class><h1>26.10 Adverbs</h1></a>
<p>Adverbs modify how regexes work and give very convenient shortcuts for certain kinds of recurring tasks.</p>
<p>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.</p>
<p>This distinction often blurs, because matching and declaration are often textually close but using the method form of matching makes the distinction clear.</p>
<p> <span class="code">'abc' ~~ /../ </span> is roughly equivalent to <span class="code">'abc'.match(/../) </span> , or even more clearly written in separate lines:</p>
<pre class="code">my $regex = /../; # definition
if 'abc'.match($regex) { # matching
say "'abc' has at least two characters";
}</pre>
<p>Regex adverbs like <span class="code">:i </span> go into the definition line and matching adverbs like <span class="code">:overlap </span> are appended to the match call:</p>
<pre class="code">my $regex = /:i . a/;
for 'baA'.match($regex, :overlap) -> $m {
say ~$m;
}
# output:
# ba
# aA</pre>
<a name="t26.10.1"$class><h2>26.10.1 Regex Adverbs </h2></a>
<p>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.</p>
<p>For example, the <span class="code">:ignorecase </span> ( <span class="code">:i </span> ) adverb tells the compiler to ignore the distinction between upper case, lower case and title case letters.</p>
<p>So <span class="code">'a' ~~ /A/ </span> is false, but <span class="code">'a' ~~ /:i A/ </span> is a successful match.</p>
<p>Regex adverbs can come before or inside a regex declaration and only affect the part of the regex that comes afterwards, lexically.</p>
<p>These two regexes are equivalent:</p>
<pre class="code">my $rx1 = rx:i/a/; # before
my $rx2 = rx/:i a/; # inside</pre>
<p>Whereas these two are not:</p>
<pre class="code">my $rx3 = rx/a :i b/; # matches only the b case insensitively
my $rx4 = rx/:i a b/; # matches completely case insensitively</pre>
<p>Brackets and parentheses limit the scope of an adverb:</p>
<pre class="code">/ (:i a b) c / # matches 'ABc' but not 'ABC'
/ [:i a b] c / # matches 'ABc' but not 'ABC'</pre>
<a name="t26.10.1.1"$class><h3>26.10.1.1 Ratchet </h3></a>
<p>The <span class="code">:ratchet </span> or <span class="code">:r </span> adverb causes the regex engine not to backtrack.</p>
<p>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 <span class="code">'abc' ~~ /\w+ ./ </span> , the <span class="code">\w+ </span> first eats up the whole string, <span class="code">abc </span> but then the <span class="code">. </span> fails. Thus <span class="code">\w+ </span> gives up a character, matching only <span class="code">ab </span> , and the <span class="code">. </span> can successfully match the string <span class="code">c </span> . This process of giving up characters (or in the case of alternations, trying a different branch) is known as backtracking.</p>
<pre class="code">say so 'abc' ~~ / \w+ . /; # True
say so 'abc' ~~ / :r \w+ . /; # False</pre>
<p>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 <span class="code">my regex identifier { \w+ } </span> and <span class="code">my regex keyword { if | else | endif } </span> , you intuitively expect the <span class="code">identifier </span> 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 <span class="code">motif </span> to be parsed as the identifier <span class="code">mot </span> followed by the keyword <span class="code">if </span> ; rather you expect <span class="code">motif </span> to be parsed as one identifier and if the parser expects an <span class="code">if </span> afterwards, rather have it fail than parse the input in a way you don't expect.</p>
<p>Since ratcheting behavior is so often desirable in parsers, there is a shortcut to declaring a ratcheting regex:</p>
<pre class="code">my token thing { .... }
# short for
my regex thing { :r ... }</pre>
<a name="t26.10.1.2"$class><h3>26.10.1.2 Sigspace </h3></a>
<p>The <b> <span class="code">:sigspace </span> </b> or <b> <span class="code">:s </span> </b> adverb makes whitespace significant in a regex.</p>
<pre class="code">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
</pre>
<p> <span class="code">m:s/ photo shop / </span> acts just the same as if one had written <span class="code">m/ photo &lt;.ws> shop &lt;.ws> / </span> . By default, <span class="code">&lt;.ws> </span> makes sure that words are separated, so <span class="code">a b </span> and <span class="code">^&amp; </span> will match <span class="code">&lt;.ws> </span> in the middle, but <span class="code">ab </span> won't.</p>
<p>Where whitespace in a regex turns into <span class="code">&lt;.ws> </span> depends on what comes before the whitespace. In the above example, whitespace in the beginning of a regex doesn't turn into <span class="code">&lt;.ws> </span> , but whitespace after characters does. In general, the rule is that if a term might match something, whitespace after it will turn into <span class="code">&lt;.ws> </span> .</p>
<p>In addition, if whitespace comes after a term, but <i>before</i> a quantifier ( <span class="code">+ </span> , <span class="code">* </span> , or <span class="code">? </span> ), <span class="code">&lt;.ws> </span> will be matched after every match of the term, so <span class="code">foo + </span> becomes <span class="code">[ foo &lt;.ws> ]+ </span> . On the other hand, whitespace <i>after</i> a quantifier acts as normal significant whitespace, e.g., " <span class="code">foo+ </span> " becomes <span class="code">foo+ &lt;.ws> </span> .</p>
<p>In all, this code:</p>
<pre class="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
}
</pre>
<p>Becomes:</p>
<pre class="code">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>
}
</pre>
<p>If a regex is declared with the <span class="code">rule </span> keyword, both the <span class="code">:sigspace </span> and <span class="code">:ratchet </span> adverbs are implied.</p>
<p>Grammars provide an easy way to override what <span class="code">&lt;.ws> </span> matches:</p>
<pre class="code">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</pre>
<p>When parsing file formats where some whitespace (for example vertical whitespace) is significant, it is advisable to override <span class="code">ws </span> .</p>
<a name="t26.10.2"$class><h2>26.10.2 Matching adverbs</h2></a>
<p>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.</p>
<p>They can never appear inside a regex, only on the outside -- either as part of an <span class="code">m/.../ </span> match or as arguments to a match method.</p>
<a name="t26.10.2.1"$class><h3>26.10.2.1 Continue </h3></a>
<p>The <span class="code">:continue </span> or short <span class="code">:c </span> 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 <span class="code">:c </span> overrides that. If no position is specified for <span class="code">:c </span> it will default to <span class="code">0 </span> unless <span class="code">$/ </span> is set, in which case it defaults to <span class="code">$/.to </span> .</p>
<pre class="code">given 'a1xa2' {
say ~m/a./; # a1
say ~m:c(2)/a./; # a2
}</pre>
<a name="t26.10.2.2"$class><h3>26.10.2.2 Exhaustive</h3></a>
<p>To find all possible matches of a regex -- including overlapping ones -- and several ones that start at the same position, use the <span class="code">:exhaustive </span> (short <span class="code">:ex </span> ) adverb.</p>
<pre class="code">given 'abracadabra' {
for m:exhaustive/ a .* a / -> $match {
say ' ' x $match.from, ~$match;
}
}</pre>
<p>The above code produces this output:</p>
<pre class="code">abracadabra
abracada
abraca
abra
acadabra
acada
aca
adabra
ada
abra
</pre>
<a name="t26.10.2.3"$class><h3>26.10.2.3 Global </h3></a>
<p>Instead of searching for just one match and returning a <a href="/type/Match">Match object</a> , search for every non-overlapping match and return them in a <a href="/type/List">List</a> . In order to do this use the <span class="code">:global </span> adverb:</p>
<pre class="code">given 'several words here' {
my @matches = m:global/\w+/;
say @matches.elems; # 3
say ~@matches[2]; # here
}</pre>
<p> <span class="code">:g </span> is shorthand for <span class="code">:global </span> .</p>
<a name="t26.10.2.4"$class><h3>26.10.2.4 Pos </h3></a>
<p>Anchor the match at a specific position in the string:</p>
<pre class="code">given 'abcdef' {
my $match = m:pos(2)/.*/;
say $match.from; # 2
say ~$match; # cdef
}</pre>
<p> <span class="code">:p </span> is shorthand for <span class="code">:pos </span> .</p>
<a name="t26.10.2.5"$class><h3>26.10.2.5 Overlap</h3></a>
<p>To get several matches, including overlapping matches, but only one (the longest) from each starting position, specify the <span class="code">:overlap </span> (short <span class="code">:ov </span> ) adverb:</p>
<pre class="code">given 'abracadabra' {
for m:overlap/ a .* a / -> $match {
say ' ' x $match.from, ~$match;
}
}</pre>
<p>produces</p>
<pre class="code">abracadabra
acadabra
adabra
abra
</pre>
<a name="t26.11"$class><h1>26.11 Look-around assertions</h1></a>
<a name="t26.11.1"$class><h2>26.11.1 Lookahead assertions</h2></a>
<p>To check that a pattern appears before another pattern, one can use a lookahead assertion via the <span class="code">before </span> assertion. This has the form:</p>
<pre class="code">&lt;?before pattern></pre>
<p>Thus, to search for the string <span class="code">foo </span> which is immediately followed by the string <span class="code">bar </span> , one could use the following regexp:</p>
<pre class="code">rx{ foo &lt;?before bar> }</pre>
<p>which one could use like so:</p>
<pre class="code">say "foobar" ~~ rx{ foo &lt;?before bar> }; #-> foo</pre>
<p>However, if you want to search for a pattern which is <b>not</b> immediately followed by some pattern, then you need to use a negative lookahead assertion, this has the form:</p>
<pre class="code">&lt;!before pattern></pre>
<p>Hence all occurrences of <span class="code">foo </span> which <i>is not</i> before <span class="code">bar </span> would be matched by</p>
<pre class="code">rx{ foo &lt;!before bar> }</pre>
<a name="t26.11.2"$class><h2>26.11.2 Lookbehind assertions</h2></a>
<p>To check that a pattern appears before another pattern, one can use a lookbehind assertion via the <span class="code">after </span> assertion. This has the form:</p>
<pre class="code">&lt;?after pattern></pre>
<p>Thus, to search for the string <span class="code">bar </span> which is immediately preceded by the string <span class="code">foo </span> , one could use the following regexp:</p>
<pre class="code">rx{ &lt;?after foo> bar }</pre>
<p>which one could use like so:</p>
<pre class="code">say "foobar" ~~ rx{ &lt;?after foo> bar }; #-> bar</pre>
<p>However, if you want to search for a pattern which is <b>not</b> immediately preceded by some pattern, then you need to use a negative lookbehind assertion, this has the form:</p>
<pre class="code">&lt;!after pattern></pre>
<p>Hence all occurrences of <span class="code">bar </span> which <i>do not</i> have <span class="code">foo </span> before them would be matched by</p>
<pre class="code">rx{ &lt;!after foo> bar }</pre>
<a name="t26.12"$class><h1>26.12 Best practices and gotchas</h1></a>
<p>Regexes and <a href="/language/grammars">grammars</a> are a whole programming paradigm that you have to learn (if you don't already know it very well).</p>
<p>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.</p>
<a name="t26.12.1"$class><h2>26.12.1 Code layout</h2></a>
<p>Without the <span class="code">:sigspace </span> 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.</p>
<p>Compare the very compact</p>
<pre class="code">my regex float { &lt;[+-]>?\d*'.'\d+[e&lt;[+-]>?\d+]? }</pre>
<p>to the more readable</p>
<pre class="code">my regex float {
&lt;[+-]>? # optional sign
\d* # leading digits, optional
'.'
\d+
[ # optional exponent
e &lt;[+-]>? \d+
]?
}</pre>
<p>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.</p>
<p>When you use a list of alternations inside a parenthesis or brackets, align the vertical bars:</p>
<pre class="code">my regex example {
&lt;preamble>
[
|| &lt;choice_1>
|| &lt;choice_2>
|| &lt;choice_3>
]+
&lt;postamble>
}</pre>
<a name="t26.12.2"$class><h2>26.12.2 Keep it small</h2></a>
<p>Regexes come with very little boilerplate, so they are often more compact than regular code. Thus it is important to keep regexes short.</p>
<p>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.</p>
<p>For example you could take the float regex from earlier:</p>
<pre class="code">my regex float {
&lt;[+-]>? # optional sign
\d* # leading digits, optional
'.'
\d+
[ # optional exponent
e &lt;[+-]>? \d+
]?
}</pre>
<p>And decompose it into parts:</p>
<pre class="code">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>?
}</pre>
<p>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.</p>
<pre class="code">my regex float {
&lt;sign>?
[
|| &lt;decimal>? '.' &lt;decimal> &lt;exponent>?
|| &lt;decimal> &lt;exponent>
]
}</pre>
<a name="t26.12.3"$class><h2>26.12.3 What to match</h2></a>
<p>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.</p>
<p>For example in <span class="code">ini </span> files:</p>
<pre class="code">[section]
key=value</pre>
<p>What can be inside the section header? Allowing only a word might be too restrictive, somebody might write <span class="code">[two words] </span> , or use dashes, or so. Instead of asking what's allowed on the inside, it might be worth asking instead: <i>what's not allowed?</i> </p>
<p>Clearly, closing brackets are not allowed, because <span class="code">[a]b] </span> would be rather ambiguous. By the same argument, opening brackets should be forbidden. This leaves us with</p>
<pre class="code">token header { '[' &lt;-[ \[\] ]>+ ']' }</pre>
<p>which is fine if you are only processing one line. But if you're processing a whole file, suddenly the regex parses</p>
<pre class="code">[with a
newline in between]</pre>
<p>which might not be a good idea. A pragmatic compromise would be</p>
<pre class="code">token header { '[' &lt;-[ \[\] \n ]>+ ']' }</pre>
<p>and then, in the post-processing, strip leading and trailing spaces and tabs from the section header.</p>
<a name="t26.12.4"$class><h2>26.12.4 Matching Whitespace</h2></a>
<p>The <span class="code">:sigspace </span> adverb (or using the <span class="code">rule </span> declarator instead of <span class="code">token </span> or <span class="code">regex </span> ) is very handy for implicitly parsing whitespace that can appear in many places.</p>
<p>Going back to the example of parsing <span class="code">ini </span> files, we have</p>
<pre class="code">my regex kvpair { \s* &lt;key=identifier> '=' &lt;value=identifier> \n+ }</pre>
<p>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</p>
<pre class="code">my regex kvpair { \s* &lt;key=identifier> \s* '=' \s* &lt;value=identifier> \n+ }</pre>
<p>That's growing unwieldy pretty quickly. So instead one can write</p>
<pre class="code">my rule kvpair { &lt;key=identifier> '=' &lt;value=identifier> \n+ }</pre>
<p>But wait! The implicit whitespace matching after the value uses up all whitespace, including newline characters, so the <span class="code">\n+ </span> doesn't have anything left to match (and <span class="code">rule </span> also disables backtracking, so no luck here).</p>
<p>Therefore it is important to redefine your definition of implicit whitespace to whitespace that is not significant in the input format.</p>
<p>This works by redefining the token <span class="code">ws </span> , however it only works in <a href="/language/grammars">grammars</a> :</p>
<pre class="code">grammar IniFormat {
token ws { &lt;!ww> \h* }
rule header { '[' (\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);</pre>
<p>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</p>
<pre class="code">token ws { &lt;!ww> \h* }</pre>
<p>which gets called for implicit whitespace parsing. It matches when it is not between two word characters ( <span class="code">&lt;!ww> </span> , 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.</p>
<p>Still there is some whitespace-related trouble lurking. The regex <span class="code">\n+ </span> won't match a string like <span class="code">"\n \n" </span> , because there is a blank between the two newlines. To allow such input strings, replace <span class="code">\n+ </span> by <span class="code">\n\s* </span> .</p>
<a name="t27"><h1 class="title">27 Sets, Bags, and Mixes</h1></a> <p class="subtitle">Unordered collections of unique and weighted objects in Perl 6</p></a> <p>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 <i>unordered</i> collection types <a href="Set"> <b> <span class="code">Set </span> </b> </a> , <a href="SetHash"> <b> <span class="code">SetHash </span> </b> </a> , <a href="Bag"> <b> <span class="code">Bag </span> </b> </a> , <a href="BagHash"> <b> <span class="code">BagHash </span> </b> </a> , <a href="Mix"> <b> <span class="code">Mix </span> </b> </a> , and <a href="MixHash"> <b> <span class="code">MixHash </span> </b> </a> . Being unordered, these containers can be more efficient than <a href="List"> <b> <span class="code">Lists </span> </b> </a> for looking up elements or dealing with repeated items.</p>
<p>If you want to get the contained objects (elements) without duplicates and you only care <i>whether</i> an element is in the collection or not, you can use a <a href="Set"> <b> <span class="code">Set </span> </b> </a> or <a href="SetHash"> <b> <span class="code">SetHash </span> </b> </a> . (If you want to get rid of duplicates but still preserve order, take a look at the <a href="unique"> <span class="code">unique </span> </a> routine for <a href="List"> <b> <span class="code">Lists </span> </b> </a> .)</p>
=defn Set or SetHash
Collection of distinct objects
<p>If you want to keep track of the number of times each object appeared, you can use a <a href="Bag"> <b> <span class="code">Bag </span> </b> </a> or <a href="BagHash"> <b> <span class="code">BagHash </span> </b> </a> . 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 <a href="Mix"> <b> <span class="code">Mix </span> </b> </a> and <a href="MixHash"> <b> <span class="code">MixHash </span> </b> </a> are similar, but they also allow fractional weights.</p>
=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.
<p> <a href="Set"> <b> <span class="code">Set </span> </b> </a> , <a href="Bag"> <b> <span class="code">Bag </span> </b> </a> , and <a href="Mix"> <b> <span class="code">Mix </span> </b> </a> are <i>immutable</i> types. Use the mutable variants <a href="SetHash"> <b> <span class="code">SetHash </span> </b> </a> , <a href="BagHash"> <b> <span class="code">BagHash </span> </b> </a> , and <a href="MixHash"> <b> <span class="code">MixHash </span> </b> </a> if you want to add or remove elements after the container has been constructed.</p>
<p>The six collection classes <span class="code">Set </span> , <span class="code">SetHash </span> , <span class="code">Bag </span> , <span class="code">BagHash </span> , <span class="code">Mix </span> , <span class="code">MixHash </span> , all share similar semantics.</p>
<p>For one thing, as far as they are concerned, identical objects refer to the same element -- where identity is determined using the <a href="">WHICH</a> methods (i.e. the same way that the <a href="">===</a> operator checks identity). For value types like <span class="code">Str </span> , this means having the same value; for reference types like <span class="code">Array </span> , it means referring to the same object instance.</p>
<p>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':</p>
<table>
<tr><th>type of $a</th> <th>value of $a{$b} if $b is an element</th> <th>value of $a{$b} if $b is not an element</th></tr>
<tr><td>Set / SetHash</td> <td>True</td> <td>False</td></tr>
<tr><td>Bag / BagHash</td> <td>a positive integer</td> <td>0</td></tr>
<tr><td>Mix / MixHash</td> <td>a non-zero real number</td> <td>0</td></tr>
</table> <a name="t27.1"$class><h1>27.1 Set/Bag Operators</h1></a>
TODO: Update this after ab5tract's set/bag/mix operator redesign.
<p>There are many infixes devoted to preforming common operations on <a href="Set"> <span class="code">Set </span> s</a> , such as unions and set differences. Other operations include boolean checks, like whether an object is an element of a <span class="code">Set </span> , or whether one <span class="code">Set </span> is a subset of another <span class="code">Set </span> .</p>
<p>These infixes can be written using the UTF-8 character that represents the function (like <a href="∈"> <span class="code">∈ </span> </a> , or <a href="∪"> <span class="code">∪ </span> </a> ), or they can be written with an equivalent ASCII version (like <a href="(elem)"> <span class="code">(elem) </span> </a> or <a href="(|)"> <span class="code">(|) </span> </a> ).</p>
<p>Most of the time, explicitly using <span class="code">Set </span> objects with these infixes is unnecessary. All of the infix operators will work on any objects of type <a href="Any"> <span class="code">Any </span> </a> for its arguments (e.g., <a href="List"> <span class="code">List </span> s</a> , <a href="Array"> <span class="code">Array </span> s</a> , <a href="Mix"> <span class="code">Mix </span> es</a> , etc.) and coerce them to <span class="code">Set </span> s where needed.</p>
<p>In some cases, if the type of an argument is a <a href="">Bag</a> , the infix operator will behave in a different but analogous way to the way it would behave with only <span class="code">Set </span> arguments.</p>
<a name="t27.1.1"$class><h2>27.1.1 Operators that return <span class="code">Bool </span> </h2></a>
<a name="t27.1.1.1"$class><h3>27.1.1.1 infix (elem)</h3></a>
<pre class="code">multi sub infix:&lt;(elem)>($a, Any $b --> Bool)
multi sub infix:&lt;(elem)>($a, Set $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> is an <b>element</b> of <span class="code">$b </span> .</p>
<a name="t27.1.1.1.1"$class><h4>27.1.1.1.1 infix ∈</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2208">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(elem)</a> .</p>
<a name="t27.1.1.1.2"$class><h4>27.1.1.1.2 infix ∉</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2209">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(elem) </span> , i.e., returns <span class="code">True </span> if <span class="code">$a </span> is not an element of <span class="code">$b </span> .</p>
<a name="t27.1.1.2"$class><h3>27.1.1.2 infix (cont)</h3></a>
<pre class="code">multi sub infix:&lt;(cont)>(Any $a, $b --> Bool)
multi sub infix:&lt;(cont)>(Set $a, $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> <b>contains</b> <span class="code">$b </span> as an element.</p>
<a name="t27.1.1.2.1"$class><h4>27.1.1.2.1 infix ∋</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x220B">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(cont)</a> .</p>
<a name="t27.1.1.2.2"$class><h4>27.1.1.2.2 infix ∌</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x220C">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(cont) </span> , i.e., returns <span class="code">True </span> if <span class="code">$a </span> does not contain <span class="code">$b </span> .</p>
<a name="t27.1.1.3"$class><h3>27.1.1.3 infix (&lt;=)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(&lt;=)>>(Any $a, Any $b --> Bool)
multi sub infix:&lt;&lt;(&lt;=)>>(Setty $a, Setty $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> is a <b>subset</b> or is equal to <span class="code">$b </span> , i.e., if all the elements of <span class="code">$a </span> are elements of <span class="code">$b </span> and <span class="code">$a </span> is a smaller or equal sized set than <span class="code">$b </span> .</p>
<a name="t27.1.1.3.1"$class><h4>27.1.1.3.1 infix ⊆</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2286">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(&lt;=)</a> .</p>
<a name="t27.1.1.3.2"$class><h4>27.1.1.3.2 infix ⊈</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2288">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(&lt;=) </span> .</p>
<a name="t27.1.1.4"$class><h3>27.1.1.4 infix (&lt;)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(&lt;)>>(Any $a, Any $b --> Bool)
multi sub infix:&lt;&lt;(&lt;)>>(Setty $a, Setty $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> is a <b>strict subset</b> of <span class="code">$b </span> , i.e., that all the elements of <span class="code">$a </span> are elements of <span class="code">$b </span> but <span class="code">$a </span> is a smaller set than <span class="code">$b </span> .</p>
<a name="t27.1.1.4.1"$class><h4>27.1.1.4.1 infix ⊂</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2282">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(&lt;)</a> .</p>
<a name="t27.1.1.4.2"$class><h4>27.1.1.4.2 infix ⊄</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2284">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(&lt;) </span> .</p>
<a name="t27.1.1.5"$class><h3>27.1.1.5 infix (>=)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(>=)>>(Any $a, Any $b --> Bool)
multi sub infix:&lt;&lt;(>=)>>(Setty $a, Setty $b --> Bool)</pre>
<p>Like <a href="">(&lt;=)</a> with reversed arguments. Returns <span class="code">True </span> if <span class="code">$a </span> is a <b>superset</b> of or equal to <span class="code">$b </span> .</p>
<a name="t27.1.1.5.1"$class><h4>27.1.1.5.1 infix ⊇</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2287">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(>=)</a> .</p>
<a name="t27.1.1.5.2"$class><h4>27.1.1.5.2 infix ⊉</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2289">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(>=) </span> .</p>
<a name="t27.1.1.6"$class><h3>27.1.1.6 infix (>)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(>)>>(Any $a, Any $b --> Bool)
multi sub infix:&lt;&lt;(>)>>(Setty $a, Setty $b --> Bool)</pre>
<p>Like <a href="">(&lt;)</a> with reversed arguments. Returns <span class="code">True </span> if <span class="code">$a </span> is a <b>strict superset</b> of <span class="code">$b </span> .</p>
<a name="t27.1.1.6.1"$class><h4>27.1.1.6.1 infix ⊃</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2283">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(>)</a> .</p>
<a name="t27.1.1.6.2"$class><h4>27.1.1.6.2 infix ⊅</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2285">>($a, $b --> Bool)</pre>
<p>Equivalent to <span class="code">!(>) </span> .</p>
<a name="t27.1.1.7"$class><h3>27.1.1.7 infix (&lt;+)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(&lt;+)>>(Any $a, Any $b --> Bool)
multi sub infix:&lt;&lt;(&lt;+)>>(Baggy $a, Baggy $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> is a Baggy <b>subset</b> of <span class="code">$b </span> , i.e., if all the elements of <span class="code">$a </span> are in <span class="code">$b </span> and each element of <span class="code">$b </span> is weighed at least as heavily as the element is in <span class="code">$a </span> .</p>
<a name="t27.1.1.7.1"$class><h4>27.1.1.7.1 infix ≼</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x227C">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(&lt;+)</a> .</p>
<a name="t27.1.1.8"$class><h3>27.1.1.8 infix (>+)</h3></a>
<pre class="code">multi sub infix:&lt;&lt;(>+)>>(Baggy $a, Baggy $b --> Bool)
multi sub infix:&lt;&lt;(>+)>>(Any $a, Any $b --> Bool)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$a </span> is a Baggy <b>superset</b> of <span class="code">$b </span> , i.e., if all the elements of <span class="code">$b </span> are in <span class="code">$a </span> and no element of <span class="code">$b </span> is weighted heavier than that element is in <span class="code">$a </span> .</p>
<a name="t27.1.1.8.1"$class><h4>27.1.1.8.1 infix ≽</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x227D">>($a, $b --> Bool)</pre>
<p>Equivalent to <a href="">(+>)</a> .</p>
<a name="t27.1.2"$class><h2>27.1.2 Operators that return <span class="code">Set </span> or <span class="code">Bag </span> </h2></a>
<a name="t27.1.2.1"$class><h3>27.1.2.1 infix (|)</h3></a>
<pre class="code">only sub infix:&lt;(|)>(**@p)</pre>
<p>Returns the <b>union</b> of all its arguments. Generally, this creates a new <span class="code">Set </span> that contains all the elements its arguments contain.</p>
<pre class="code">&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></pre>
<p>If any of its arguments are <span class="code">Baggy </span> , it creates a new <span class="code">Bag </span> that contains all the elements of the arguments, each weighed by the highest weight that appeared for that element.</p>
<pre class="code">bag(&lt;a a b c a>) (|) bag(&lt;a a b c c>) === bag(&lt;a a a b c c>)</pre>
<a name="t27.1.2.1.1"$class><h4>27.1.2.1.1 infix ∪</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x222A">>(|p)</pre>
<p>Equivalent to <a href="">(|)</a> .</p>
<a name="t27.1.2.2"$class><h3>27.1.2.2 infix (&amp;)</h3></a>
<pre class="code">only sub infix:&lt;(&amp;)>(**@p)</pre>
<p>Returns the <b>intersection</b> of all of its arguments. Generally, this creates a new <span class="code">Set </span> that contains only the elements common to all of the arguments.</p>
<pre class="code">&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></pre>
<p>If any of the arguments are <span class="code">Baggy </span> , the result is a new <span class="code">Bag </span> containing the common elements, each weighted by the largest <i>common</i> weight (which is the minimum of the weights of that element over all arguments).</p>
<pre class="code">bag(&lt;a a b c a>) (&amp;) bag(&lt;a a b c c>) === bag(&lt;a a b c>)</pre>
<a name="t27.1.2.2.1"$class><h4>27.1.2.2.1 infix ∩</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2229">>(|p)</pre>
<p>Equivalent to <a href="">(&amp;)</a> .</p>
<a name="t27.1.2.3"$class><h3>27.1.2.3 infix (-)</h3></a>
<pre class="code">only sub infix:&lt;(-)>(**@p)</pre>
<p>Returns the <b>set difference</b> of all its arguments. Generally, this returns the <span class="code">Set </span> 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.</p>
<p>If the first argument is <span class="code">Baggy </span> , this returns a <span class="code">Bag </span> that contains each element of the first argument with its weight subtracted by the weight of that element in each of the other arguments.</p>
<pre class="code">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>)</pre>
<a name="t27.1.2.3.1"$class><h4>27.1.2.3.1 infix ∖</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2216">>(|p)</pre>
<p>Equivalent to <a href="">(-)</a> .</p>
<a name="t27.1.2.4"$class><h3>27.1.2.4 infix (^)</h3></a>
<pre class="code">multi sub infix:&lt;(^)>(Any $a, Any $b --> Setty)
multi sub infix:&lt;(^)>(Set $a, Set $b --> Setty)</pre>
<p>Returns the <b>symmetric set difference</b> of all its arguments, i.e., a <span class="code">Set </span> made up of all the elements that <span class="code">$a </span> has but <span class="code">$b </span> doesn't and all the elements <span class="code">$b </span> has but <span class="code">$a </span> doesn't. Equivalent to <span class="code">($a ∖ $b) ∪ ($b ∖ $a) </span> .</p>
<a name="t27.1.2.4.1"$class><h4>27.1.2.4.1 infix ⊖</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x2296">>($a, $b --> Setty)</pre>
<p>Equivalent to <a href="">(^)</a> .</p>
<a name="t27.1.2.5"$class><h3>27.1.2.5 infix (.)</h3></a>
<pre class="code">only sub infix:&lt;(.)>(**@p)</pre>
<p>Returns the Baggy <b>multiplication</b> of its arguments, i.e., a <span class="code">Bag </span> that contains each element of the arguments with the weights of the element across the arguments multiplied together to get the new weight.</p>
<pre class="code">&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>)</pre>
<a name="t27.1.2.5.1"$class><h4>27.1.2.5.1 infix ⊍</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x228D">>(|p)</pre>
<p>Equivalent to <a href="">(.)</a> .</p>
<a name="t27.1.2.6"$class><h3>27.1.2.6 infix (+)</h3></a>
<pre class="code">only sub infix:&lt;(+)>(**@p)</pre>
<p>Returns the Baggy <b>addition</b> of its arguments, i.e., a <span class="code">Bag </span> that contains each element of the arguments with the weights of the element across the arguments added together to get the new weight.</p>
<pre class="code">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>)</pre>
<a name="t27.1.2.6.1"$class><h4>27.1.2.6.1 infix ⊎</h4></a>
<pre class="code">only sub infix:&lt;&lt;"\x228E">>(|p)</pre>
<p>Equivalent to <a href="">(+)</a> .</p>
<a name="t28"><h1 class="title">28 Subscripts</h1></a> <p class="subtitle">Accessing data structure elements by index or key</p></a> <p>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 <i>v</i> would be referred to as <i>v₁, v₂, v₃</i> , this concept is called "subscripting" (or "indexing") in Perl 6.</p>
<a name="t28.1"$class><h1>28.1 Basics</h1></a>
<p>Perl 6 provides two universal subscripting interfaces:</p>
<table>
<tr><th></th> <th>elements are identified by</th> <th>interface name</th> <th>supported by</th></tr>
<tr><td>[ ]</td> <td>zero-based indices</td> <td>Positional</td> <td>Array, List, Buf, Match, ...</td></tr>
<tr><td>{ }</td> <td>string or object keys</td> <td>Associative</td> <td>Hash, Bag, Mix, Match, ...</td></tr>
</table> <ul><li><p> <b>Positional</b> subscripting (via <a href="/language/operators#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> ) addresses elements of an ordered collection by their position. Index 0 refers to the first element, index 1 to the second, and so on:</p>
<pre class="code">my @chores = "buy groceries", "feed dog", "wash car";
say @chores[0]; #-> buy groceries
say @chores[1]; #-> feed dog
say @chores[2]; #-> wash car</pre>
</li></ul> <ul><li><p> <b>Associative</b> subscripting (via <a href="/language/operators#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> ), 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 <a href="">Hash</a> uses string keys, whereas a <a href="">Mix</a> allows arbitrary objects as keys, etc.:</p>
<pre class="code">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</pre>
<p>For passing single-word string keys to <span class="code">{ } </span> , you can also use the <a href="/language/quoting#Word_quoting:_qw">angle-bracketed word quoting constructs</a> as if they were postcircumfix operators:</p>
<pre class="code">say %grade&lt;Zoe>; #-> C
say %grade&lt;Ben>; #-> B+</pre>
<p>This is really just syntactic sugar that gets turned into the corresponding <span class="code">{ } </span> form at compile-time:</p>
<pre class="code">%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>> }</pre>
<p>You may have noted above that we avoided having to quote <span class="code">Zoe </span> by using the <span class="code">= </span> > operator, but that same operator did not just put invisible quotes around <span class="code">Date.new(2015, 4, 5) </span> , and we were able to find the same element using <span class="code">$stats{ Date.new(2015, 4, 4) + 1 } </span> . This is because <span class="code">= </span> > only puts invisible quotes around single words, and by "word" we mean an identifier/name. The <span class="code">= </span> > operator is there to prevent us from accidentally calling functions or using constants with that name.</p>
<p>Hash subscripts do not do the same thing as <span class="code">= </span> >. The default <span class="code">Hash </span> 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 <span class="code">Hash </span> , subscripts coerce keys into strings, as long as those keys produce something <span class="code">Cool </span> . You can use <span class="code">.perl </span> on a collection to be sure whether the keys are strings or objects:</p>
<pre class="code">( 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 }</pre>
<p>While the invisible quotes around single names is built into <span class="code">= </span> >, string conversion is not built into the curly braces: it is a behavior of the default <span class="code">Hash </span> . Not all types of hashes or collections do so:</p>
<pre class="code">my %h := MixHash.new;
$h{pi} = 1; %h.perl.say; #-> (3.14159265358979e0=>1).MixHash</pre>
<p>(Any name that <span class="code">= </span> > would convert to a string can also be used to build a pair using "adverbial notation" and will appear that way when viewed through <span class="code">.perl </span> , which is why we see <span class="code">:pi(1) </span> above.)</p>
</li></ul> <p>Subscripts can be applied to any expression that returns a subscriptable object, not just to variables:</p>
<pre class="code">say "__Hello__".match(/__(.*)__/)[0]; #-> 「Hello」
say "__Hello__".match(/__(.*)__/).[0]; # same, in method notation</pre>
<p>Positional and associative subscripting are not mutually exclusive - for example, <a href="">Match</a> objects support both (each accessing a different set of data). Also, to make list processing more convenient, class <a href="">Any</a> 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.)</p>
<pre class="code">say 42[0]; #-> 42
say 42&lt;foo>; # ERROR: postcircumfix { } not defined for type Int</pre>
<a name="t28.2"$class><h1>28.2 Nonexistent elements</h1></a>
<p>What happens when a <i>nonexistent</i> element is addressed by a subscript, is up to the collection type in question. Standard <a href="">Array</a> and <a href="">Hash</a> collections return the type object of their <a href="of">value type constraint</a> (which, by default, is <a href="">Any</a> ):</p>
<pre class="code">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)</pre>
<p>However, other types of collections may react differently to subscripts that address nonexistent elements:</p>
<pre class="code">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</pre>
<p>To silently skip nonexistent elements in a subscripting operation, see <a href="">#Truncating slices</a> and the <a href="">#:v</a> adverb.</p>
<a name="t28.3"$class><h1>28.3 From the end</h1></a>
<p>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: <span class="code">*-1 </span> refers to the last element, <span class="code">*-2 </span> to the second-to-last element, and so on.</p>
<pre class="code">my @alphabet = 'A' .. 'Z';
say @alphabet[*-1]; #-> Z
say @alphabet[*-2]; #-> Y
say @alphabet[*-3]; #-> X</pre>
<p>Note: The asterisk is important. Passing a bare negative integer (e.g. <span class="code">@alphabet[-1] </span> ) like you would do in many other programming languages, throws an error in Perl 6.</p>
<p>What actually happens here, is that an expression like <span class="code">*-1 </span> declares a code object via <a href="">Whatever</a> -currying - and the <span class="code">[ ] </span> 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, <span class="code">@alphabet[*-1] </span> becomes <span class="code">@alphabet[@alphabet.elems - 1] </span> .</p>
<p>This means that you can use arbitrary expressions which depend on the size of the collection:</p>
<pre class="code">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</pre>
<a name="t28.4"$class><h1>28.4 Slices</h1></a>
<p>When multiple elements of a collection need to be accessed, there's a shortcut to doing multiple separate subscripting operations: Simply specify a <i>list</i> of indices/keys in the subscript, to get back a <i>list</i> of elements - also called a "slice" - in the same order.</p>
<p>For positional slices, you can mix normal indices with <a href="#From the end">from-the-end</a> ones:</p>
<pre class="code">my @alphabet = 'a' .. 'z';
dd @alphabet[15, 4, *-9, 11]; #-> ("p", "e", "r", "l")</pre>
<p>For associative slices, the angle-brackets form often comes in handy:</p>
<pre class="code">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")</pre>
<p>Be aware that slices are controlled by the <i>type</i> of what is passed to ( <a href="#Multiple dimensions">one dimension of</a> ) the subscript, not its length:</p>
<table>
<tr><th>subscript</th> <th>result</th></tr>
<tr><td>any Iterable not mentioned below</td> <td>normal slice</td></tr>
<tr><td>a Range</td> <td>L&lt;truncates|#Truncating slices> in [ ]</td></tr>
<tr><td>a lazy Iterable</td> <td>L&lt;truncates|#Truncating slices> in [ ]</td></tr>
<tr><td>* (Whatever-star)</td> <td>full slice (as if all keys/indices were specified)</td></tr>
<tr><td>any other object</td> <td>single-element access rather than a slice</td></tr>
<tr><td>empty</td> <td>L&lt;Zen slice|#Zen slices></td></tr>
</table> <p>So even a one-element list returns a slice, whereas a bare scalar value doesn't:</p>
<pre class="code">dd @alphabet[2,]; #-> ("c",)
dd @alphabet[2]; #-> "c"</pre>
<p>(The angle-bracket form for associative subscripts works out because <a href="/language/quoting#Word_quoting:_qw">word quoting</a> conveniently returns a <a href="">Str</a> in case of a single word, but a <a href="">List</a> in case of multiple words.)</p>
<p>In fact, the list structure of ( <a href="#Multiple
dimensions">the current dimension of</a> ) the subscript is preserved across the slice operation (but the kind of Iterable is not -- the result is always just lists.)</p>
<pre class="code">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")</pre>
<a name="t28.4.1"$class><h2>28.4.1 Truncating slices</h2></a>
<p>Normally, referring to nonexistent elements in a slice subscript causes the output list to contain undefined values (or <a href="#Nonexistent elements">whatever else</a> the collection in question chooses to return for nonexistent elements). However if the outer object passed to ( <a href="#Multiple dimensions">one dimension of</a> ) of a positional subscript is a <a href="">Range</a> , it will be automatically truncated to the actual size of the collection:</p>
<pre class="code">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")</pre>
<p> <a href="#From the end">From-the-end</a> indices are allowed as range end-points.</p>
<pre class="code">say @array[*-3 .. *]; # select the last three elements</pre>
<p>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.</p>
<pre class="code">dd @letters[0,2,4...*]; # Every other element of the array.</pre>
<p>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:</p>
<pre class="code">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)</pre>
<p>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:</p>
<pre class="code">@letters[0 xx *];</pre>
<p>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):</p>
<pre class="code">my $a = (0 xx *).map({ @letters[$_] }); # "a","a","a" ... forever</pre>
<p>If you <i>don't</i> want to specify your slice as a range/sequence but still want to silently skip nonexistent elements, you can use the <a href="">#:v</a> adverb.</p>
<a name="t28.4.2"$class><h2>28.4.2 Zen slices</h2></a>
<p>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".</p>
<p>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):</p>
<pre class="code">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{()}; #-> ()</pre>
<p>It is usually used to <a href="/language/quoting#Interpolation:_qq">interpolate</a> entire arrays / hashes into strings:</p>
<pre class="code">my @words = "cruel", "world";
say "Hello, @words[]!" #-> Hello, cruel world!</pre>
<a name="t28.5"$class><h1>28.5 Multiple dimensions</h1></a>
<p>...</p>
TODO: Explain multi-dim subscripts. It's probably best to wait for
jnthn's ongoing refactor to finish before writing this section.
<a name="t28.6"$class><h1>28.6 Modifying elements</h1></a>
TODO
<a name="t28.7"$class><h1>28.7 Autovivification</h1></a>
<p>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:</p>
<pre class="code">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."]}</pre>
<p> <span class="code">$beatles </span> started out undefined, but became a <a href="">Hash</a> object because it was subscripted with <span class="code">{ } </span> in the assignment. Similarly, <span class="code">$beatles{"White Album"} </span> became an <a href="">Array</a> object due to being subscripted with <span class="code">[ ] </span> in the assignment.</p>
<p>Note that the subscripting itself does not cause autovivification: It only happens when the result of the subscripting chain is <i>assigned</i> to (or otherwise mutated).</p>
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.
<a name="t28.8"$class><h1>28.8 Binding</h1></a>
<p>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.</p>
<p>The built-in <a href="">Array</a> and <a href="">Hash</a> types support this in order to allow building complex linked data structures:</p>
<pre class="code">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</pre>
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.
<p>See <a href="">#method BIND-POS</a> and <a href="">#method BIND-KEY</a> for the underlying mechanism.</p>
<a name="t28.9"$class><h1>28.9 Adverbs</h1></a>
<p>The return value and possible side-effect of a subscripting operation can be controlled using adverbs.</p>
<p>Beware of the relatively loose precedence of operator adverbs, which may require you to add parens in compound expressions:</p>
<pre class="code">if $foo || %hash&lt;key>:exists { ... } # WRONG, tries to adverb the || op
if $foo || (%hash&lt;key>:exists) { ... } # correct</pre>
<p>The supported adverbs are:</p>
<a name="t28.9.1"$class><h2>28.9.1 :exists </h2></a>
<p>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:</p>
<pre class="code">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)</pre>
<p>May also be negated to test for non-existence:</p>
<pre class="code">dd %fruit&lt;apple banana>:!exists; #-> (False, True)</pre>
<p>To check if <i>all</i> elements of a slice exist, use an <a href="">all</a> junction:</p>
<pre class="code">if all %fruit&lt;apple orange banana>:exists { ... }</pre>
<p> <span class="code">:exists </span> can be combined with the <a href="">#:delete</a> and <a href="">#:p</a> / <a href="">#:kv</a> adverbs - in which case the behavior is determined by those adverbs, except that any returned element <i>value</i> is replaced with the corresponding <a href="">Bool</a> indicating element <i>existence</i> .</p>
<p>See <a href="">#method EXISTS-POS</a> and <a href="">#method EXISTS-KEY</a> for the underlying mechanism.</p>
<a name="t28.9.2"$class><h2>28.9.2 :delete </h2></a>
<p>Delete the element from the collection, in addition to returning its value.</p>
<pre class="code">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;></pre>
<p>With the negated form of the adverb, the element is not actually deleted. This means you can pass a flag to make it conditional:</p>
<pre class="code">dd %fruit&lt;apple> :delete($flag); # deletes the element only if $flag is
# true, but always returns the value.</pre>
<p>Can be combined with the <a href="">#:exists</a> and <a href="">#:p</a> / <a href="">#:kv</a> / <a href="">#:k</a> / <a href="">#:v</a> adverbs - in which case the return value will be determined by those adverbs, but the element will at the same time also be deleted.</p>
<p>See <a href="">#method DELETE-POS</a> and <a href="">#method DELETE-KEY</a> for the underlying mechanism.</p>
<a name="t28.9.3"$class><h2>28.9.3 :p </h2></a>
<p>Return both the index/key and the value of the element, in the form of a <a href="">Pair</a> , and silently skip nonexistent elements:</p>
<pre class="code">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)</pre>
<p>If you <i>don't</i> want to skip nonexistent elements, use the negated form:</p>
<pre class="code">dd %month&lt;Jan Foo Mar>:!p; #-> ("Jan" => 1, "Foo" => Any, "Mar" => 3)</pre>
<p>Can be combined with the <a href="">#:exists</a> and <a href="">#:delete</a> adverbs.</p>
<p>See also the <a href="">pairs</a> routine.</p>
<a name="t28.9.4"$class><h2>28.9.4 :kv </h2></a>
<p>Return both the index/key and the value of the element, in the form of a <a href="">List</a> , and silently skip nonexistent elements. When used on a <a href="#Slicing">slice</a> , the return value is a single flat list of interleaved keys and values:</p>
<pre class="code">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)</pre>
<p>If you <i>don't</i> want to skip nonexistent elements, use the negated form:</p>
<pre class="code">dd %month&lt;Jan Foo Mar>:!kv; #-> ("Jan", 1, "Foo", Any, "Mar", 3)</pre>
<p>This adverb is commonly used to iterate over slices:</p>
<pre class="code">for %month&lt;Feb Mar>:kv -> $month, $i {
say "$month had {Date.new(2015, $i, 1).days-in-month} days in 2015"
}</pre>
<p>Can be combined with the <a href="">#:exists</a> and <a href="">#:delete</a> adverbs.</p>
<p>See also the <a href="">kv</a> routine.</p>
<a name="t28.9.5"$class><h2>28.9.5 :k </h2></a>
<p>Return only the index/key of the element, rather than its value, and silently skip nonexistent elements:</p>
<pre class="code">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")</pre>
<p>If you <i>don't</i> want to skip nonexistent elements, use the negated form:</p>
<pre class="code">dd %month&lt;Jan Foo Mar>:!k; #-> ("Jan", "Foo", "Mar")</pre>
<p>See also the <a href="">keys</a> routine.</p>
<a name="t28.9.6"$class><h2>28.9.6 :v </h2></a>
<p>Return the bare value of the element (rather than potentially returning a mutable value container), and silently skip nonexistent elements:</p>
<pre class="code">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)</pre>
<p>If you <i>don't</i> want to skip nonexistent elements, use the negated form:</p>
<pre class="code">dd %month&lt;Jan Foo Mar>:!v; #-> (1, Any, 3)</pre>
<p>See also the <a href="">values</a> routine.</p>
<a name="t28.10"$class><h1>28.10 Custom types</h1></a>
<p>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.</p>
<p>You don't have to manually overload the <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> and <a href="/routine/{ }#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> 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:</p>
<table>
<tr><th>when you write:</th> <th>this gets called behind the scenes:</th></tr>
<tr><td>%foo&lt;aa></td> <td>%foo.AT-KEY("aa")</td></tr>
<tr><td>%foo&lt;aa>:delete</td> <td>%foo.DELETE-KEY("aa")</td></tr>
<tr><td>@foo[3,4,5]</td> <td>@foo.AT-POS(3), @foo.AT-POS(4), @foo.AT-POS(5)</td></tr>
<tr><td>@foo[*-1]</td> <td>@foo.AT-POS(@foo.elems - 1)</td></tr>
</table> <p>So in order to make subscripting work, you only have to implement or delegate those low-level methods ( <a href="#Methods_to_implement_for_positional_subscripting">detailed below</a> ) for your custom type.</p>
<p>If you do, you should also let your type compose the <a href="/type/Positional"> <span class="code">Positional </span> </a> or <a href="/type/Associative"> <span class="code">Associative </span> </a> 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.</p>
<a name="t28.10.1"$class><h2>28.10.1 Custom type example</h2></a>
TODO: Maybe factor this out into a tutorial page
<p>Imagine a HTTP::Header type which, despite being a custom class with special behavior, can be indexed like a hash:</p>
<pre class="code">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</pre>
<p>The simplest way to implement this class, would be to give it an attribute of type <a href="">Hash</a> , 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):</p>
<pre class="code">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] }
}</pre>
<p>However, HTTP header field names are supposed to be case-insensitive (and preferred in camel-case). We can accommodate this by taking the <span class="code">*-KEY </span> and <span class="code">push </span> methods out of the <span class="code">handles </span> list, and implementing them separately like this:</p>
<pre class="code">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) }</pre>
<p>Note that subscripting <span class="code">%!fields </span> returns an appropriate rw container, which our <span class="code">AT-KEY </span> can simply pass on.</p>
<p>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 <span class="code">StrOrArrayOfStr </span> type constraint on <span class="code">%!fields </span> , and replace our <span class="code">AT-KEY </span> implementation with one that returns a custom <span class="code">Proxy </span> container which takes care of sanitising values on assignment:</p>
<pre class="code">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
}
}
);
}</pre>
<p>Note that declaring the method as <span class="code">multi </span> and restricting it to <span class="code">:D </span> (defined invocants) makes sure that the undefined case is passed through to the default implementation provided by <span class="code">Any </span> (which is involved in auto-vivification).</p>
<a name="t28.10.2"$class><h2>28.10.2 Methods to implement for positional subscripting</h2></a>
<p>In order to make index-based subscripting via <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> work for your custom type, you should implement at least <span class="code">elems </span> , <span class="code">AT-POS </span> and <span class="code">EXISTS-POS </span> - and optionally others as detailed below.</p>
<a name="t28.10.2.1"$class><h3>28.10.2.1 method elems</h3></a>
<pre class="code">multi method elems (::?CLASS:D:)</pre>
<p>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 <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> when indexing elements from the end, as in <span class="code">@foo[*-1] </span> .</p>
<p>If not implemented, your type will inherit the default implementation from <span class="code">Any </span> that always returns <span class="code">1 </span> 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 <a href="">fail</a> s or <a href="">die</a> s, to avoid silently doing the wrong thing.</p>
<a name="t28.10.2.2"$class><h3>28.10.2.2 method AT-POS</h3></a>
When modifying this section, please also adapt the AT-KEY
section accordingly as they are very similar.
<pre class="code">multi method AT-POS (::?CLASS:D: $index)</pre>
TODO: Cover the case of multi-dim indices (also for all the other
methods below), after jnthn's ongoing refactor is finished.
<p>Expected to return the element at position <span class="code">$index </span> . This is what <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> normally calls.</p>
<p>If you want an element to be mutable (like they are for the built-in <a href="">Array</a> 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 <span class="code">return-rw </span> or the <span class="code">is rw </span> routine trait to make that work; see the <a href="/language/subscripting#Custom_type_example">example</a> .)</p>
<a name="t28.10.2.3"$class><h3>28.10.2.3 method EXISTS-POS</h3></a>
When modifying this section, please also adapt the EXISTS-KEY
section accordingly as they are very similar.
<pre class="code">multi method EXISTS-POS (::?CLASS:D: $index)</pre>
<p>Expected to return a Bool indicating whether or not there is an element at position <span class="code">$index </span> . This is what <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> calls when invoked like <span class="code">@foo[42]:exists </span> .</p>
<p>What "existence" of an element means, is up to your type.</p>
<p>If you don't implement this, your type will inherit the default implementation from <span class="code">Any </span> , 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 <a href="">fail</a> s or <a href="">die</a> s, to avoid silently doing the wrong thing.</p>
<a name="t28.10.2.4"$class><h3>28.10.2.4 method DELETE-POS</h3></a>
When modifying this section, please also adapt the DELETE-KEY
section accordingly as they are very similar.
<pre class="code">multi method DELETE-POS (::?CLASS:D: $index)</pre>
<p>Expected to delete the element at position <span class="code">$index </span> , and return the value it had. This is what <a href="/routine/[ ]#postcircumfix_[_]"> <span class="code">postcircumfix [ ] </span> </a> calls when invoked like <span class="code">@foo[42]:delete </span> .</p>
<p>What "deleting" an element means, is up to your type.</p>
<p>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.</p>
<a name="t28.10.2.5"$class><h3>28.10.2.5 method ASSIGN-POS</h3></a>
When modifying this section, please also adapt the ASSIGN-KEY
section accordingly as they are very similar.
<pre class="code">multi method ASSIGN-POS (::?CLASS:D: $index, $new)</pre>
<p>Expected to set the element at position <span class="code">$index </span> to the value <span class="code">$new </span> . Implementing this is entirely optional; if you don't, <span class="code">self.AT-POS($index) = $new </span> is used instead, and if you do, you should make sure it has the same effect.</p>
<p>This is meant as an opt-in performance optimization, so that simple assignments like <span class="code">@numbers[5] = "five" </span> can operate without having to call <span class="code">AT-POS </span> (which would have to create and return a potentially expensive container object).</p>
<p>Note that implementing <span class="code">ASSIGN-POS </span> does <i>not</i> relieve you from making <span class="code">AT-POS </span> an <span class="code">rw </span> method though, because less trivial assignments/modifications such as <span class="code">@numbers[5]++ </span> will still use <span class="code">AT-POS </span> .</p>
<a name="t28.10.2.6"$class><h3>28.10.2.6 method BIND-POS</h3></a>
When modifying this section, please also adapt the BIND-KEY
section accordingly as they are very similar.
<pre class="code">multi method BIND-POS (::?CLASS:D: $index, \new)</pre>
<p>Expected to bind the value or container <span class="code">new </span> to the slot at position <span class="code">$index </span> , replacing any container that would be naturally found there. This is what is called when you write:</p>
<pre class="code">my $x = 10;
@numbers[5] := $x;</pre>
<p>The generic <a href="">Array</a> 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.</p>
<a name="t28.10.3"$class><h2>28.10.3 Methods to implement for associative subscripting</h2></a>
<p>In order to make key-based subscripting via <a href="/routine/{ }#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> work for your custom type, you should implement at least <span class="code">AT-KEY </span> and <span class="code">EXISTS-KEY </span> - and optionally others as detailed below.</p>
<a name="t28.10.3.1"$class><h3>28.10.3.1 method AT-KEY</h3></a>
When modifying this section, please also adapt the AT-POS
section accordingly as they are very similar.
<pre class="code">multi method AT-KEY (::?CLASS:D: $key)</pre>
<p>Expected to return the element associated with <span class="code">$key </span> . This is what <a href="/routine/{ }#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> normally calls.</p>
<p>If you want an element to be mutable (like they are for the built-in <a href="">Hash</a> 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 <span class="code">return-rw </span> or the <span class="code">is rw </span> routine trait to make that work; see the <a href="/language/subscripts#Custom_type_example">example</a> .)</p>
<p>On the other hand if you want your collection to be read-only, feel free to return non-container values directly.</p>
<a name="t28.10.3.2"$class><h3>28.10.3.2 method EXISTS-KEY</h3></a>
When modifying this section, please also adapt the EXISTS-POS
section accordingly as they are very similar.
<pre class="code">multi method EXISTS-KEY (::?CLASS:D: $key)</pre>
<p>Expected to return a Bool indicating whether or not there is an element associated with <span class="code">$key </span> . This is what <a href="/routine/{ }#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> calls when invoked like <span class="code">%foo&lt;aa>:exists </span> .</p>
<p>What "existence" of an element means, is up to your type.</p>
<p>If you don't implement this, your type will inherit the default implementation from <span class="code">Any </span> , 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 <a href="">fail</a> s or <a href="">die</a> s, to avoid silently doing the wrong thing.</p>
<a name="t28.10.3.3"$class><h3>28.10.3.3 method DELETE-KEY</h3></a>
When modifying this section, please also adapt the DELETE-POS
section accordingly as they are very similar.
<pre class="code">multi method DELETE-KEY (::?CLASS:D: $key)</pre>
<p>Expected to delete the element associated with <span class="code">$key </span> , and return the value it had. This is what <a href="/routine/{ }#postcircumfix_{_}"> <span class="code">postcircumfix { } </span> </a> calls when invoked like <span class="code">%foo&lt;aa>:delete </span> .</p>
<p>What "deleting" an element means, is up to your type - though it should usually cause <span class="code">EXISTS-KEY </span> to become <span class="code">False </span> for that key.</p>
<p>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.</p>
<a name="t28.10.3.4"$class><h3>28.10.3.4 method ASSIGN-KEY</h3></a>
When modifying this section, please also adapt the ASSIGN-POS
section accordingly as they are very similar.
<pre class="code">multi method ASSIGN-KEY (::?CLASS:D: $key, $new)</pre>
<p>Expected to set the element associated with <span class="code">$key </span> to the value <span class="code">$new </span> . Implementing this is entirely optional; if you don't, <span class="code">self.AT-KEY($key) = $new </span> is used instead, and if you do, you should make sure it has the same effect.</p>
<p>This is meant as an opt-in performance optimization, so that simple assignments <span class="code">%age&lt;Claire> = 29 </span> can operate without having to call <span class="code">AT-KEY </span> (which would have to create and return a potentially expensive container object).</p>
<p>Note that implementing <span class="code">ASSIGN-KEY </span> does <i>not</i> relieve you from making <span class="code">AT-KEY </span> an <span class="code">rw </span> method though, because less trivial assignments/modifications such as <span class="code">%age&lt;Claire>++ </span> will still use <span class="code">AT-KEY </span> .</p>
<a name="t28.10.3.5"$class><h3>28.10.3.5 method BIND-KEY</h3></a>
When modifying this section, please also adapt the BIND-POS
section accordingly as they are very similar.
<pre class="code">multi method BIND-KEY (::?CLASS:D: $key, \new)</pre>
<p>Expected to bind the value or container <span class="code">new </span> to the slot associated with <span class="code">$key </span> , replacing any container that would be naturally found there. This is what is called when you write:</p>
<pre class="code">my $x = 10;
%age&lt;Claire> := $x;</pre>
<p>The generic <a href="">Hash</a> 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.</p>
<a name="t29"><h1 class="title">29 Syntax</h1></a> <p class="subtitle">General rules of Perl 6 syntax</p></a> <p>Perl 6 borrows many concepts from human language. Which is not surprising, considering it was designed by a linguist.</p>
<p>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.</p>
<p>It is also self-clocking, so that the parser can detect most of the common errors and give good error messages.</p>
<a name="t29.1"$class><h1>29.1 Lexical Conventions</h1></a>
<p>Perl 6 code is Unicode text, current implementations support UTF-8 as the input encoding.</p>
<a name="t29.1.1"$class><h2>29.1.1 Free Form</h2></a>
<p>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.</p>
<p>So you can write</p>
<pre class="code">if True {
say "Hello";
}
</pre>
<p>or</p>
<pre class="code"> if True {
say "Hello";
}
</pre>
<p>or</p>
<pre class="code">if True { say "Hello" }
</pre>
<p>or even</p>
<pre class="code">if True {say "Hello"}
</pre>
<p>though you can't leave out any of the remaining whitespace.</p>
<a name="t29.1.2"$class><h2>29.1.2 Separating Statements</h2></a>
<p>A Perl 6 program is a list of statements, separated by semicolons <span class="code">; </span> . A semicolon after the final statement (or after the final statement inside a block) is optional, though it's good form to include it.</p>
<p>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 <span class="code">if </span> statement block.</p>
<pre class="code">if True {
say "Hello";
}
say "world";
</pre>
<p>Both semicolons are optional here, but leaving them out increases the chance of syntax errors when adding more lines later.</p>
<p>You do need to include a semicolon between the <span class="code">if </span> block and the say statement if you want them all on one line.</p>
<pre class="code">if True { say "Hello" }; say "world";
# ^^^ this ; is required
</pre>
<a name="t29.1.3"$class><h2>29.1.3 Comments</h2></a>
<p>Comments are parts of the program text only intended for human readers, and the Perl 6 compilers does not evaluate them as program text.</p>
<p>Comments count as whitespace in places where the absence of presence of whitespace disambiguates possible parses.</p>
<a name="t29.1.3.1"$class><h3>29.1.3.1 Single-line comments</h3></a>
<p>The most common form of comments in Perl 6 starts with a single hash character <span class="code"># </span> and goes until the end of the line.</p>
<pre class="code">if $age > 250 { # catch obvious outliers
# this is another comment!
die "That doesn't look right"
}
</pre>
<a name="t29.1.3.2"$class><h3>29.1.3.2 Multi-line / embedded comments</h3></a>
<p>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.</p>
<pre class="code">if #`( why would I ever write an inline comment here? ) True {
say "something stupid";
}
</pre>
<p>Brackets inside the comment can be nested, so in <span class="code">#`{ a { b } c } </span> , the comment goes until the very end of the string. You may also use more complex brackets, such as <span class="code">#`{{ double-curly-brace }} </span> , which might help disambiguate from nested brackets.</p>
<a name="t29.1.3.3"$class><h3>29.1.3.3 Pod comments</h3></a>
<p>Pod syntax can be used for multi-line comments</p>
<pre class="code">say "this is code";
=begin comment
Here are several
lines
of comment
=end comment
say 'code again';
</pre>
<a name="t29.1.4"$class><h2>29.1.4 Identifiers</h2></a>
<p>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 <span class="code">- </span> or single quotes <span class="code">' </span> in the middle, but not two in a row.</p>
<pre class="code"># valid identifiers:
x
something-longer
with-numbers1234
don't
fish-food
# not valid identifiers:
with-nubmers1234-5
42
is-prime?
fish--food</pre>
<p>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 <a href="/language/variables">variables</a> for more details.)</p>
<a name="t29.2"$class><h1>29.2 Statements and Expressions</h1></a>
<p>Perl 6 programs are made of lists of statements. A special case of a statement is an <i>expression</i> , which returns a value. For example <span class="code">if True { say 42 } </span> is syntactically a statement, but not an expression, whereas <span class="code">1 + 2 </span> is an expression (and thus also a statement).</p>
<p>The <span class="code">do </span> prefix turns statements into expressions. So while</p>
<pre class="code">my $x = if True { 42 }; # Syntax error!</pre>
<p>is an error,</p>
<pre class="code">my $x = do if True { 42 };</pre>
<p>assigns the return value of the if statement (here <span class="code">42 </span> ) to the variable <span class="code">$x </span> .</p>
<a name="t29.3"$class><h1>29.3 Terms</h1></a>
<p>Terms are the basic nouns that, optionally together with operators, can form expressions. Examples for terms are variables ( <span class="code">$x </span> ), barewords such as type names ( <span class="code">Int </span> ), literals ( <span class="code">42 </span> ), declarations ( <span class="code">sub f() { } </span> ) and calls ( <span class="code">f() </span> ).</p>
<p>For example, in the expression <span class="code">2 * $salary </span> , <span class="code">2 </span> and <span class="code">$salary </span> are two terms (an <a href="/type/Int">integer</a> literal and a <a href="/language/variables">variable</a> ).</p>
<a name="t29.3.1"$class><h2>29.3.1 Variables</h2></a>
<p>Variables typically start with a special character called the <i>sigil</i> , and are followed by an identifier. Variables must be declared before you can use them.</p>
<pre class="code"># declaration:
my $number = 21;
# usage:
say $number * 2;</pre>
<p>See the <a href="/language/variables">documentation on variables</a> for more details.</p>
<a name="t29.3.2"$class><h2>29.3.2 Barewords (Constants, Type Names)</h2></a>
<p>Pre-declared identifiers can be terms on their own. Those are typically type names or constants, but also the term <span class="code">self </span> which refers to an object that a method was called on (see <a href="/language/objects">objects</a> ), and sigiless variables:</p>
<pre class="code">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</pre>
<a name="t29.3.3"$class><h2>29.3.3 Packages and Qualified Names</h2></a>
<p>Named entities, such as variables, constants, classes, modules, subs, etc, are part of a namespace. Nested parts of a name use <span class="code">:: </span> to separate the heirarchy. Some examples:</p>
<pre class="code">$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</pre>
<p>See the <a href="/language/packages">documentaton on packages</a> for more details.</p>
<a name="t29.3.4"$class><h2>29.3.4 Literals</h2></a>
<p>A <a href="https://en.wikipedia.org/wiki/Literal_%28computer_programming%29">literal</a> is a representation of a constant value in source code. Perl 6 has literals for several built-in types, like <a href="/type/Str">strings</a> , several numeric types, <a href="/type/Pair">pairs</a> and more.</p>
<a name="t29.3.4.1"$class><h3>29.3.4.1 String literals</h3></a>
<p>String literals are surrounded by quotes:</p>
<pre class="code">say 'a string literal';
say "a string literal\nthat interprets escape sequences";</pre>
<p>See <a href="/language/quoting">quoting</a> for many more options.</p>
<a name="t29.3.4.2"$class><h3>29.3.4.2 Number literals</h3></a>
<p>Number literals are generally specified in base ten, unless a prefix like <span class="code">0x </span> (he <b>x</b> adecimal, base 16), <span class="code">0o </span> ( <b>o</b> ctal, base 8) or <span class="code">0b </span> ( <b>b</b> inary, base 2) or an explicit base in adverbial notation like <span class="code">:16&lt;A0> </span> specifies it otherwise. Unlike other programming languages, leading zeros do <i>not</i> indicate base 8; instead a compile-time warning is issued</p>
<p>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:</p>
<pre class="code">1000000
1_000_000
10_00000
100_00_00</pre>
<a name="t29.3.4.2.1"$class><h4>29.3.4.2.1 Int literals</h4></a>
<p>Integers default to signed base-10, but you can use other bases. For details, see <a href="/type/Int">Int</a> .</p>
<pre class="code">-2
12345
0xBEEF # base 16
0o755 # base 8
:3&lt;1201> # arbitrary base, here base 3</pre>
<a name="t29.3.4.2.2"$class><h4>29.3.4.2.2 Rat literals</h4></a>
<p> <a href="/type/Rat">Rat</a> literals (rationals) are very common, and take the place of decimals or floats in many other languages. Integer division also results in a <span class="code">Rat </span> .</p>
<pre class="code">1.0
3.14159
-2.5
:3&lt;21.0012> # Base 3 rational
2/3 # Not actually a literal, but still a Rat</pre>
<a name="t29.3.4.2.3"$class><h4>29.3.4.2.3 Num literals</h4></a>
<p>Scientific notation with an exponent to base ten after an <span class="code">e </span> produces <a href="/type/Num">floating point number</a> :</p>
<pre class="code">1e0
6.022e23
1e-9
-2e48</pre>
<a name="t29.3.4.2.4"$class><h4>29.3.4.2.4 Complex literals</h4></a>
<p> <a href="/type/Complex">Complex</a> numbers are written either as an imaginary number (which is just a rational number with postfix <span class="code">i </span> appended), or as a sum of a real and an imaginary number:</p>
<pre class="code">1+2i
6.123e5i</pre>
<a name="t29.3.4.3"$class><h3>29.3.4.3 Pair literals</h3></a>
<p> <a href="/type/Pair">Pairs</a> are made of a key and a value, and there are two basic forms for constructing them: <span class="code">key => 'value' </span> and <span class="code">:key('value') </span> .</p>
<a name="t29.3.4.3.1"$class><h4>29.3.4.3.1 Arrow pairs</h4></a>
<p>Arrow pairs can have an expression or an identifier on the left-hand side:</p>
<pre class="code">identifer => 42
"identifier" => 42
('a' ~ 'b') => 1</pre>
<a name="t29.3.4.3.2"$class><h4>29.3.4.3.2 Adverbial pairs (colon pairs)</h4></a>
<p>Short forms without explicit values:</p>
<pre class="code">my $thing = 42;
:$thing # same as thing => $thing
:thing # same as thing => True
:!thing # same as thing => False</pre>
<p>The variable form also works with other sigils, like <span class="code">:&amp;callback </span> or <span class="code">:@elements </span> .</p>
<p>Long forms with explicit values:</p>
<pre class="code">: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' }</pre>
<a name="t29.3.4.4"$class><h3>29.3.4.4 Array literals</h3></a>
<p>A pair of square brackets can surround an expression to form an itemized <a href="/type/Array">Array</a> literal; typically there is a comma-delimited list inside:</p>
<pre class="code">say ['a', 'b', 42].join(' '); # a b 42
# ^^^^^^^^^^^^^^ Array constructor</pre>
<p>The array constructor flattens non-itemized arrays and lists, but not itemized arrays themselves:</p>
<pre class="code">my @a = 1, 2;
# flattens:
say [@a, 3, 4].elems; # 4
# does not flatten:
say [[@a], [3, 4]].elems; # 2</pre>
<a name="t29.3.4.5"$class><h3>29.3.4.5 Hash literals</h3></a>
<p>A pair of curly braces can surround a list of pairs to form a <a href="/type/Hash">Hash</a> 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.</p>
<pre class="code">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</pre>
<p>When assigning to a <span class="code">% </span> sigil variable, the curly braces are optional.</p>
<pre class="code">my %ages = fred => 23, jean => 87, ann => 4;</pre>
<p>By default keys in <span class="code">{ } </span> are forced to strings. To compose a hash with non-string keys, use a colon prefix:</p>
<pre class="code">my $when = :{ (now) => "Instant", (DateTime.now) => "DateTime" };</pre>
<p>Note that with objects as keys, you cannot access non-string keys as strings:</p>
<pre class="code">:{ -1 => 41, 0 => 42, 1 => 43 }&lt;0> # Any
:{ -1 => 41, 0 => 42, 1 => 43 }{0} # 42</pre>
<a name="t29.3.4.6"$class><h3>29.3.4.6 Regex literals</h3></a>
<p>A <a href="/type/Regex">Regex</a> is declared with slashes like <span class="code">/foo/ </span> . Note that this <span class="code">// </span> syntax is shorthand for the full <span class="code">rx// </span> syntax.</p>
<pre class="code">/foo/ # Short version
rx/foo/ # Longer version
Q :regex /foo/ # Even longer version
my $r = /foo/; # Regexes can be assigned to variables</pre>
<a name="t29.3.4.7"$class><h3>29.3.4.7 Signature literals</h3></a>
<p>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:</p>
<pre class="code">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!" }
}</pre>
<p>See the <a href="/type/Signature">Signatures</a> documentation for more about signatures.</p>
<a name="t29.3.5"$class><h2>29.3.5 Declarations</h2></a>
<a name="t29.3.5.1"$class><h3>29.3.5.1 Variable declaration</h3></a>
<pre class="code">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</pre>
<p>See <a href="http://docs.perl6.org/language/variables#Variable_Declarators_and_Scope">Variable Declarators and Scope</a> for more details on other scopes (our, has).</p>
<a name="t29.3.5.2"$class><h3>29.3.5.2 Subroutine declaration</h3></a>
<pre class="code"># The signature is optional
sub foo { say "Hello!" }
sub say-hello($to-whom) { say "Hello $to-whom!" }</pre>
<p>You can also assign subroutines to variables.</p>
<pre class="code">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</pre>
<a name="t29.3.5.3"$class><h3>29.3.5.3 Module, Class, Role, and Grammar declaration</h3></a>
<p>There are several types of compilation units (packages), each declared with a keyword, a name, some optional traits, and a body of functions.</p>
<pre class="code">module Gar { }
class Foo { }
role Bar { }
grammar Baz { }</pre>
<p>You can declare a unit of things without explicit curly brackets.</p>
<pre class="code">unit module Gar;
# ... stuff goes here instead of in {}'s</pre>
<a name="t29.3.5.4"$class><h3>29.3.5.4 Multi-dispatch declaration</h3></a>
<p>See also <a href="http://docs.perl6.org/language/functions#Multi-dispatch">Multi-dispatch</a> .</p>
<p>Subroutines can be declared with multiple signatures.</p>
<pre class="code">multi sub foo() { say "Hello!" }
multi sub foo($name) { say "Hello $name!" }</pre>
<p>Inside of a class, you can also declare multi-dispatch methods.</p>
<pre class="code">multi method greet { }
multi method greet(Str $name) { }</pre>
<a name="t29.4"$class><h1>29.4 Subroutine calls</h1></a>
<p>See <a href="/language/functions">functions</a> .</p>
TODO
<pre class="code">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>>.();</pre>
<a name="t29.5"$class><h1>29.5 Operators</h1></a>
<p>See <a href="/language/operators">Operators</a> for lots of details.</p>
<p>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.</p>
<p>There are five types (arrangements) for operators, each taking either one or two arguments.</p>
<pre class="code">++$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</pre>
<a name="t29.5.1"$class><h2>29.5.1 Meta Operators</h2></a>
<p>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.</p>
<pre class="code">$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</pre>
<p>Wrap an infix operator in <span class="code">[ ] </span> to create a new reduction operator that works on a single list of inputs, resulting in a single value.</p>
<pre class="code">[+] &lt;1 2 3 4 5> # 15
(((1 + 2) + 3) + 4) + 5 # equivalent expanded version</pre>
<p>Wrap an infix operator in <span class="code">« » </span> (or the ASCII equivalent <span class="code"> </span> ) to create a new hyper operator that works pairwise on two lists.</p>
<pre class="code">&lt;1 2 3> «+» &lt;4 5 6> # &lt;5 7 9></pre>
<p>The direction of the arrows indicates what to do when the lists are not the same size.</p>
<pre class="code">@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</pre>
<p>You can also wrap a unary operator with a hyper operator.</p>
<pre class="code">-« &lt;1 2 3> # &lt;-1 -2 -3></pre>
<a name="t30"><h1 class="title">30 Terms</h1></a> <p class="subtitle">Perl 6 Terms</p></a> <p>Most syntactic constructs in Perl 6 can be categorized in <i>terms</i> and <a href="/language/operators">operators</a> .</p>
<p>Here you can find an overview of different kinds of terms.</p>
<a name="t30.1"$class><h1>30.1 Literals</h1></a>
<a name="t30.1.1"$class><h2>30.1.1 Int</h2></a>
<pre class="code">42
12_300_00
:16&lt;DEAD_BEEF></pre>
<p> <a href="">Int</a> literals consist of digits and can contain underscores between any two digits.</p>
<p>To specify a base other than ten, use the colonpair form <span class="code">:radix&lt;number> </span> .</p>
<a name="t30.1.2"$class><h2>30.1.2 Rat</h2></a>
<pre class="code">12.34
1_200.345_678</pre>
<p> <a href="">Rat</a> literals (rational numbers) contain two integer parts joined by a dot.</p>
<p>Note that trailing dots are not allowed, so you have to write <span class="code">1.0 </span> instead of <span class="code">1. </span> (this rule is important because there are infix operators starting with a dot, for example the <span class="code">.. </span> <a href="">Range</a> operator).</p>
<a name="t30.1.3"$class><h2>30.1.3 Num</h2></a>
<pre class="code">12.3e-32
3e8</pre>
<p> <a href="">Num</a> literals (floating point numbers) consist of <a href="">Rat</a> or <a href="">Int</a> literals followed by an <span class="code">e </span> and a (possibly negative) exponent. <span class="code">3e8 </span> constructs a <a href="">Num</a> with value <span class="code">3 * 10**8 </span> .</p>
<a name="t30.1.4"$class><h2>30.1.4 Str</h2></a>
<pre class="code">'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!|</pre>
<p>String literals are most often created with <span class="code">' </span> or <span class="code">" </span> , however strings are actually a powerful sub-language of Perl 6. See <a href="">Quoting Constructs</a> .</p>
<a name="t30.1.5"$class><h2>30.1.5 Regex</h2></a>
<pre class="code">/ match some text /
rx/slurp \s rest (.*) $/</pre>
<p>These forms produce regex literals. See <a href="">Quoting Constructs</a> .</p>
<a name="t30.1.6"$class><h2>30.1.6 Pair</h2></a>
<pre class="code">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</pre>
<p> <a href="">Pair</a> objects can be created either with <span class="code">infix:«=>» </span> (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).</p>
<p>In the identifier form of a colon-pair, the optional value can be any circumfix. If it is left blank, the value is <span class="code">Bool::True </span> . The value of the <span class="code">:!identifier </span> form is <span class="code">Bool::False </span> .</p>
<p>If used in an argument list, all of these forms count as named arguments, with the exception of <span class="code">'quoted string' => $value </span> .</p>
<a name="t30.1.7"$class><h2>30.1.7 List</h2></a>
<pre class="code">()
1, 2, 3
&lt;a b c>
«a b c»
qw/a b c/</pre>
<p> <a href="">List</a> literals are: the empty pair of parens <span class="code">() </span> , a comma-separated list, or several quoting constructs.</p>
<a name="t30.1.8"$class><h2>30.1.8 term *</h2></a>
<p>Creates an object of type <span class="code">Whatever </span> . See <a href="">Whatever</a> documentation for more details.</p>
<a name="t30.2"$class><h1>30.2 Identifier terms</h1></a>
<p>There are built-in identifier terms in Perl 6, which are listed below. In addition one can add new identifier terms with the syntax:</p>
<pre class="code">sub term:&lt;fourty-two> { 42 };
say fourty-two</pre>
<p>or as constants:</p>
<pre class="code">constant forty-two = 42;
say fourty-two</pre>
<a name="t30.2.1"$class><h2>30.2.1 term self</h2></a>
<p>Inside a method, <span class="code">self </span> 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 <a href="">X::Syntax::NoSelf</a> is thrown.</p>
<a name="t30.2.2"$class><h2>30.2.2 term now</h2></a>
<p>Returns an <a href="">Instant</a> object representing the current time.</p>
<a name="t30.2.3"$class><h2>30.2.3 term time</h2></a>
<p>Returns an <a href="">Int</a> representing the current time.</p>
<a name="t30.2.4"$class><h2>30.2.4 term rand</h2></a>
<p>Returns a pseudo-random <a href="">Num</a> in the range <span class="code">0..^1 </span> .</p>
<a name="t30.2.5"$class><h2>30.2.5 term pi</h2></a>
<p>Returns the number <span class="code">pi </span> , i.e. the ratio between circumference and diameter of a circle.</p>
<a name="t30.2.6"$class><h2>30.2.6 term e</h2></a>
<p>Returns Euler's number.</p>
<a name="t30.2.7"$class><h2>30.2.7 term i</h2></a>
<p>Returns the imaginary unit (for <a href="">Complex</a> numbers).</p>
<a name="t30.3"$class><h1>30.3 Variables</h1></a>
<p>Variables are discussed in the <a href="/language/variables">variable language docs</a> .</p>
<a name="t31"><h1 class="title">31 Testing</h1></a> <p class="subtitle">Writing and running tests in Perl 6</p></a> <p>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.</p>
<p>In Perl 6, the <span class="code">Test </span> module provides a testing framework similar to the traditional Perl 5 <a href="http://perldoc.perl.org/Test/More.html">Test::More</a> module. Thus, anyone familiar with <span class="code">Test::More </span> (and friends) should be comfortable with Perl 6's <span class="code">Test </span> module. The <span class="code">Test </span> module is the testing module used by the official spectest suite.</p>
<p>The testing functions emit output conforming to the <a href="http://testanything.org">Test Anything Protocol</a> .</p>
<a name="t31.1"$class><h1>31.1 Writing tests</h1></a>
<p>As with any Perl project, the tests live under the <span class="code">t </span> directory in the project's base directory.</p>
<p>A typical test file looks something like this:</p>
<pre class="code">use v6;
use Test;
use lib 'lib';
plan $num-tests;
# .... tests</pre>
<p>We ensure that we're using Perl 6, via the <span class="code">use v6 </span> pragma, then we load the <span class="code">Test </span> module and specify where our libraries are. We then specify how many tests we <i>plan</i> 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 <i>done</i> testing.</p>
<a name="t31.2"$class><h1>31.2 Running tests</h1></a>
<p>One can run tests individually by specifying the test filename on the command line:</p>
<pre class="code">$ perl6 t/test-filename.t</pre>
<p>Or via the <a href="http://perldoc.perl.org/prove.html">prove</a> command from Perl 5, where one specifies <span class="code">perl6 </span> as the executable to run the tests:</p>
<pre class="code">$ prove --exec perl6 -r t</pre>
<a name="t31.3"$class><h1>31.3 Test plans</h1></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r114">plan($count)</a></span> </p>
</li></ul> <p>Specify the total number of tests. Usually written at the beginning of a test file.</p>
<pre class="code">plan 15; # expect to run 15 tests</pre>
<p>In <span class="code">subtest </span> s, <span class="code">plan </span> is used to specify the total number of tests within the subtest.</p>
<p>If a <span class="code">plan </span> is used, it is not necessary to denote the end of testing with <span class="code">done-testing </span> .</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r115">done-testing</a></span> </p>
</li></ul> <p>Specify that testing has finished. Use this function when you do not as yet have a <span class="code">plan </span> for the number of tests to run. A <span class="code">plan </span> is thus not required when using <span class="code">done-testing </span> .</p>
<a name="t31.4"$class><h1>31.4 Testing return values</h1></a>
<p>The <span class="code">Test </span> module exports various functions that check the return value of a given expression, and produce standardized test output accordingly.</p>
<p>In practice, the expression will often be a call to a function or method that you want to unit-test.</p>
<a name="t31.4.1"$class><h2>31.4.1 By truthiness</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r116">ok($value, $description?), nok($condition, $description?)</a></span> </p>
</li></ul> <p>The <span class="code">ok </span> function marks a test as passed if the given <span class="code">$value </span> evaluates to <span class="code">True </span> in a boolean context. The <span class="code">nok </span> function marks a test as passed if the given value evaluates to <span class="code">False </span> . Both functions accept an optional <span class="code">$description </span> of the test.</p>
<pre class="code">ok $response.success, 'HTTP response was successful';
nok $query.error, 'Query completed without error';</pre>
<p>In principle you could use <span class="code">ok </span> for every kind of comparison test, by including the comparison in the exression passed to <span class="code">$value </span> :</p>
<pre class="code">ok factorial(6) == 720, 'Factorial - small integer';</pre>
<p>However, where possible it is better to use one of the specialized comparison test functions below, because they can print more helpful diagnostics ouput in case the comparison fails.</p>
<a name="t31.4.2"$class><h2>31.4.2 By string comparison</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r117">is($value, $expected, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if <span class="code">$value </span> and <span class="code">$expected </span> compare positively with the <a href="/routine/eq">eq operator</a> . The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">is $pdf-document.author, "Joe", 'Retrieving the author field';
is factorial(6), 720, 'Factorial - small integer';</pre>
<p>As a special case, if <span class="code">$expected </span> is a type object, the comparison uses the <span class="code">=== </span> operator instead:</p>
<pre class="code">my Int $a;
is $a, Int, 'The variable $a is an unassigned Int';</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r118">isnt($value, $expected, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if <span class="code">$value </span> and <span class="code">$expected </span> are <b>not</b> equal using the same rules as <span class="code">is() </span> . The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">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';</pre>
<a name="t31.4.3"$class><h2>31.4.3 By approximate numeric comparison</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r119">is-approx($value, $expected, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the <span class="code">$value </span> and <span class="code">$expected </span> numerical values are within <span class="code">1e-5 </span> of each other. The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">my $eulers-constant-approx = 2.71828;
is-approx $eulers-constant-approx, e, "approximate Euler's constant";</pre>
<a name="t31.4.4"$class><h2>31.4.4 By structural comparison</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r120">is-deeply($value, $expected, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if <span class="code">$value </span> and <span class="code">$expected </span> compare positively with the <a href="/routine/eqv">eqv operator</a> . This is the best way to check for equality of (deep) data structures. The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">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"';
</pre>
<p>Note that string comparison here would have been fragile, because hashes are not sorted, and converting a <a href="/type/Hash">Hash</a> to a string loses information.</p>
<a name="t31.4.5"$class><h2>31.4.5 By arbitrary comparison</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r121">cmp-ok($value, $comparison, $expected, $description?)</a></span> </p>
</li></ul> <p>Compares <span class="code">$value </span> and <span class="code">$expected </span> with the given <span class="code">$comparison </span> operator and passes the test if the comparison yields a <span class="code">True </span> value. For ease of use, operators may be passed as strings, such as <span class="code">'==' </span> or <span class="code">'~~' </span> . The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">cmp-ok 'my spelling is apperling', '~~', /perl/, "bad speller";</pre>
<a name="t31.4.6"$class><h2>31.4.6 By object type</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r122">isa-ok($value, $expected-type, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given object <span class="code">$value </span> is, or inherits from, the given <span class="code">$expected-type </span> . For convenience, types may also be specified as a string. The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">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</pre>
<a name="t31.4.7"$class><h2>31.4.7 By regex</h2></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r123">like($value, $expected-regex, $description?)</a></span> </p>
</li></ul> <pre class="code">like 'foo', /fo/, 'foo looks like fo';</pre>
<p>Marks a test as passed if the <span class="code">$value </span> , when coerced to a string, matches the <span class="code">$expected-regex </span> . The function accepts an optional <span class="code">$description </span> of the test.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r124">unlike($value, $expected-regex, $description?)</a></span> </p>
</li></ul> <pre class="code">unlike 'foo', /bar/, 'foo does not look like bar';</pre>
<p>Marks a test as passed if the <span class="code">$value </span> , when coerced to a string, does <b>not</b> match the <span class="code">$expected-regex </span> . The function accepts an optional <span class="code">$description </span> of the test.</p>
<a name="t31.5"$class><h1>31.5 Testing modules</h1></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r125">use-ok($module)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$module </span> is correctly loaded.</p>
<pre class="code">use-ok 'Full::Qualified::ModuleName';</pre>
<a name="t31.6"$class><h1>31.6 Testing exceptions</h1></a>
<ul><li><p> <span class="indexed$additional-class"><a name="r126">dies-ok($code, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$code </span> throws an exception.</p>
<p>The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">sub saruman(Bool :$ents-destroy-isengard) {
die "Killed by Wormtongue" if $ents-destroy-isengard;
}
dies-ok { saruman(ents-destroy-isengard => True) }, "Saruman dies";
</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r127">lives-ok($code, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$code </span> <b>does not</b> throw an exception.</p>
<p>The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">sub frodo(Bool :$destroys-ring) {
die "Oops, that wasn't supposed to happen" unless $destroys-ring;
}
lives-ok { frodo(destroys-ring => True) }, "Frodo survivies";
</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r128">eval-dies-ok($string, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$string </span> throws an exception when <span class="code">eval </span> ed as code.</p>
<p>The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">eval-dies-ok q[my $joffrey = "nasty";
die "bye bye Ned" if $joffrey ~~ /nasty/],
"Ned Stark dies";
</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r129">eval-lives-ok($string, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$string </span> <b>does not</b> throw an exception when <span class="code">eval </span> ed as code.</p>
<p>The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">eval-lives-ok q[my $daenerys-burns = False;
die "Oops, Khaleesi now ashes" if $daenerys-burns],
"Dany is blood of the dragon";
</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r130">throws-like($code, $expected-exception, $description?)</a></span> </p>
</li></ul> <p>Marks a test as passed if the given <span class="code">$code </span> throws the specific exception <span class="code">$expected-exception </span> . The code <span class="code">$code </span> may be specified as something <span class="code">Callable </span> , or as a string to be <span class="code">EVAL </span> ed. The exception may be specified as a type object, or as a string containing its type name.</p>
<p>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.</p>
Someone needs to clarify the preceding paragraph, because I have
no idea what it is talking about... ;)
<p>The function accepts an optional <span class="code">$description </span> of the test.</p>
<p>Please note that you can only use the <span class="code">EVAL </span> form 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. For instance:</p>
<pre class="code">throws-like { EVAL q[ fac("foo") ] }, X::TypeCheck::Argument;</pre>
<a name="t31.7"$class><h1>31.7 Grouping tests</h1></a>
<p>The result of a group of subtests is only <span class="code">ok </span> if all subtests are <span class="code">ok </span> .</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r131">subtest(&amp;subtests, $description?)</a></span> </p>
</li></ul> <p>The <span class="code">subtest </span> function executes the given block, consisting of usually more than one test, possibly including a <span class="code">plan </span> or <span class="code">done </span> . It will pass the test only if <b>all</b> tests in the block, pass. The function accepts an optional <span class="code">$description </span> of the test.</p>
<pre class="code">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";
</pre>
<a name="t31.8"$class><h1>31.8 Skipping tests</h1></a>
<p>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 <span class="code">todo </span> . Or it could be the case that a given feature only works on a particular platform - in which case one would <span class="code">skip </span> the test on other platforms.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r132">todo($reason, $count = 1)</a></span> </p>
</li></ul> <p>Mark <span class="code">$count </span> tests as TODO, giving a <span class="code">$reason </span> as to why. By default only one test will be marked TODO.</p>
<pre class="code">sub my-custom-pi { 3 };
todo 'not yet precise enough'; # Mark the test as TODO.
is my-custom-pi(), pi, 'my-custom-pi'; # Tun the test, but don't report
# failure in test harness.</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r133">skip($reason, $count = 1)</a></span> </p>
</li></ul> <p>Skip <span class="code">$count </span> tests, giving a <span class="code">$reason </span> as to why. By default only one test will be skipped. Use such functionality when a test (or tests) would die if run.</p>
<pre class="code">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;
}
</pre>
<ul><li><p> <span class="indexed$additional-class"><a name="r134">skip-rest($reason?)</a></span> </p>
</li></ul> <p>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 <span class="code">$reason </span> as to why.</p>
<pre class="code">unless $location ~~ "Wimbledon Common" {
skip-rest "We can't womble, the remaining tests will fail";
exit;
}
# tests requiring functional wombling
ok womble();
# ...
</pre>
<p>Note that <span class="code">skip-rest </span> requires a <span class="code">plan </span> to be set, otherwise the <span class="code">skip-rest </span> call will throw an error. If no plan was set, you can use <span class="code">done </span> to indicate the end of the test run (though of course the test summary will not count skipped tests).</p>
<a name="t31.9"$class><h1>31.9 Manual control</h1></a>
<p>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.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r135">pass($description?), flunk($description?)</a></span> </p>
</li></ul> <p>The <span class="code">pass </span> function marks a test as passed. <span class="code">flunk </span> marks a test as <b>not</b> passed. Both functions accept an optional test <span class="code">$description </span> .</p>
<pre class="code">pass "Actually, this test has passed";
flunk "But this one hasn't passed";</pre>
<p>As the Perl 5 documentation for <span class="code">Test::More </span> notes, such constructs are used when one has a complicated test condition. As such, they should be used very, very sparingly.</p>
<ul><li><p> <span class="indexed$additional-class"><a name="r136">diag($message)</a></span> </p>
</li></ul> <p>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).</p>
<pre class="code">diag "Yay! The tests got to here!";</pre>
<a name="t32"><h1 class="title">32 Traps to avoid</h1></a> <p class="subtitle">Traps to avoid when getting started with Perl 6</p></a> <p>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.</p>
<p>This document aims to show common misconceptions.</p>
<p>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.</p>
<a name="t32.1"$class><h1>32.1 Objects</h1></a>
<a name="t32.1.1"$class><h2>32.1.1 Assigning to attributes</h2></a>
<p>Newcomers often think that, because attributes with accessors are declared as <span class="code">has $.x </span> , they can assign to <span class="code">$.x </span> inside the class. That's not the case.</p>
<p>For example</p>
<pre class="code">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</pre>
<p>dies with</p>
<pre class="code">Cannot modify an immutable Int</pre>
<p>in the first line marked with <span class="code"># WRONG </span> , because <span class="code">$.x </span> , short for <span class="code">$( self.x ) </span> , is a call to a read-only accessor.</p>
<p>The syntax <span class="code">has $.x </span> is short for something like <span class="code">has $!x; method x() { $!x } </span> , so the actual attribute is called <span class="code">$!x </span> , and a read-only accessor method is automatically generated.</p>
<p>Thus the correct way to write method <span class="code">double </span> is</p>
<pre class="code">method double {
$!x *= 2;
$!y *= 2;
self;
}</pre>
<p>which operates on the attributes directly.</p>
<a name="t32.1.2"$class><h2>32.1.2 BUILD prevents automatic attribute initialization from constructor arguments</h2></a>
<p>When you define your own <span class="code">BUILD </span> submethod, you must take care of initializing all attributes yourself. For example</p>
<pre class="code">use v6;
class A {
has $.x;
has $.y;
submethod BUILD {
$!y = 18;
}
}
say A.new(x => 42).x; # Any</pre>
<p>leaves <span class="code">$!x </span> uninitialized, because the custom <span class="code">BUILD </span> doesn't initialize it.</p>
<p>One possible remedy is to explicitly initialize the attribute in <span class="code">BUILD </span> :</p>
<pre class="code">submethod BUILD(:$x) {
$!y = 18;
$!x := $x;
}</pre>
<p>which can be shortened to:</p>
<pre class="code">submethod BUILD(:$!x) {
$!y = 18;
}</pre>
<p>Another, more general approach is to leave <span class="code">BUILD </span> alone, and hook into the <span class="code">BUILDALL </span> mechanism instead:</p>
<pre class="code">use v6;
class A {
has $.x;
has $.y;
method BUILDALL(|c) {
nextsame;
$!y = 18;
}
}
say A.new(x => 42).x; # 42</pre>
<p>(Note that <span class="code">BUILDALL </span> is a method, not a submethod. That's because by default, there is only one such method per class hierarchy, whereas <span class="code">BUILD </span> is explicitly called per class. Which also explains why you need the <span class="code">nextsame </span> inside <span class="code">BUILDALL </span> , but not inside <span class="code">BUILD </span> ).</p>
<a name="t32.2"$class><h1>32.2 Regexes</h1></a>
<a name="t32.2.1"$class><h2>32.2.1 Whitespace in Regexes does not match literally</h2></a>
<pre class="code">$ perl6 -e "say 'a b' ~~ /a b/"
False</pre>
<p>Whitespace in regexes is, by default, considered an optional filler without semantics, just like in the rest of the Perl 6 language.</p>
<p>Ways to match whitespace:</p>
<ul><li><p> <span class="code">\s </span> to match any one whitespace, <span class="code">\s+ </span> to match at least one</p>
</li></ul> <ul><li><p> <span class="code">' ' </span> (a blank in quotes) to match a single blank</p>
</li></ul> <ul><li><p> <span class="code">\t </span> , <span class="code">\n </span> for specific whitespace (tab, newline)</p>
</li></ul> <ul><li><p> <span class="code">\h </span> , <span class="code">\v </span> for horizontal, vertical whitespace</p>
</li></ul> <ul><li><p> <span class="code">.ws </span> , a built-in rule for whitespace that oftentimes does what you actually want it to do</p>
</li></ul> <ul><li><p>with <span class="code">m:s/a b/ </span> or <span class="code">m:sigspace/a b/ </span> , the blank in the regexes matches arbitrary whitespace</p>
</li></ul> <a name="t32.3"$class><h1>32.3 Captures</h1></a>
<a name="t32.3.1"$class><h2>32.3.1 Containers versus values in a Capture</h2></a>
<p>Beginners might expect a variable in a <span class="code">Capture </span> to supply its current value when that <span class="code">Capture </span> is later used. For example:</p>
<pre class="code">$ perl6 -e 'my $a = 2; say join ',', ($a, ++$a)'
3,3</pre>
<p>Here the <span class="code">Capture </span> contained the <b>container</b> pointed to by <span class="code">$a </span> and the <b>value</b> of the result of the expression <span class="code">++$a </span> . Since the <span class="code">Capture </span> must be reified before <span class="code">&amp;say </span> can use it, the <span class="code">++$a </span> may happen before <span class="code">&amp;say </span> looks inside the container in <span class="code">$a </span> and so it may already be incremented.</p>
<p>Instead, use an expression that produces a value when you want a value.</p>
<pre class="code">$ perl6 -e 'my $a = 2; say join ',', (+$a, ++$a)'
2,3</pre>
<a name="t32.4"$class><h1>32.4 Arrays</h1></a>
<a name="t32.4.1"$class><h2>32.4.1 Referencing the last element of an array</h2></a>
<p>In Perl 5 one could reference the last element of an array by asking for the "-1th" element of the array, e.g.:</p>
<pre class="code">my @array = qw{victor alice bob charlie eve};
say @array[-1]; #-> eve</pre>
<p>In Perl 6 it is not possible to use negative subscripts, however the same is achieved by actually using a function, namely <span class="code">*-1 </span> . Thus accessing the last element of an array becomes:</p>
<pre class="code">my @array = qw{victor alice bob charlie eve};
say @array[*-1]; #-> eve</pre>
<a name="t32.4.2"$class><h2>32.4.2 Typed Array parameters</h2></a>
<p>Quite often new users will happen to write something like:</p>
<pre class="code">sub foo (Array @a) { ... }</pre>
<p>...before they have gotten far enough in the documentation to realize that this is asking for an Array of Arrays. To say that <span class="code">@a </span> should only accept Arrays, use instead:</p>
<pre class="code">sub foo(@a where Array) { ... }</pre>
<p>It is also common to expect this to work, when it does not:</p>
<pre class="code">sub bar(Int @a) { 42.say };
bar([1,2,3]); #-> expected Positional[Int] but got Array</pre>
<p>The problem here is that [1,2,3] is not an <span class="code">Array[Int] </span> , 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 <span class="code">Array[Int] </span> .</p>
<pre class="code">my Int @b = 1,2,3;
bar(@b); #-> 42
bar(Array[Int].new(1,2,3));</pre>
<p>This may seem inconvenient, but on the upside it moves the type-check on what is assigned to <span class="code">@b </span> to where the assignment happens, rather than requiring every element to be checked on every call.</p>
<a name="t32.5"$class><h1>32.5 Strings</h1></a>
<a name="t32.5.1"$class><h2>32.5.1 Capitalizing a string</h2></a>
<p>In Perl 5 one could capitalize a string by using the <span class="code">ucfirst </span> function</p>
<pre class="code">say ucfirst "alice"; #-> Alice</pre>
<p>The <span class="code">ucfirst </span> function does not exist in Perl 6; one needs to use the <span class="code">tc </span> method:</p>
<pre class="code">say "alice".tc; #-> Alice</pre>
<p>which is equivalent to</p>
<pre class="code">say tc "alice"; #-> Alice</pre>
<p>Here, <span class="code">tc </span> means "title case".</p>
<a name="t32.5.2"$class><h2>32.5.2 Strings are not iterable</h2></a>
<p>There are methods that Str inherits from Any that work on iterables like lists. Interators on Strings contain one element that is the whole string. To use <span class="code">sort </span> , <span class="code">reverse </span> and friends, you need to split the string into a list first.</p>
<pre class="code">say "abc".reverse; # abc (what is wrong)
say "abc".comb.reverse.join; # cba</pre>
<a name="t32.6"$class><h1>32.6 Adverbs and Precedence</h1></a>
<p>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 find in the abstract syntax tree. Use paranteses to help Perl 6 to understand what you mean or use operators with looser precedence.</p>
<pre class="code">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</pre>
<a name="t33"><h1 class="title">33 Entering Unicode Characters</h1></a> <p class="subtitle">Input methods for unicode characters in editors and the shell</p></a> <p>Perl 6 allows the use of unicode characters as variable names. Many operators are defined with unicode symbols (in particular the <a href="/language/setbagmix#Set%2FBag_Operators">set/bag operators</a> ) 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.</p>
<p>General information about entering unicode under various operating systems and environments can be found on the Wikipedia <a href="https://en.wikipedia.org/wiki/Unicode_input">unicode input page</a> .</p>
<a name="t33.1"$class><h1>33.1 Editors and shells</h1></a>
<a name="t33.1.1"$class><h2>33.1.1 Vim</h2></a>
<p>In <a href="http://www.vim.org/">Vim</a> , unicode characters are entered (in insert-mode) by pressing first <span class="code">Ctrl-V </span> (also denoted <span class="code">^V </span> ), then <span class="code">u </span> and then the hexadecimal value of the unicode character to be entered. For example, the Greek letter λ (lambda) is entered via the key combination:</p>
<pre class="code">^Vu03BB</pre>
<p>You can also use <span class="code">Ctrl-K </span> / <span class="code">^K </span> along with a digraph to type in some characters. So an alternative to the above using digraphs looks like this:</p>
<pre class="code">^Kl*</pre>
<p>The list of digraphs Vim provides is documented <a href="http://vimdoc.sourceforge.net/htmldoc/digraph.html">here</a> ; you can add your own with the <span class="code">:digraph </span> command.</p>
<p>Further information about entering special characters in Vim can be found on the Vim Wikia page about <a href="http://vim.wikia.com/wiki/Entering_special_characters">entering special characters</a> .</p>
<a name="t33.1.2"$class><h2>33.1.2 Emacs</h2></a>
<p>In <a href="http://www.gnu.org/software/emacs/">Emacs</a> , unicode characters are entered by first entering the chord <span class="code">Ctrl-x 8 Enter </span> at which point the text <span class="code">Unicode (name or hex): </span> appears in the mode line. 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 (whitespace has been added between the commands for clarity):</p>
<pre class="code">Ctrl-x 8 Enter 3bb Enter</pre>
<p>Further information about unicode and its entry into Emacs can be found on the <a href="http://www.emacswiki.org/emacs/UnicodeEncoding">Unicode Encoding Emacs wiki page</a> .</p>
<a name="t33.1.3"$class><h2>33.1.3 Unix shell</h2></a>
<p>At the bash shell, one enters unicode characters by using entering <span class="code">Ctrl-Shift-u </span> , 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):</p>
<pre class="code">Ctrl-Shift-u 2208 Enter</pre>
<p>This also the method one would use to enter unicode characters into the <span class="code">perl6 </span> REPL, if one has started the REPL inside a Unix shell.</p>
<a name="t33.2"$class><h1>33.2 Unicode characters useful in Perl 6</h1></a>
<a name="t33.2.1"$class><h2>33.2.1 <a href="http://en.wikipedia.org/wiki/Guillemet">Guillemets</a> </h2></a>
<p>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:</p>
<table>
<tr><th>symbol</th> <th>unicode code point</th> <th>ascii equivalent</th></tr>
<tr><td>«</td> <td>U+00AB</td> <td>&lt;&lt;</td></tr>
<tr><td>»</td> <td>U+00BB</td> <td>>></td></tr>
</table> <p>Thus constructs such as these are now possible:</p>
<pre class="code">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</pre>
<a name="t33.2.2"$class><h2>33.2.2 Set/bag operators</h2></a>
<p>The <a href="/language/setbagmix#Set%2FBag_Operators">set/bag operators</a> 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. <span class="code">Ctrl-V u </span> in Vim; <span class="code">Ctrl-Shift-u </span> in Bash) then the unicode code point hexadecimal number.</p>
<table>
<tr><th>operator</th> <th>unicode code point</th> <th>ascii equivalent</th></tr>
<tr><td>∈</td> <td>U+2208</td> <td>(elem)</td></tr>
<tr><td>∉</td> <td>U+2209</td> <td>!(elem)</td></tr>
<tr><td>∋</td> <td>U+220B</td> <td>(cont)</td></tr>
<tr><td>∌</td> <td>U+220C</td> <td>!(cont)</td></tr>
<tr><td>⊆</td> <td>U+2286</td> <td>(&lt;=)</td></tr>
<tr><td>⊈</td> <td>U+2288</td> <td>!(&lt;=)</td></tr>
<tr><td>⊂</td> <td>U+2282</td> <td>(&lt;)</td></tr>
<tr><td>⊄</td> <td>U+2284</td> <td>!(&lt;)</td></tr>
<tr><td>⊇</td> <td>U+2287</td> <td>(>=)</td></tr>
<tr><td>⊉</td> <td>U+2289</td> <td>!(>=)</td></tr>
<tr><td>⊃</td> <td>U+2283</td> <td>(>)</td></tr>
<tr><td>⊅</td> <td>U+2285</td> <td>!(>)</td></tr>
<tr><td>≼</td> <td>U+227C</td> <td>(&lt;+)</td></tr>
<tr><td>≽</td> <td>U+227D</td> <td>(>+)</td></tr>
<tr><td>∪</td> <td>U+222A</td> <td>(|)</td></tr>
<tr><td>∩</td> <td>U+2229</td> <td>(&amp;)</td></tr>
<tr><td>∖</td> <td>U+2216</td> <td>(-)</td></tr>
<tr><td>⊖</td> <td>U+2296</td> <td>(^)</td></tr>
<tr><td>⊍</td> <td>U+228D</td> <td>(.)</td></tr>
<tr><td>⊎</td> <td>U+228E</td> <td>(+)</td></tr>
</table> <a name="t33.2.3"$class><h2>33.2.3 Mathematical symbols</h2></a>
<p>Wikipedia contains a full list of <a href="https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode">mathematical operators and symbols in unicode</a> as well as links to their mathematical meaning.</p>
<a name="t33.2.4"$class><h2>33.2.4 Greek characters</h2></a>
<p>Greek characters may be used as variable names. For a list of Greek and Coptic characters and their unicode code points see the <a href="https://en.wikipedia.org/wiki/Greek_alphabet#Greek_in_Unicode">Greek in Unicode Wikipedia article</a> .</p>
<p>For example, to assign the value 3 to π, enter the following in Vim (whitespace added to the compose sequences for clarity):</p>
<pre class="code"> my $ <b>Ctrl-V u 03C0</b> = 3; # same as: my $π = 3;
say $ <b>Ctrl-V u 03C0</b> ; # 3 same as: say $π;
</pre>
<a name="t33.2.5"$class><h2>33.2.5 Superscripts and subscripts</h2></a>
<p>A limited set of <a href="http://en.wikipedia.org/wiki/Superscripts_and_Subscripts">superscripts and subscripts</a> can be created directly in unicode by using the <span class="code">U+207x </span> , <span class="code">U+208x </span> and (less often) the <span class="code">U+209x </span> ranges. However, to produce a value squared (to the power of 2) or cubed (to the power of 3), one needs to use <span class="code">U+00B2 </span> and <span class="code">U+00B3 </span> since these are defined in the <a href="http://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)">Latin1 supplement Unicode block</a> .</p>
<p>Thus, to write the <a href="http://en.wikipedia.org/wiki/Taylor_series">Taylor series</a> expansion around zero of the function <span class="code">exp(x) </span> one would input into e.g. vim the following:</p>
<pre class="code"> 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!
</pre>
<p>Or to specify the elements in a list from <span class="code">1 </span> up to <span class="code">k </span> :</p>
<pre class="code"> 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ₖ
</pre>
<a name="t34"><h1 class="title">34 Variables</h1></a> <p class="subtitle">Variables in Perl 6</p></a> <p>Variable names start with a special character called a <i>sigil</i> , followed optionally by a second special character named <i>twigil</i> and then an <i>identifier</i> .</p>
<a name="t34.1"$class><h1>34.1 Sigils</h1></a>
<p>The sigil serves both as a rough type constraint and as an indicator as to whether the contents of the variable flatten in list context. See also the documentation in <a href="">List</a> .</p>
<table>
<tr><th>Sigil</th> <th>Type constraint</th> <th>Default type</th> <th>Flattens</th> <th>Assignment</th></tr>
<tr><td>$</td> <td>Mu (no type constraint)</td> <td>Any</td> <td>No</td> <td>item</td></tr>
<tr><td>&amp;</td> <td>Callable</td> <td>Callable</td> <td>No</td> <td>item</td></tr>
<tr><td>@</td> <td>Positional</td> <td>Array</td> <td>Yes</td> <td>list</td></tr>
<tr><td>%</td> <td>Associative</td> <td>Hash</td> <td>Yes</td> <td>list</td></tr>
</table> <p>Examples:</p>
<pre class="code">my $square = 9 ** 2;
my @array = 1, 2, 3; # Array variable with three elements
my %hash = London => 'UK', Berlin => 'Germany';</pre>
<p>Variables without sigils are also possible, see <a href="#Sigilless variables">sigilless variables</a> .</p>
<a name="t34.1.1"$class><h2>34.1.1 Item and List Assignment</h2></a>
<p>There are two types of assignment, <i>item assignment</i> and <i>list assignment</i> . Both use the equal sign <span class="code">= </span> as operator. The distinction whether an <span class="code">= </span> means item or list assignment is based on the syntax of the left-hand side.</p>
<p>Item assignment places the value from the right-hand side into the variable (container) on the left.</p>
<p>List assignment leaves the choice of what to do to the variable on the left.</p>
<p>For example, <a href="">Array</a> variables ( <span class="code">@ </span> sigil) empty themselves on list assignment and then put all the values from the right-hand side into themselves.</p>
<p>The type of assignment (item or list) is decided by the first context seen in the current expression or declarator:</p>
<pre class="code">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)</pre>
<p>Thus, the behavior of an assignment contained within a list assignment depends on the expression or declarator that contains it.</p>
<p>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:</p>
<pre class="code">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)</pre>
<p>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:</p>
<pre class="code">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)</pre>
<p>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:</p>
<pre class="code">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)</pre>
<p>This is because the whole expression is <span class="code">@array = $num = 42, "str" </span> , while <span class="code">$num = 42 </span> is not is own separate expression.</p>
<p>See <a href="Language/operators">operators</a> for more details on precedence.</p>
<a name="t34.1.2"$class><h2>34.1.2 Sigilless variables</h2></a>
<p>It is possible to create "variables" in Perl 6 that do not have sigils:</p>
<pre class="code">my \degrees = pi / 180;
my \θ = 15 * degrees;</pre>
<p>Note, however, that these do not create <a href="">containers</a> . That means <span class="code">degrees </span> and <span class="code">θ </span> above actually directly represent <span class="code">Num </span> s. To illustrate, try assigning to one after you've defined it:</p>
<pre class="code">θ = 3; # Dies with the error "Cannot modify an immutable Num"</pre>
<p>Sigilless variables do not enforce context, so they can be used to pass something on as-is:</p>
<pre class="code">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;
}</pre>
<a name="t34.2"$class><h1>34.2 Twigils</h1></a>
<p>Twigils influence the scoping of a variable. Please be aware that twigils have no influence over whether the primary sigil interpolates. That is, if <span class="code">$a </span> interpolates, so do <span class="code">$^a </span> , <span class="code">$*a </span> , <span class="code">$=a </span> , <span class="code">$?a </span> , <span class="code">$.a </span> , etc. It only depends on the <span class="code">$ </span> .</p>
<table>
<tr><th>Twigil</th> <th>Scope</th></tr>
<tr><td>*</td> <td>dynamic</td></tr>
<tr><td>!</td> <td>attribute (class member)</td></tr>
<tr><td>?</td> <td>compile-time variable</td></tr>
<tr><td>.</td> <td>method (not really a variable)</td></tr>
<tr><td>&lt;</td> <td>index into match object (not really a variable)</td></tr>
<tr><td>^</td> <td>self-declared formal positional parameter</td></tr>
<tr><td>:</td> <td>self-declared formal named parameter</td></tr>
<tr><td>=</td> <td>Pod variables</td></tr>
<tr><td>~</td> <td>the sublanguage seen by the parser at this lexical spot</td></tr>
</table> <a name="t34.2.1"$class><h2>34.2.1 The <span class="code">* </span> Twigil</h2></a>
<p>Dynamic variables are looked up through the caller, not through the outer scope. For example:</p>
<pre class="code">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();
</pre>
<p>The first time <span class="code">&amp;say-all </span> is called, it prints " <span class="code">1, 10, 100 </span> " just as one would expect. The second time though, it prints " <span class="code">1, 11, 101 </span> ". This is because <span class="code">$lexical </span> isn't looked up in the caller's scope but in the scope <span class="code">&amp;say-all </span> was defined in. The two dynamic variables are looked up in the caller's scope and therefore have the values <span class="code">11 </span> and <span class="code">101 </span> . The third time <span class="code">&amp;say-all </span> is called <span class="code">$*dynamic1 </span> isn't <span class="code">11 </span> anymore, but <span class="code">$*dynamic2 </span> is still <span class="code">101 </span> . This stems from the fact that we declared a new dynamic variable <span class="code">$*dynamic1 </span> in the block and did not assign to the old variable as we did with <span class="code">$*dynamic2 </span> .</p>
<p>The dynamic variables differ from other variable types in that refering to an undeclared dynamic variable is not a compile time error but a runtime <a href="/type/Failure">failure</a> , 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:</p>
<pre class="code">sub foo() {
$*FOO // 'foo';
}
say foo; # -> 'foo'
my $*FOO = 'bar';
say foo; # -> 'bar'
</pre>
<a name="t34.2.2"$class><h2>34.2.2 The <span class="code">! </span> Twigil</h2></a>
<p>Attributes are variables that exist per instance of a class. They may be directly accessed from within the class via <span class="code">! </span> :</p>
<pre class="code">class Point {
has $.x;
has $.y;
method Str() {
"($!x, $!y)"
}
}
</pre>
<p>Note how the attributes are declared as <span class="code">$.x </span> and <span class="code">$.y </span> but are still accessed via <span class="code">$!x </span> and <span class="code">$!y </span> . This is because in Perl 6 all attributes are private and can be directly accessed within the class by using <span class="code">$!attribute-name </span> . Perl 6 may automatically generate accessor methods for you though. For more details on objects, classes and their attributes see <a href="/language/objects">object orientation</a> .</p>
<a name="t34.2.3"$class><h2>34.2.3 The <span class="code">? </span> Twigil</h2></a>
<p>Compile-time variables may be addressed via the <span class="code">? </span> twigil. They are known to the compiler and may not be modified after being compiled in. A popular example for this is:</p>
<pre class="code">say "$?FILE: $?LINE"; # prints "hello.pl: 23" if this is the 23 line of a
# file named "hello.pl".</pre>
<p>Although they may not be changed at runtime, the user is allowed to (re)define such variables.</p>
<pre class="code">constant $?TABSTOP = 4; # this causes leading tabs in a heredoc or in a POD
# block's virtual margin to be counted as 4 spaces.</pre>
<p>For a list of these special variables see <a href="">#Compile-time variables</a> .</p>
<a name="t34.2.4"$class><h2>34.2.4 The <span class="code">. </span> Twigil</h2></a>
<p>The <span class="code">. </span> twigil isn't really for variables at all. In fact, something along the lines of</p>
<pre class="code">class Point {
has $.x;
has $.y;
method Str() {
"($.x, $.y)" # note that we use the . instead of ! this time
}
}
</pre>
<p>just calls the methods <span class="code">x </span> and <span class="code">y </span> on <span class="code">self </span> , which are automatically generated for you because you used the <span class="code">. </span> twigil when the attributes were declared. Note, however, that subclasses may override those methods. If you don't want this to happen, use <span class="code">$!x </span> and <span class="code">$!y </span> instead.</p>
<p>The fact that the <span class="code">. </span> twigil just does a method call also implies that the following is possible too:</p>
<pre class="code">class SaySomething {
method a() { say "a"; }
method b() { $.a; }
}
SaySomething.b; # prints "a"
</pre>
<p>For more details on objects, classes and their attributes and methods see <a href="/language/objects">object orientation</a> .</p>
<a name="t34.2.5"$class><h2>34.2.5 The <span class="code">&lt; </span> Twigil</h2></a>
<p>The <span class="code">&lt; </span> twigil is just an alias for <span class="code">$/&lt;...> </span> where <span class="code">$/ </span> is the match variable. For more information about the match variable see <a href="">$/</a> and <a href="/type/Match">type Match</a> .</p>
<a name="t34.2.6"$class><h2>34.2.6 The <span class="code">^ </span> Twigil</h2></a>
<p>The <span class="code">^ </span> twigil declares a formal positional parameter to blocks or subroutines. Variables of the form <span class="code">$^variable </span> 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</p>
<pre class="code"> for ^4 {
say " <b>$^second</b> follows <b>$^first</b> ";
}
</pre>
<p>which prints</p>
<pre class="code">1 follows 0
3 follows 2</pre>
<p>has two formal parameters, namely <span class="code">$first </span> and <span class="code">$second </span> . Note that even though <span class="code">$^second </span> appears before <span class="code">$^first </span> in the code, <span class="code">$^first </span> 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 <span class="code">$^a </span> once, you may refer to it using only <span class="code">$a </span> thereafter.</p>
<p>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.</p>
<pre class="code">sub say-it { say $^a; } # valid
sub say-it() { say $^a; } # invalid
{ say $^a; } # valid
-> $x, $y, $x { say $^a; } # invalid</pre>
<p>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.</p>
<a name="t34.2.7"$class><h2>34.2.7 The <span class="code">: </span> Twigil</h2></a>
<p>The <span class="code">: </span> 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 <span class="code">^ </span> twigil also apply here (with the exception that they are not positional and therefore not ordered using Unicode order, of course). So this:</p>
<pre class="code"> say { <b>$:add</b> ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add
</pre>
<p>Will print " <span class="code">-1 </span> ".</p>
<p>See <a href="">^</a> for more details about placeholder variables.</p>
<a name="t34.2.8"$class><h2>34.2.8 The <span class="code">= </span> Twigil</h2></a>
<p>The <span class="code">= </span> twigil is used to access Pod variables. Every Pod block in the current file can be accessed via a Pod object, such as <span class="code">$=data </span> , <span class="code">$=SYNOPSIS </span> or <span class="code">=UserBlock </span> . That is: a variable with the same name of the desired block and a <span class="code">= </span> twigil.</p>
<pre class="code">=begin Foo
...
=end Foo
#after that, $=Foo gives you all Foo-Pod-blocks
</pre>
<p>You may access the Pod tree which contains all Pod structures as a hierarchical data structure through <span class="code">$=pod </span> .</p>
<p>Note that all those <span class="code">$=someBlockName </span> support the <span class="code">Positional </span> and the <span class="code">Associative </span> roles.</p>
<a name="t34.2.9"$class><h2>34.2.9 The <span class="code">~ </span> Twigil</h2></a>
<p>Note: Slangs are NYI in Rakudo.</p>
<p>The <span class="code">~ </span> twigil is for referring to sublanguages (called slangs). The following are useful:</p>
<pre class="code">$~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</pre>
<p>You may <span class="code">supersede </span> or <span class="code">augment </span> these languages in your current lexical scope by using</p>
<pre class="code">augment slang Regex { # derive from $~Regex and then modify $~Regex
token backslash:std&lt;\Y> { YY };
}</pre>
<p>or</p>
<pre class="code">supersede slang Regex { # completely substitute $~Regex
...
}</pre>
<a name="t34.3"$class><h1>34.3 Variable Declarators and Scope</h1></a>
<p>Most of the time it's enough to create a new variable using the <span class="code">my </span> keyword:</p>
<pre class="code"> <b>my</b> $amazing-variable = "World";
say "Hello $amazing-variable!"; # Hello World!
</pre>
<p>However, there are many declarators that change the details of scoping beyond what <a href="">#Twigils</a> can do.</p>
<table>
<tr><th>Declarator</th> <th>Effect</th></tr>
<tr><td>my</td> <td>Introduces lexically scoped names</td></tr>
<tr><td>our</td> <td>Introduces package-scoped names</td></tr>
<tr><td>has</td> <td>Introduces attribute names</td></tr>
<tr><td>anon</td> <td>Introduces names that are private to the construct</td></tr>
<tr><td>state</td> <td>Introduces lexically scoped but persistent names</td></tr>
<tr><td>augment</td> <td>Adds definitions to an existing name</td></tr>
<tr><td>supersede</td> <td>Replaces definitions of an existing name</td></tr>
</table> <p>There are also two prefixes that resemble declarators but act on predefined variables:</p>
<table>
<tr><th>Prefix</th> <th>Effect</th></tr>
<tr><td>temp</td> <td>Restores a variable's value at the end of scope</td></tr>
<tr><td>let</td> <td>Restores a variable's value at the end of scope if the block exits unsuccessfully</td></tr>
</table> <a name="t34.3.1"$class><h2>34.3.1 The <span class="code">my </span> Declarator</h2></a>
<p>Declaring a variable with <span class="code">my </span> gives it lexical scope. This means it only exists within the current block. For example:</p>
<pre class="code">{
my $foo = "bar";
say $foo; # -> "bar"
}
say $foo; # !!! "Variable '$foo' is not declared"</pre>
<p>This dies because <span class="code">$foo </span> is only defined as long as we are in the same scope.</p>
<p>Additionally, lexical scoping means that variables can be temporarily redefined in a new scope:</p>
<pre class="code">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"
</pre>
<p>If a variable has been redefined, any code that referenced the outer variable will continue to reference the outer variable. So here, <span class="code">&amp;outer-location </span> still prints the outer <span class="code">$location </span> :</p>
<pre class="code">sub new-location {
my $location = "nowhere"
outer-location;
}
new-location; # -> "outside"
</pre>
<p>To make <span class="code">new-location() </span> print <span class="code">nowhere </span> , make <span class="code">$location </span> a dynamic variable using <a href="#The_*_Twigil">the * twigil</a> .</p>
<p> <span class="code">my </span> is the default scope for subroutines, so <span class="code">my sub x() {} </span> and <span class="code">sub x() {} </span> do exactly the same thing.</p>
<a name="t34.3.2"$class><h2>34.3.2 The <span class="code">our </span> Declarator</h2></a>
<p> <span class="code">our </span> variables work just like <span class="code">my </span> variables, except that they also introduce an alias into the symbol table.</p>
<pre class="code">module M {
our $Var;
# $Var available here
}
# Available as $M::Var here.</pre>
<a name="t34.3.3"$class><h2>34.3.3 The <span class="code">has </span> Declarator</h2></a>
<p> <span class="code">has </span> scopes attributes to instances of a class or role, and methods to classes or roles. <span class="code">has </span> is implied for methods, so <span class="code">has method x() {} </span> and <span class="code">method x() {} </span> do the same thing.</p>
<p>See <a href="/language/objects">object orientation</a> for more documentation and some examples.</p>
<a name="t34.3.4"$class><h2>34.3.4 The <span class="code">anon </span> Declarator</h2></a>
<p>The <span class="code">anon </span> declarator prevents a symbol from getting installed in the lexical scope, the method table and everywhere else.</p>
<p>For example you can use it to declare subroutines which know their own name, but still aren't installed in a scope:</p>
<pre class="code">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</pre>
<a name="t34.3.5"$class><h2>34.3.5 The <span class="code">state </span> Declarator</h2></a>
<p> <span class="code">state </span> declares lexically scoped variables, just like <span class="code">my </span> . 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.</p>
<p>Therefore, the subroutine</p>
<pre class="code">sub a {
state @x;
state $l = 'A';
@x.push($l++);
};
say a for 1..6;
</pre>
<p>will continue to increment <span class="code">$l </span> and append it to <span class="code">@x </span> each time it is called. So it will output</p>
<pre class="code">[A]
[A B]
[A B C]
[A B C D]
[A B C D E]
[A B C D E F]
</pre>
<p>As with <span class="code">my </span> , declaring multiple <span class="code">state </span> variables must be placed in parentheses and for declaring a single variable, parentheses may be omitted.</p>
<p>Please note that many operators come with implicit binding, what will lead to actions at a distance. Use <span class="code">.clone </span> or coercion to create a new container that can be bound to.</p>
<pre class="code">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)]»</pre>
<a name="t34.3.5.1"$class><h3>34.3.5.1 The <span class="code">$ </span> Variable</h3></a>
<p>As well as explicitly declared named state variables <span class="code">$ </span> can be used as an anonymous state variable without an explicit <span class="code">state </span> declaration:</p>
<pre class="code">perl6 -e 'sub foo() { say ++$ }; foo() for ^3'
</pre>
<p>produces:</p>
<pre class="code">1
2
3
</pre>
<p>Furthermore, state variables are not required to exist in subroutines. You could, for example, use <span class="code">$ </span> in a one-liner to number the lines in a file:</p>
<pre class="code">perl6 -ne 'say ++$ ~ " $_"' example.txt
</pre>
<p>Each reference to <span class="code">$ </span> within a lexical scope in effect is a separate variable, as illustrated by:</p>
<pre class="code">perl6 -e '{ say ++$; say $++ } for ^5'
</pre>
<p>which produces:</p>
<pre class="code">1
0
2
1
3
2
4
3
5
4
</pre>
<p>If you need to refer to the value of <span class="code">$ </span> more than once within the scope it should be copied to a new variable, for example:</p>
<pre class="code">sub foo() {
given ++$ {
when 1 {
say "one";
}
when 2 {
say "two";
}
when 3 {
say "three";
}
default {
say "many";
}
}
}
foo() for ^3;
</pre>
<p>produces:</p>
<pre class="code">one
two
three
</pre>
<a name="t34.3.5.2"$class><h3>34.3.5.2 The <span class="code">@ </span> Variable</h3></a>
<p>In a similar manner to the <span class="code">$ </span> variable there is also a <a href="">Positional</a> anonymous state variable <span class="code">@ </span> :</p>
<pre class="code">sub foo($x) {
say (@).push($x);
}
foo($_) for ^3;
</pre>
<p>Produces:</p>
<pre class="code">[0]
[0 1]
[0 1 2]
</pre>
<p>The <span class="code">@ </span> here is parenthesized in order to disambiguate the expression from a class member variable named <span class="code">@.push </span> . Indexed access doesn't require this disambiguation but you will need to copy the value in order to do anything useful with it:</p>
<pre class="code">sub foo($x) {
my $v = @;
$v[$x] = $x;
say $v;
}
foo($_) for ^3;
</pre>
<p>Produces:</p>
<pre class="code">[0]
[0 1]
[0 1 2]
</pre>
<p>As with <span class="code">$ </span> each mention of <span class="code">@ </span> in a scope introduces a new anonymous array.</p>
<a name="t34.3.5.3"$class><h3>34.3.5.3 The <span class="code">% </span> Variable</h3></a>
<p>Finally there is also an <a href="">Associative</a> anonymous state variable <span class="code">% </span> :</p>
<pre class="code">sub foo($x) {
say (%).push($x => $x);
}
foo($_) for ^3;
</pre>
<p>Which produces:</p>
<pre class="code">0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2
</pre>
<p>The same caveat about disambiguation applies. As you may expect, indexed access is also possible (with copying to make it useful):</p>
<pre class="code">sub foo($x) {
my $v = %;
$v{$x} = $x;
say $v;
}
foo($_) for ^3;
</pre>
<p>Which produces:</p>
<pre class="code">0 => 0
0 => 0, 1 => 1
0 => 0, 1 => 1, 2 => 2
</pre>
<p>As with the other anonymous state variables each mention of <span class="code">% </span> within a given scope will effectively introduce a separate variable.</p>
<a name="t34.3.6"$class><h2>34.3.6 The <span class="code">augment </span> Declarator</h2></a>
<p>With <span class="code">augment </span> , you can add attributes and methods to existing classes and grammars, provided you activated the <span class="code">MONKEY-TYPING </span> pragma first.</p>
<p>Since classes are usually <span class="code">our </span> scoped, and thus global, this means modifying global state, which is strongly discouraged. For almost all situations, there are better solutions.</p>
<pre class="code"># don't do this
use MONKEY-TYPING;
augment class Int {
method is-answer { self == 42 }
}
say 42.is-answer; # True</pre>
<p>(In this case, the better solution would be to use a <a href="/language/functions">function</a> ).</p>
<a name="t34.3.7"$class><h2>34.3.7 The <span class="code">supersede </span> Declarator</h2></a>
TODO
<a name="t34.3.8"$class><h2>34.3.8 The <span class="code">temp </span> Prefix</h2></a>
<p>Like <span class="code">my </span> , <span class="code">temp </span> restores the old value of a variable at the end of its scope. However, <span class="code">temp </span> does not create a new variable.</p>
<pre class="code">my $cookies = 5;
sub buy-cookie { $cookies++ }
{
my $cookies = 42;
buy-cookie; # Increments the outer $cookies variable
say $cookies; # 42
# the outer $cookies variable is 6 now
}
{
temp $cookies = 42;
# Still the same $cookies, but a new value:
buy-cookie;
say $cookies; # -> 43
}
# Old value is restored
say $cookies; # -> 6
</pre>
<a name="t34.3.9"$class><h2>34.3.9 The <span class="code">let </span> Prefix</h2></a>
<p>Restores the previous value if the block exits unsuccessfully. A successful exit means the block returned a defined value or a list.</p>
<pre class="code">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;</pre>
<p>In the above case, if the <span class="code">Bool.pick </span> returns true, the answer will stay as 84 because the block returns a defined value ( <span class="code">say </span> returns true). Otherwise the <span class="code">die </span> statement will cause the block to exit unsuccessfully, resetting the answer to 42.</p>
this is duplicated in operators.pod
<a name="t34.4"$class><h1>34.4 Type Constraints and Initialization</h1></a>
<p>Variables can have a type constraint, which goes between the declarator and the variable name:</p>
<pre class="code"> my Int $x = 42;
$x = 'a string'; # throws an <a href="/type/X::TypeCheck::Assignment">X::TypeCheck::Assignment</a> error
</pre>
<p>If a scalar variable has a type constraint but no initial value, it is initialized with the type object of the constraint type.</p>
<pre class="code">my Int $x;
say $x.^name; # Int
say $x.defined; # False</pre>
<p>Scalar variables without an explicit type constraint are typed as <a href="/type/Mu">Mu</a> but default to the <a href="/type/Any">Any</a> type object.</p>
<p>Variables with the <span class="code">@ </span> sigil are initialized with an empty <a href="/type/Array">Array</a> ; variables with the <span class="code">% </span> sigil are initialized with an empty <a href="/type/Hash">Hash</a> .</p>
<p>The default value of a variable can be set with the <span class="code">is default </span> trait, and re-applied by assigning <span class="code">Nil </span> to it:</p>
<pre class="code">my Real $product is default(1);
say $product; # 1
$produce *= 5;
say $product; # 5
$product = Nil;
say $product; # 1</pre>
<a name="t34.5"$class><h1>34.5 Special Variables</h1></a>
<p>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.</p>
<a name="t34.5.1"$class><h2>34.5.1 Pre-defined lexical variables</h2></a>
<p>There are three special variables that are available in every block:</p>
<table>
<tr><th>Variable</th> <th>Meaning</th></tr>
<tr><td>$_</td> <td>topic variable</td></tr>
<tr><td>$/</td> <td>regex match</td></tr>
<tr><td>$!</td> <td>exceptions</td></tr>
</table> <a name="t34.5.1.1"$class><h3>34.5.1.1 The <span class="code">$_ </span> Variable</h3></a>
<p> <span class="code">$_ </span> is the topic variable. It is the default parameter for blocks that do not have an explicit signature, so constructs like <span class="code">for @array { ... } </span> and <span class="code">given $var { ... } </span> bind to <span class="code">$_ </span> simply by invoking the block.</p>
<pre class="code">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</pre>
<p> <span class="code">CATCH </span> blocks set <span class="code">$_ </span> to the exception that was caught. The <span class="code">~~ </span> smart-match operator sets <span class="code">$_ </span> on the right-hand side expression to the value of the left-hand side.</p>
<p>Calling a method on <span class="code">$_ </span> can be shortened by leaving off the variable name:</p>
<pre class="code">.say; # same as $_.say</pre>
<p> <span class="code">m/regex/ </span> and <span class="code">/regex/ </span> regex matches and <span class="code">s/regex/subst/ </span> substitutions work on <span class="code">$_ </span> :</p>
<pre class="code">say "Looking for strings with non-alphabetic characters...";
for &lt;ab:c d$e fgh ij*> {
.say if m/&lt;!alpha>/;
}</pre>
<p>This outputs:</p>
<pre class="code">Looking for strings with non-alphabetic characters...
ab:c
d$e
ij*</pre>
<a name="t34.5.1.2"$class><h3>34.5.1.2 The <span class="code">$/ </span> Variable</h3></a>
<p> <span class="code">$/ </span> is the match variable. It stores the result of the last <a href="regex">Regex</a> match and so usually contains objects of type <a href="">Match</a> .</p>
<pre class="code">'abc 12' ~~ /\w+/; # sets $/ to a Match object
say $/.Str; # abc</pre>
<p>The <span class="code">Grammar.parse </span> method also sets the caller's <span class="code">$/ </span> to the resulting <a href="">Match</a> object.</p>
<pre class="code">use XML;
XML.parse(slurp "filename.xml")
say $/;</pre>
<a name="t34.5.1.2.1"$class><h4>34.5.1.2.1 Positional Attributes </h4></a>
<p> <span class="code">$/ </span> can have positional attributes if the <a href="regex">Regex</a> had capture-groups in it, which are just formed with parentheses.</p>
<pre class="code">'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;
say $/[0]; # 「bbbbb」
say $/[1]; # 「dddddeff」</pre>
<p>These can also be accessed by the shortcuts <span class="code">$0 </span> , <span class="code">$1 </span> , <span class="code">$2 </span> , etc.</p>
<pre class="code">say $0; # 「bbbbb」
say $1; # 「dddddeff」</pre>
<p>To get all of the positional attributes, any of <span class="code">$/.list </span> , <span class="code">@$/ </span> , or <span class="code">@() </span> can be used.</p>
<pre class="code">say @().join; # bbbbbdddddeff</pre>
<a name="t34.5.1.2.2"$class><h4>34.5.1.2.2 Named Attributes </h4></a>
<p> <span class="code">$/ </span> can have named attributes if the <a href="regex">Regex</a> had named capture-groups in it, or if the Regex called out to another Regex.</p>
<pre class="code">'I.... see?' ~~ / \w+ $&lt;punctuation>=[ &lt;-[\w\s]>+ ] \s* $&lt;final-word> = [ \w+ . ] /;
say $/&lt;punctuation>; # 「....」
say $/&lt;final-word>; # 「see?」</pre>
<p>These can also be accessed by the shortcut <span class="code">$&lt;named> </span> .</p>
<pre class="code">say $&lt;punctuation>; # 「....」
say $&lt;final-word>; # 「see?」</pre>
<p>To get all of the named attributes, any of <span class="code">$/.hash </span> , <span class="code">%$/ </span> , or <span class="code">%() </span> can be used.</p>
<pre class="code">say %().join; # "punctuation ....final-word see?"</pre>
<a name="t34.5.1.3"$class><h3>34.5.1.3 The <span class="code">$! </span> Variable</h3></a>
<p> <span class="code">$! </span> is the error variable. If a <span class="code">try </span> block or statement prefix catches an exception, that exception is stored in <span class="code">$! </span> . If no exception was caught, <span class="code">$! </span> is set to the <span class="code">Any </span> type object.</p>
<p>Note that <span class="code">CATCH </span> blocks <i>do not</i> set <span class="code">$! </span> . Rather they set <span class="code">$_ </span> inside the block to the caught exception.</p>
<a name="t34.5.2"$class><h2>34.5.2 Compile-time variables</h2></a>
<table>
<tr><td>$?FILE Which file am I in?</td></tr>
<tr><td>$?LINE Which line am I at?</td></tr>
<tr><td>&amp;?ROUTINE Which routine am I in?</td></tr>
<tr><td>&amp;?BLOCK Which block am I in?</td></tr>
<tr><td>%?LANG What is the current set of interwoven languages?</td></tr>
<tr><td>%?RESOURCES The files associated with the "Distribution" of the current compilation unit.</td></tr>
</table> <p>Other compile-time variables:</p>
<table>
<tr><td>$?SCOPE</td> <td>Which lexical scope am I in?</td></tr>
<tr><td>$?PACKAGE</td> <td>Which package am I in?</td></tr>
<tr><td>$?MODULE</td> <td>Which module am I in?</td></tr>
<tr><td>$?CLASS</td> <td>Which class am I in? (as variable)</td></tr>
<tr><td>$?ROLE</td> <td>Which role am I in? (as variable)</td></tr>
<tr><td>$?GRAMMAR</td> <td>Which grammar am I in?</td></tr>
<tr><td>$?TABSTOP</td> <td>How many spaces is a tab in a heredoc or virtual margin?</td></tr>
<tr><td>$?USAGE</td> <td>The usage message generated from the signatures of MAIN subs.</td></tr>
<tr><td>$?ENC</td> <td>Default encoding of Str.encode/Buf.decode/various IO methods.</td></tr>
</table> <a name="t34.5.3"$class><h2>34.5.3 Dynamic variables</h2></a>
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.
<table>
<tr><td>$*ARGFILES Magic command-line input handle.</td></tr>
<tr><td>@*ARGS Arguments from the command line.</td></tr>
<tr><td>$*IN Standard input filehandle, AKA stdin</td></tr>
<tr><td>$*OUT Standard output filehandle, AKA stdout</td></tr>
<tr><td>$*ERR Standard error filehandle, AKA stderr</td></tr>
<tr><td>$*REPO A variable holding information about modules installed/loaded</td></tr>
<tr><td>$*TZ The system's local timezone.</td></tr>
<tr><td>$*CWD The Current Working Directory.</td></tr>
<tr><td>$*KERNEL Which kernel am I compiled for?</td></tr>
<tr><td>$*DISTRO Which OS distribution am I compiling under?</td></tr>
<tr><td>$*VM Which virtual machine am I compiling under?</td></tr>
<tr><td>$*PERL Which Perl am I compiled for?</td></tr>
<tr><td>$*PID Process ID of the current process.</td></tr>
<tr><td>$*PROGRAM-NAME Path to the current executable as it was entered on the command line, or C&lt;-e> if perl was invoked with the -e flag.</td></tr>
<tr><td>$*PROGRAM Location (in the form of an C&lt;IO::Path> object) of the Perl program being executed.</td></tr>
<tr><td>$*EXECUTABLE Absolute path of the perl executable that is currently running.</td></tr>
<tr><td>$*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.</td></tr>
<tr><td>$*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.</td></tr>
<tr><td>$*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.</td></tr>
<tr><td>$*HOME An L&lt;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&lt;Nil></td></tr>
<tr><td>$*SPEC The appropriate L&lt;IO::Spec> sub-class for the platform that the program is running on.</td></tr>
</table> <a name="t35"><h1 class="title">35 class AST</h1></a> <p class="subtitle">Abstract representation of a piece of source code</p></a> <pre class="code">class AST { }</pre>
<p>An <span class="code">AST </span> or <i>Abstract Syntax Tree</i> is a partially processed representation of a program. ASTs are return values of the <span class="code">quasi </span> quoting construct, and are typically used within macros to generate code that is inserted in the calling location of the macro.</p>
<p>There is no API defined for ASTs yet. Hopefully that will emerge as part of the work on macros.</p>
<a name="t36"><h1 class="title">36 class Any</h1></a> <p class="subtitle">Thing/object</p></a> <pre class="code">class Any is Mu { ... }</pre>
<p>While <a href="/type/Mu">Mu</a> is the root of the Perl 6 class hierarchy, <span class="code">Any </span> is the class that serves as a default base class for new classes, and as the base class for most built-in classes.</p>
<p>Since Perl 6 intentionally confuses items and single-element lists, most methods in <span class="code">Any </span> are also present on class <a href="/type/List">List</a> , and coerce to List or a list-like type.</p>
<a name="t36.1"$class><h1>36.1 Methods</h1></a>
<a name="t36.1.1"$class><h2>36.1.1 method ACCEPTS</h2></a>
<p>Defined as:</p>
<pre class="code">multi method ACCEPTS(Any:D: Mu $other)</pre>
<p>Usage:</p>
<pre class="code">EXPR.ACCEPTS(EXPR);</pre>
<p>Returns <span class="code">True </span> if <span class="code">$other === self </span> (i.e. it checks object identity).</p>
<p>Many built-in types override this for more specific comparisons</p>
<a name="t36.1.2"$class><h2>36.1.2 method any</h2></a>
<p>Defined as:</p>
<pre class="code">method any() returns Junction:D</pre>
<p>Usage:</p>
<pre class="code">LIST.any</pre>
<p>Interprets the invocant as a list and creates an <span class="code">any </span> - <a href="/type/Junction">Junction</a> from it.</p>
<pre class="code">say so 2 == &lt;1 2 3>.any; # True
say so 5 == &lt;1 2 3>.any; # False</pre>
<a name="t36.1.3"$class><h2>36.1.3 method all</h2></a>
<p>Defined as:</p>
<pre class="code">method all() returns Junction:D</pre>
<p>Usage:</p>
<pre class="code">LIST.any</pre>
<p>Interprets the invocant as a list and creates an <span class="code">all </span> - <a href="/type/Junction">Junction</a> from it.</p>
<pre class="code">say so 1 &lt; &lt;2 3 4>.all; # True
say so 3 &lt; &lt;2 3 4>.all; # False</pre>
<a name="t36.1.4"$class><h2>36.1.4 method one</h2></a>
<p>Defined as:</p>
<pre class="code">method one() returns Junction:D</pre>
<p>Usage:</p>
<pre class="code">LIST.one</pre>
<p>Interprets the invocant as a list and creates an <span class="code">one </span> - <a href="/type/Junction">Junction</a> from it.</p>
<pre class="code">say so 1 == (1, 2, 3).one; # True
say so 1 == (1, 2, 1).one; # False</pre>
<a name="t36.1.5"$class><h2>36.1.5 method none</h2></a>
<p>Defined as:</p>
<pre class="code">method none() returns Junction:D</pre>
<p>Usage:</p>
<pre class="code">LIST.none</pre>
<p>Interprets the invocant as a list and creates an <span class="code">none </span> - <a href="/type/Junction">Junction</a> from it.</p>
<pre class="code">say so 1 == (1, 2, 3).none; # False
say so 4 == (1, 2, 3).none; # True</pre>
<a name="t36.1.6"$class><h2>36.1.6 method list</h2></a>
<p>Interprets the invocant as a list, and returns that <a href="/type/List">List</a> .</p>
<pre class="code">say 42.list.^name; # List
say 42.list.elems; # 1</pre>
<a name="t36.1.7"$class><h2>36.1.7 routine reverse</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub reverse(*@list ) returns List:D
multi method reverse(List:D:) returns List:D</pre>
<p>Usage:</p>
<pre class="code">reverse(LIST)
LIST.reverse</pre>
<p>Returns a list with the same elements in reverse order.</p>
<p>Note that <span class="code">reverse </span> always refers to reversing elements of a list; to reverse the characters in a string, use <a href="">flip</a> .</p>
<p>Examples:</p>
<pre class="code">say &lt;hello world!>.reverse # world! hello
say reverse ^10 # 9 8 7 6 5 4 3 2 1 0</pre>
<a name="t36.1.8"$class><h2>36.1.8 method sort</h2></a>
<p>Sorts iterables with <span class="code">infix:&lt;cmp> </span> or given code object.</p>
<p>Examples:</p>
<pre class="code">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</pre>
<a name="t36.1.9"$class><h2>36.1.9 method flat</h2></a>
<p>Interprets the invocant as a list, flattens it, and returns that list.</p>
<pre class="code">say ((1, 2), (3)).elems; # 2
say ((1, 2), (3)).flat.elems; # 3</pre>
<a name="t36.1.10"$class><h2>36.1.10 method eager</h2></a>
<p>Interprets the invocant as a list, evaluates it eagerly, and returns that list.</p>
<pre class="code">say (1..10).eager; # 1 2 3 4 5 6 7 8 9 10</pre>
<a name="t36.1.11"$class><h2>36.1.11 method elems</h2></a>
<p>Interprets the invocant as a list, and returns the number of elements in the list.</p>
<pre class="code">say 42.elems; # 1
say &lt;a b c>.elems; # 3</pre>
<a name="t36.1.12"$class><h2>36.1.12 method end</h2></a>
<p>Interprets the invocant as a list, and returns the last index of that list.</p>
<pre class="code">say 6.end; # 0
say &lt;a b c>.end; # 2</pre>
<a name="t36.1.13"$class><h2>36.1.13 method pairup</h2></a>
<pre class="code">method pairup() returns List</pre>
<p>Interprets the invocant as a list, and constructs a list of <a href="/type/Pair">pairs</a> from it, in the same way that assignment to a <a href="/type/Hash">Hash</a> 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).</p>
<pre class="code">say (a => 1, 'b', 'c').pairup.perl; # ("a" => 1, "b" => "c").list</pre>
<a name="t36.1.14"$class><h2>36.1.14 sub exit</h2></a>
<pre class="code">sub exit(Int() $status = 0)</pre>
<p>Exits the current process with return code <span class="code">$status </span> .</p>
TODO maybe find a better place to document &amp;exit
<a name="t37"><h1 class="title">37 class Array</h1></a> <p class="subtitle">Sequence of itemized values</p></a> <pre class="code">class Array is List { ... }</pre>
<p>An <span class="code">Array </span> is a <a href="">List</a> which forces all its elements to be scalar containers, which means you can assign to array elements.</p>
<a name="t37.1"$class><h1>37.1 Methods</h1></a>
<a name="t37.1.1"$class><h2>37.1.1 routine pop</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub pop(Array:D )
multi method pop(Array:D:)</pre>
<p>Usage:</p>
<pre class="code">pop ARRAY
ARRAY.pop</pre>
<p>Removes and returns the last item from the array. Fails for an empty array.</p>
<p>Example:</p>
<pre class="code">> my @foo = &lt;a b>;
a b
> @foo.pop;
b
> pop @foo
a
> pop @foo
Element popped from empty list</pre>
<a name="t37.1.2"$class><h2>37.1.2 routine push</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub push(Array:D, **@values) returns Array:D
multi method push(Array:D: **@values) returns Array:D</pre>
<p>Usage:</p>
<pre class="code">push ARRAY, VALUES
ARRAY.push(VALUES)
ARRAY.push: VALUES</pre>
<p>Adds the <span class="code">@values </span> to the end of the array, and returns the modified list. Fails for infinite arrays.</p>
<p>Example:</p>
<pre class="code">my @foo = &lt;a b c>;
@foo.push: 'd';
say @foo; # a b c d</pre>
<p>Note that <span class="code">push </span> 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:</p>
<pre class="code">my @a = &lt;a b c>;
my @b = &lt;d e f>;
@a.push: @b;
say @a.elems; # 4
say @a[3].join; # def</pre>
<p>Only if you supply multiple values as separate arguments to <span class="code">push </span> are multiple values added to the array:</p>
<pre class="code">my @a = '1';
my @b = &lt;a b>;
my @c = &lt;E F>;
@a.push: @b, @c;
say @a.elems; # 3</pre>
<p>See <a href="#method append">method append</a> for when you want to append multiple values that are stored in a single array.</p>
<a name="t37.1.3"$class><h2>37.1.3 method append</h2></a>
<p>Defined as</p>
<pre class="code">sub append(\array, elems)
multi method append(Array:D: \values)
multi method append(Array:D: **@values is raw)</pre>
<p>Usage:</p>
<pre class="code">ARRAY.append(LIST)
append ARRAY, LIST</pre>
<p>Appends the argument list to the array passed as first argument. This modifies the array in-place. Returns the modified array.</p>
<p>The difference to method <span class="code">push </span> is that with an array or list argument, <span class="code">append </span> appends several elements (one for each array or list element), whereas <span class="code">push </span> appends just one element.</p>
<a name="t37.1.4"$class><h2>37.1.4 routine shift</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub shift(Array:D )
multi method shift(Array:D:)</pre>
<p>Usage:</p>
<pre class="code">shift ARRAY
ARRAY.shift</pre>
<p>Removes and returns the first item from the array. Fails for an empty arrays.</p>
<p>Example:</p>
<pre class="code">my @foo = &lt;a b>;
say @foo.shift; # a
say @foo.shift; # b
say @foo.shift; # Element shifted from empty list</pre>
<a name="t37.1.5"$class><h2>37.1.5 routine unshift</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub unshift(Array:D, **@values) returns Array:D
multi method unshift(Array:D: **@values) returns Array:D</pre>
<p>Usage:</p>
<pre class="code">unshift ARRAY, VALUES
ARRAY.unshift(VALUES)
ARRAY.unshift: VALUES</pre>
<p>Adds the <span class="code">@values </span> to the start of the array, and returns the modified array. Fails if <span class="code">@values </span> is infinite.</p>
<p>Example:</p>
<pre class="code">my @foo = &lt;a b c>;
@foo.unshift: 1, 3 ... 11;
say @foo; # 1 3 5 7 9 11 a b c</pre>
<p>The notes in <a href="#method push">the documentation for method push</a> apply, regarding how many elements are added to the array.</p>
<p> <a href="">#method prepend</a> is the equivalent for adding multiple elements from one list or array.</p>
<a name="t37.1.6"$class><h2>37.1.6 method prepend</h2></a>
<p>Defined as</p>
<pre class="code">sub prepend(\array, elems)
multi method prepend(Array:D: \values)
multi method prepend(Array:D: **@values is raw)</pre>
<p>Usage:</p>
<pre class="code">ARRAY.prepend(LIST)
prepend ARRAY, LIST</pre>
<p>Adds the elements from <span class="code">LIST </span> to the front of the array, modifying it in-place.</p>
<a name="t37.1.7"$class><h2>37.1.7 routine splice</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub splice(@list, $start, $elems?, *@replacement) returns Array
multi method splice(Array:D $start, $elems?, *@replacement) returns Array</pre>
<p>Usage:</p>
<pre class="code">splice(ARRAY, START, ELEMS?, REPLACEMENT?)
ARRAY.splice(START, ELEMS?, REPLACEMENT?)</pre>
<p>Deletes <span class="code">$elems </span> elements starting from index <span class="code">$start </span> from the <span class="code">Array </span> , returns them and replaces them by <span class="code">@replacement </span> . If <span class="code">$elems </span> is omitted, all the elements starting from index <span class="code">$start </span> are deleted.</p>
<p>Example:</p>
<pre class="code">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</pre>
<a name="t38"><h1 class="title">38 role Associative</h1></a> <p class="subtitle">Object that supports looking up values by key</p></a> <pre class="code">role Associative { }</pre>
<p>A common role for types that support name-based lookup through <span class="code">postcircumfix:&lt;{ }> </span> , for example <a href="">Hash</a> and <a href="">Map</a> .</p>
<p>The <span class="code">% </span> sigil restricts variables to objects that do <span class="code">Associative </span> .</p>
<p>Associative does not provide any methods.</p>
<a name="t39"><h1 class="title">39 class Attribute</h1></a> <p class="subtitle">Member variable</p></a> <pre class="code">class Attribute { }</pre>
<p>In Perl 6 lingo, an <i>attribute</i> refers to a per-instance/object storage slot. An <span class="code">Attribute </span> is used to talk about classes' and roles' attributes on the meta level.</p>
<p>Normal usage of attributes does not require the user to use class Attribute explicitly.</p>
<p>The usual way to obtain an object of type <span class="code">Attribute </span> is by introspection:</p>
<pre class="code">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</pre>
<a name="t39.1"$class><h1>39.1 Methods</h1></a>
<a name="t39.1.1"$class><h2>39.1.1 method name</h2></a>
<p>Defined as:</p>
<pre class="code">method name(Attribute:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.name</pre>
<p>Returns the name of the attribute. Note that this is always the private name, so if an attribute is declared as <span class="code">has $.a </span> , the name returned is <span class="code">$!a </span> .</p>
<a name="t39.1.2"$class><h2>39.1.2 method package</h2></a>
<p>Defined as:</p>
<pre class="code">method package(Attribute:D:) returns Mu:U</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.package</pre>
<p>Returns the package (class/grammar/role) to which this attribute belongs.</p>
<a name="t39.1.3"$class><h2>39.1.3 method has_accessor</h2></a>
<p>Defined as:</p>
<pre class="code">method has_accessor(Attribute:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.has_accessor</pre>
<p>Returns <span class="code">True </span> if the attribute has a public accessor method.</p>
<a name="t39.1.4"$class><h2>39.1.4 method readonly</h2></a>
<p>Defined as:</p>
<pre class="code">method readonly(Attribute:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.readonly</pre>
<p>Returns <span class="code">True </span> for readonly attributes, which is the default. Returns <span class="code">False </span> for attributes marked as <span class="code">is rw </span> .</p>
<a name="t39.1.5"$class><h2>39.1.5 method type</h2></a>
<p>Defined as:</p>
<pre class="code">method type(Attribute:D:) returns Mu</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.type</pre>
<p>Returns the type constraint of the attribute.</p>
<a name="t39.1.6"$class><h2>39.1.6 method get_value</h2></a>
<p>Defined as:</p>
<pre class="code">method get_value(Attribute:D: Mu $instance)</pre>
<p>Usage:</p>
<pre class="code">my $val = ATTRIBUTE.get_value(OBJECT)</pre>
<p>Returns the value stored in this attribute of object <span class="code">$instance </span> .</p>
<p>Note that this method violates encapsulation of the object, and should be used with care. Here be dragons.</p>
<a name="t39.1.7"$class><h2>39.1.7 method set_value</h2></a>
<p>Defined as:</p>
<pre class="code">method set_value(Attribute:D: Mu $instance, Mu \new_val)</pre>
<p>Usage:</p>
<pre class="code">ATTRIBUTE.set_value(OBJECT, NEW_VALUE)</pre>
<p>Binds the value <span class="code">new_val </span> to this attribute of object <span class="code">$instance </span> .</p>
<p>Note that this method violates encapsulation of the object, and should be used with care. Here be dragons.</p>
<a name="t39.1.8"$class><h2>39.1.8 trait is required</h2></a>
<pre class="code">multi sub trait_mod:&lt;is> (Attribute $attr, :$required!)</pre>
<p>Marks an attribute as being required. If a value is not provided during object construction, an exception is thrown.</p>
<pre class="code">class Foo {
has $.bar is required;
has $.baz;
}
Foo.new(bar => 42) # works
Foo.new(baz => 42) # fails - bar is required</pre>
<p> <span class="code">is required </span> 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 <a href="">bless</a> .</p>
<a name="t39.1.9"$class><h2>39.1.9 trait is rw</h2></a>
<pre class="code">multi sub trait_mod:&lt;is> (Attribute:D $attr, :$rw!)</pre>
<p>Marks an attribute as read/write as opposed to the default <span class="code">readonly </span> . The default accessor for the attribute will return a writable value.</p>
<pre class="code">class Foo {
has $.bar is rw;
has $.baz;
}
my $foo = Foo.new;
$foo.bar = 42; # works
$foo.baz = 42; # fails</pre>
<a name="t40"><h1 class="title">40 class Backtrace</h1></a> <p class="subtitle">Snapshot of the dynamic call stack</p></a> <pre class="code">class Backtrace is List { ... }</pre>
<p>A backtrace shows the dynamic call stack, usually leading up to a point where an exception was thrown.</p>
<p>It is a List of <a href="">Backtrace::Frame</a> objects. Its default stringification excludes backtrace frames that are deemed unnecessary or confusing, for example routines like <span class="code">&amp;die </span> are hidden by default.</p>
<a name="t40.1"$class><h1>40.1 Methods</h1></a>
<a name="t40.1.1"$class><h2>40.1.1 method new</h2></a>
<p>Defined as:</p>
<pre class="code">proto method new(*@, *%) {*}
multi method new()</pre>
<p>Usage:</p>
<pre class="code">$backtrace = Backtrace.new</pre>
<p>Creates a new backtrace, using its calling location as the origin of the backtrace.</p>
<a name="t40.1.2"$class><h2>40.1.2 method Str</h2></a>
<p>Defined as:</p>
<pre class="code">multi method Str(Backtrace:D:) returns Str:D:</pre>
<p>Usage:</p>
<pre class="code">BACKTRACE.Str</pre>
<p>Returns a concise string representation of the backtrace, omitting routines marked as <span class="code">is hidden-from-backtrace </span> , and at the discretion of the implementor, also some routines from the setting.</p>
<a name="t40.1.3"$class><h2>40.1.3 method full</h2></a>
<p>Defined as:</p>
<pre class="code">multi method full(Backtrace:D:) returns Str:D:</pre>
<p>Usage:</p>
<pre class="code">BACKTRACE.full</pre>
<p>Returns a full string representation of the backtrace, including hidden frames, compiler-specific frames and those from the setting.</p>
<a name="t41"><h1 class="title">41 class Backtrace::Frame</h1></a> <p class="subtitle">Single frame of a </p></a> <pre class="code">class Backtrace::Frame { }</pre>
<p>A single backtrace frame. It identifies a location in the source code.</p>
<a name="t41.1"$class><h1>41.1 Methods</h1></a>
<a name="t41.1.1"$class><h2>41.1.1 method file</h2></a>
<p>Defined as:</p>
<pre class="code">method file(Backtrace::Frame:D) returns Str</pre>
<p>Usage:</p>
<pre class="code">FRAME.file</pre>
<p>Returns the file name.</p>
<a name="t41.1.2"$class><h2>41.1.2 method line</h2></a>
<p>Defined as:</p>
<pre class="code">method line(Backtrace::Frame:D) returns Int</pre>
<p>Usage:</p>
<pre class="code">FRAME.line</pre>
<p>Returns the line number (line numbers start to count from 1).</p>
<a name="t41.1.3"$class><h2>41.1.3 method code</h2></a>
<p>Defined as:</p>
<pre class="code">method code(Backtrace::Frame:D)</pre>
<p>Usage:</p>
<pre class="code">FRAME.code</pre>
<p>Returns the code object into which <span class="code">.file </span> and <span class="code">.line </span> point, if available.</p>
<a name="t41.1.4"$class><h2>41.1.4 method subname</h2></a>
<p>Defined as:</p>
<pre class="code">method subname(Backtrace::Frame:D) returns Str</pre>
<p>Usage:</p>
<pre class="code">FRAME.subname</pre>
<p>Returns the name of the enclosing subroutine.</p>
<a name="t41.1.5"$class><h2>41.1.5 method is-hidden</h2></a>
<p>Defined as:</p>
<pre class="code">method is-hidden(Backtrace::Frame:D) return Bool:D</pre>
<p>Usage:</p>
<pre class="code">FRAME.is-hidden</pre>
<p>Returns <span class="code">True </span> if the frame is marked as hidden with the <span class="code">is hidden-from-backtrace </span> trait.</p>
<a name="t41.1.6"$class><h2>41.1.6 method is-routine</h2></a>
<p>Defined as:</p>
<pre class="code">method is-routine(Backtrace::Frame:D) return Bool:D</pre>
<p>Usage:</p>
<pre class="code">FRAME.is-routine</pre>
<p>Return <span class="code">True </span> if the frame point into a routine (and not into a mere <a href="">Block</a> ).</p>
<a name="t41.1.7"$class><h2>41.1.7 method is-setting</h2></a>
<p>Defined as:</p>
<pre class="code">method is-setting(Backtrace::Frame:D) return Bool:D</pre>
<p>Usage:</p>
<pre class="code">FRAME.is-setting</pre>
<p>Returns <span class="code">True </span> if the frame is part of a setting.</p>
<a name="t42"><h1 class="title">42 class Bag</h1></a> <p class="subtitle">Immutable collection of distinct objects with integer weights</p></a> <pre class="code">class Bag does Baggy { }</pre>
<p>A <span class="code">Bag </span> 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 <i>mutable</i> bags, see <a href="">BagHash</a> instead.)</p>
<p> <span class="code">Bag </span> s are often used for performing weighted random selections - see <a href="method pick">.pick</a> and <a href="method roll">.roll</a> .</p>
<p>Objects/values of any type are allowed as bag elements. Within a <span class="code">Bag </span> , items that would compare positively with the <a href="">===</a> 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):</p>
<pre class="code">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
</pre>
<p> <span class="code">Bag </span> s can be treated as object hashes using the <span class="code">{ } </span> postcircumfix operator, which returns the corresponding integer weight for keys that are elements of the bag, and <span class="code">0 </span> for keys that aren't:</p>
<pre class="code">say $breakfast&lt;bacon>; # 1
say $breakfast&lt;spam>; # 4
say $breakfast&lt;sausage>; # 0</pre>
<a name="t42.1"$class><h1>42.1 Creating <span class="code">Bag </span> objects</h1></a>
<p> <span class="code">Bag </span> s can be composed using the <a href="#sub bag">bag</a> subroutine (or <span class="code">Bag.new </span> , for which it is a shorthand). Any positional parameters, regardless of their type, become elements of the bag:</p>
<pre class="code">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</pre>
<p>Alternatively, the <span class="code">.Bag </span> coercer (or its functional form, <span class="code">Bag() </span> ) can be called on an existing object to coerce it to a <span class="code">Bag </span> . 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:</p>
<pre class="code">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</pre>
<p>Furthermore, you can get a <span class="code">Bag </span> by using bag operators (see next section) on objects of other types such as <a href="">List</a> , which will internally call <span class="code">.Bag </span> 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:</p>
<pre class="code">say (1..5) (+) 4; # bag(1, 2, 3, 4(2), 5)</pre>
<a name="t42.2"$class><h1>42.2 Operators</h1></a>
<p>Perl 6 provides common set and bag operators, which can take <span class="code">Bag </span> s (or any other collections) as input, and return result as <span class="code">Bool </span> , <span class="code">Set </span> or <span class="code">Bag </span> values. For example:</p>
<pre class="code">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))
</pre>
<p>See <a href="">setbagmix#Set/Bag Operators</a> for a complete list of set and bag operators with detailed explanations.</p>
<a name="t42.3"$class><h1>42.3 Subroutines</h1></a>
<a name="t42.3.1"$class><h2>42.3.1 sub bag</h2></a>
<pre class="code">sub bag(*@args --> Bag)</pre>
<p>Creates a new <span class="code">Bag </span> from <span class="code">@args </span> .</p>
<a name="t42.4"$class><h1>42.4 See Also</h1></a>
<p> <a href="/language/setbagmix">Sets, Bags, and Mixes</a> </p>
<a name="t43"><h1 class="title">43 class BagHash</h1></a> <p class="subtitle">Mutable collection of distinct objects with integer weights</p></a> <pre class="code">class BagHash does Baggy { }</pre>
<p>A <span class="code">BagHash </span> 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 <i>immutable</i> bags, see <a href="">Bag</a> instead.)</p>
<p>Objects/values of any type are allowed as bag elements. Within a <span class="code">BagHash </span> , items that would compare positively with the <a href="">===</a> 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):</p>
<pre class="code">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
</pre>
<p> <span class="code">BagHash </span> es can be treated as object hashes using the <span class="code">{ } </span> postcircumfix operator, which returns the corresponding integer weight for keys that are elements of the bag, and <span class="code">0 </span> for keys that aren't. It can also be used to modify weights; Setting a weight to <span class="code">0 </span> automatically removes that element from the bag, and setting a weight to a positive number adds that element if it didn't already exist:</p>
<pre class="code">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
</pre>
<a name="t43.1"$class><h1>43.1 Creating <span class="code">BagHash </span> objects</h1></a>
<p> <span class="code">BagHash </span> es can be composed using <span class="code">BagHash.new </span> . Any positional parameters, regardless of their type, become elements of the bag:</p>
<pre class="code">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</pre>
<p>Alternatively, the <span class="code">.BagHash </span> coercer (or its functional form, <span class="code">BagHash() </span> ) can be called on an existing object to coerce it to a <span class="code">BagHash </span> . 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:</p>
<pre class="code">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</pre>
<a name="t43.2"$class><h1>43.2 Operators</h1></a>
<p>Perl 6 provides common set and bag operators, which can take <span class="code">BagHash </span> es (or any other collections) as input, and return result as <span class="code">Bool </span> , <span class="code">Set </span> or <span class="code">Bag </span> values. For example:</p>
<pre class="code">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))
</pre>
<p>See <a href="setbagmix#Set/Bag Operators">Set/Bag Operators</a> for a complete list of set and bag operators with detailed explanations.</p>
<a name="t43.3"$class><h1>43.3 See Also</h1></a>
<p> <a href="/language/setbagmix">Sets, Bags, and Mixes</a> </p>
<a name="t44"><h1 class="title">44 role Baggy</h1></a> <p class="subtitle">Collection of distinct weighted objects</p></a> <pre class="code">class Baggy does QuantHash { }</pre>
<p>A role for collections of weighted objects. See <a href="">Bag</a> , <a href="">BagHash</a> , and <a href="">Mixy</a> .</p>
<a name="t44.1"$class><h1>44.1 Methods</h1></a>
<a name="t44.1.1"$class><h2>44.1.1 method grab</h2></a>
TODO
<a name="t44.1.2"$class><h2>44.1.2 method grabpairs</h2></a>
TODO
<a name="t44.1.3"$class><h2>44.1.3 method pick</h2></a>
TODO
<a name="t44.1.4"$class><h2>44.1.4 method pickpairs</h2></a>
TODO
<a name="t44.1.5"$class><h2>44.1.5 method roll</h2></a>
TODO
<a name="t44.1.6"$class><h2>44.1.6 method classify-list</h2></a>
TODO
<a name="t44.1.7"$class><h2>44.1.7 method categorize-list</h2></a>
TODO
<a name="t44.1.8"$class><h2>44.1.8 method keys</h2></a>
TODO
<a name="t44.1.9"$class><h2>44.1.9 method values</h2></a>
TODO
<a name="t44.1.10"$class><h2>44.1.10 method kv</h2></a>
TODO
<a name="t44.1.11"$class><h2>44.1.11 method elems</h2></a>
TODO
<a name="t44.1.12"$class><h2>44.1.12 method total</h2></a>
TODO
<a name="t44.1.13"$class><h2>44.1.13 method ACCEPTS</h2></a>
TODO
<a name="t44.2"$class><h1>44.2 See Also</h1></a>
<p> <a href="/language/setbagmix">Sets, Bags, and Mixes</a> </p>
<a name="t45"><h1 class="title">45 role Blob</h1></a> <p class="subtitle">Immutable buffer for binary data ('Binary Large OBject')</p></a> <pre class="code">role Blob[::T = uint8] does Positional[T] does Stringy { }</pre>
<p>The <span class="code">Blob </span> role is an immutable interface to binary types, and offers a list-like interface to lists of integers, typically unsigned integers.</p>
<a name="t45.1"$class><h1>45.1 Methods</h1></a>
<a name="t45.1.1"$class><h2>45.1.1 method new</h2></a>
<p>Defined as:</p>
<pre class="code">method new(*@codes)</pre>
<p>Usage:</p>
<pre class="code">$blob = Blob.new(LIST)</pre>
<p>Creates a <span class="code">Blob </span> from a list of integers.</p>
<a name="t45.1.2"$class><h2>45.1.2 method Bool</h2></a>
<p>Defined as:</p>
<pre class="code">multi method Bool(Blob:D:)</pre>
<p>Usage:</p>
<pre class="code">BLOB.Bool</pre>
<p>Returns <span class="code">False </span> if and only if the buffer is empty.</p>
<a name="t45.1.3"$class><h2>45.1.3 method elems</h2></a>
<p>Defined as:</p>
<pre class="code">multi method elems(Blob:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">BLOB.elems</pre>
<p>Returns the number of elements of the buffer.</p>
<a name="t45.1.4"$class><h2>45.1.4 method decode</h2></a>
<p>Defined as:</p>
<pre class="code">multi method decode(Blob:D: Str:D $encoding = 'UTF-8') returns Str:D</pre>
<p>Usage:</p>
<pre class="code">BLOB.decode(ENCODING?)</pre>
<p>Applies an encoding to turn the blob into a <a href="/type/Str">Str</a> .</p>
<a name="t45.1.5"$class><h2>45.1.5 method subbuf</h2></a>
<p>Defined as:</p>
<pre class="code">method subbuf(Int $from, Int $len = self.elems) returns Blob:D
method subbuf(Range $range) returns Blob:D</pre>
<p>Usage:</p>
<pre class="code">BLOB.subbuf(FROM, LENGTH?)
BLOB.subbuf(RANGE)</pre>
<p>Extracts a part of the invocant buffer, starting from the index with elements <span class="code">$from </span> , and taking <span class="code">$len </span> elements (or less if the buffer is shorter), and creates a new buffer as the result.</p>
<pre class="code">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></pre>
<p>For convenience, also allows a <span class="code">Range </span> to be specified to indicate which part of the invocant buffer you would like:</p>
<pre class="code">say Blob.new(1..10).subbuf(2..5); # Blob:0x&lt;03 04 05 06></pre>
<a name="t45.1.6"$class><h2>45.1.6 method unpack</h2></a>
<p>Defined as:</p>
<pre class="code">method unpack(Blob:D: $template) returns List:D</pre>
<p>Usage:</p>
<pre class="code">BLOB.unpack(TEMPLATE)</pre>
<p>Extracts features from the blob according to the template string, and returns them as a list.</p>
<p>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 <span class="code">* </span> (which typically stands for "use up the rest of the Blob here"), or a positive integer (without a <span class="code">+ </span> ).</p>
<p>Whitespace between template units is ignored.</p>
<p>Examples of valid templates include <span class="code">"A4 C n*" </span> and <span class="code">"A*" </span> .</p>
<p>The following letters are recognized:</p>
<table>
<tr><th>Letter</th> <th>Meaning</th></tr>
<tr><td>A</td> <td>Extract a string, where each element of the Blob maps to a codepoint</td></tr>
<tr><td>a</td> <td>Same as A</td></tr>
<tr><td>C</td> <td>Extract an element from the blob as an integer</td></tr>
<tr><td>H</td> <td>Extracts a hex string</td></tr>
<tr><td>L</td> <td>Extracts four elements and returns them as a single unsigned integer</td></tr>
<tr><td>n</td> <td>Extracts two elements and combines them in "network" (big-endian) byte order into a single integer</td></tr>
<tr><td>N</td> <td>Extracts four elements and combines them in "network" (big-endian) byte order into a single integer</td></tr>
<tr><td>S</td> <td>Extracts two elements and returns them as a single unsigned integer</td></tr>
<tr><td>v</td> <td>Same as S</td></tr>
<tr><td>V</td> <td>Same as L</td></tr>
<tr><td>x</td> <td>Drop an element from the blob (that is, ignore it)</td></tr>
<tr><td>Z</td> <td>Same as A</td></tr>
</table> <a name="t45.1.7"$class><h2>45.1.7 sub pack</h2></a>
<pre class="code">sub pack(Str $template, *@items) returns Buf</pre>
<p>Packs the given items according to the template and returns a buffer containing the packed bytes.</p>
<p>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 <a href="/routine/unpack">unpack</a> .</p>
<a name="t46"><h1 class="title">46 class Block</h1></a> <p class="subtitle">Code object with its own lexical scope</p></a> <pre class="code">class Block is Code { }</pre>
<p>A <span class="code">Block </span> is a code object meant for small-scale code reuse. A block is created syntactically by a list of statements enclosed in curly braces.</p>
<p>Without an explicit signature or placeholder arguments, a block has <span class="code">$_ </span> as a positional argument</p>
<pre class="code">my $block = { uc $_; };
say $block.WHAT; # Block
say $block('hello'); # HELLO</pre>
<p>A block can have a signature between <span class="code">-> </span> or <span class="code">&lt;-> </span> and the block:</p>
<pre class="code">my $add = -> $a, $b { $a + $b };
say $add(38, 4); # 42</pre>
<p>If the signature is introduced with <span class="code">&lt;-> </span> , then the parameters are marked as <span class="code">rw </span> by default:</p>
<pre class="code">my $swap = &lt;-> $a, $b { ($a, $b) = ($b, $a) };
my ($a, $b) = (2, 4);
$swap($a, $b);
say $a; # 4</pre>
<p>Blocks that aren't of type <span class="code">Routine </span> (which is a subclass of <span class="code">Block </span> ) are transparent to <a href="">return</a> .</p>
<pre class="code">sub f() {
say &lt;a b c>.map: { return 42 };
# ^^^^^^ exits &amp;f, not just the block
}</pre>
<p>Bare blocks in sink context are automatically executed:</p>
<pre class="code">say 1;
{
say 2; # executed directly, not a Block object
}
say 3;</pre>
<a name="t47"><h1 class="title">47 enum Bool</h1></a> <p class="subtitle">Logical boolean</p></a> <pre class="code">enum Bool &lt;False True></pre>
<p>An enum for boolean true/false decisions.</p>
<a name="t47.1"$class><h1>47.1 Operators</h1></a>
<a name="t47.1.1"$class><h2>47.1.1 prefix ?</h2></a>
<pre class="code">multi sub prefix:&lt;?>(Mu) returns Bool:D</pre>
<p>Coerces its argument to <span class="code">Bool </span> .</p>
<a name="t47.1.2"$class><h2>47.1.2 prefix so</h2></a>
<pre class="code">multi sub prefix:&lt;so>(Mu) returns Bool:D</pre>
<p>Coerces its argument to <span class="code">Bool </span> , has looser precedence than <span class="code">prefix:&lt;?> </span> .</p>
<a name="t48"><h1 class="title">48 role Buf</h1></a> <p class="subtitle">Mutable buffer for binary data</p></a> <pre class="code">role Buf[::T] does Blob[T] { ... }</pre>
<p>A <span class="code">Buf </span> is a mutable sequence of (usually unsigned) integers.</p>
<pre class="code">my $b = Buf.new(1, 2, 3);
$b[1] = 42;</pre>
<a name="t49"><h1 class="title">49 role Callable</h1></a> <p class="subtitle">Invocable code object</p></a> <pre class="code">role Callable { ... }</pre>
<p>Role for objects which support calling them. It's used in <a href="">Block</a> , <a href="">Routine</a> , <a href="">Sub</a> , <a href="">Method</a> , <a href="">Submethod</a> and <a href="">Macro</a> types.</p>
<a name="t49.1"$class><h1>49.1 Methods</h1></a>
<a name="t49.1.1"$class><h2>49.1.1 method assuming</h2></a>
<pre class="code">method assuming (Callable:D $self: |primers)</pre>
<p>Returns a <span class="code">Callable </span> that implements the same behaviour as the original, but has the values passed to .assuming already bound to the corresponding parameters.</p>
<pre class="code">sub add(Int $x,Int $y) { $x + $y };
my &amp;add_to_5 = &amp;add.assuming(5);
say add_to_5(4); #-> 9</pre>
according to design docs it's Callable but in rakudo it's assuming is in Block
<a name="t50"><h1 class="title">50 class Capture</h1></a> <p class="subtitle">Argument list suitable for passing to a </p></a> <pre class="code">class Capture does Positional does Associative { }</pre>
<p>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.</p>
<p>When you call <span class="code">print $a, $b </span> , the <span class="code">$a, $b </span> part is a Capture.</p>
<p>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 <i>syntax</i> than a normal List. There are two easy ways to make a named argument: 1) use an unquoted key naming a parameter, followed by <span class="code">'= </span> '>, followed by the argument and 2) use a colon-pair literal named after the parameter:</p>
<pre class="code">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" => { ... }</pre>
<p>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 <span class="code">\ </span> . 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.</p>
<pre class="code">my $c = \42; # Capture with one positional parts
$c = \(1, 2, a => 'b'); # Capture with two positional and one named part</pre>
<p>To use such a Capture, you may use <span class="code">'|' </span> 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.</p>
<pre class="code">my $c = \(4,2,3);
reverse(|$c).say; # 3 2 4
sort(5,|$c).say; # 2 3 4 5</pre>
<p>Inside a Signature, a Capture may be created by prefixing a sigilless parameter with a vertical bar <span class="code">| </span> . This packs the remainder of the argument list into that parameter.</p>
<pre class="code">f(1, 2, 3, a => 4, b => 5);
sub f($a, |c) {
# c is \(2, 3, a => 4, b => 5)
}</pre>
<p>Note that Captures are still Lists in that they may contain containers, not just values:</p>
<pre class="code">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</pre>
<a name="t50.1"$class><h1>50.1 Methods</h1></a>
<a name="t50.1.1"$class><h2>50.1.1 method list</h2></a>
<p>Defined as:</p>
<pre class="code">method list(Capture:D:) returns Positional</pre>
<p>Usage:</p>
<pre class="code">CAPTURE.list</pre>
<p>Returns the positional part of the Capture.</p>
<a name="t50.1.2"$class><h2>50.1.2 method hash</h2></a>
<p>Defined as:</p>
<pre class="code">method hash(Capture:D:) returns Associative</pre>
<p>Usage:</p>
<pre class="code">CAPTURE.hash</pre>
<p>Returns the named/hash part of the Capture.</p>
<a name="t50.1.3"$class><h2>50.1.3 method elems</h2></a>
<p>Defined as:</p>
<pre class="code">method elems(Capture:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">CAPTURE.elems</pre>
<p>Returns the number of positional elements in the Capture.</p>
<a name="t51"><h1 class="title">51 class Channel</h1></a> <p class="subtitle">Thread-safe queue for sending values from producers to consumers</p></a> <pre class="code">class Channel { ... }</pre>
<p>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.</p>
<pre class="code">my $c = Channel.new;
await (^10).map: {
start {
my $r = rand;
sleep $r;
$c.send($r);
}
}
$c.close;
say $c.list;</pre>
<a name="t51.1"$class><h1>51.1 Methods</h1></a>
<a name="t51.1.1"$class><h2>51.1.1 method send</h2></a>
<p>Defined as:</p>
<pre class="code">method send(Channel:D: \item)</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.send(ITEM)</pre>
<p>Enqueues an item into the channel. Throws an exception of type <a href="">X::Channel::SendOnClosed</a> if the channel has been closed already.</p>
<a name="t51.1.2"$class><h2>51.1.2 method receive</h2></a>
<p>Defined as:</p>
<pre class="code">method receive(Channel:D:)</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.receive</pre>
<p>Receives and removes an item from the channel. It blocks if no item is present, waiting for a <span class="code">send </span> from another thread.</p>
<p>Throws an exception of type <a href="">X::Channel::ReceiveOnClosed</a> if the channel has been closed, and the last item has been removed already, or if <span class="code">close </span> is called while <span class="code">receive </span> is waiting for an item to arrive.</p>
<p>If the channel has been marked as erratic with method <span class="code">fail </span> , and the last item has been removed, throws the argument that was given to <span class="code">fail </span> as an exception.</p>
<p>See method <span class="code">poll </span> for a non-blocking version that won't throw exceptions.</p>
<a name="t51.1.3"$class><h2>51.1.3 method poll</h2></a>
<p>Defined as:</p>
<pre class="code">method poll(Channel:D:)</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.poll</pre>
<p>Receives and removes an item from the channel. If no item is present, returns <span class="code">Nil </span> instead of waiting.</p>
<p>See method <span class="code">receive </span> for a blocking version that properly responds to channel closing and failure.</p>
<a name="t51.1.4"$class><h2>51.1.4 method close</h2></a>
<p>Defined as:</p>
<pre class="code">method close(Channel:D:)</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.close</pre>
<p>Close the channel. This makes subsequent <span class="code">send </span> calls die, as well as a <span class="code">receive </span> call past the end of the queue, and is a prerequisite for <span class="code">list </span> to terminate.</p>
<a name="t51.1.5"$class><h2>51.1.5 method list</h2></a>
<p>Defined as:</p>
<pre class="code">method list(Channel:D:) returns List:D</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.list</pre>
<p>Returns a list of all remaining items in the queue, and removes them from the channel. This can only terminate once <span class="code">close </span> has been called.</p>
<a name="t51.1.6"$class><h2>51.1.6 method closed</h2></a>
<p>Defined as:</p>
<pre class="code">method closed(Channel:D:) returns Promise:D</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.closed</pre>
<p>Returns a promise that will be kept once the channel is closed by a call to method <span class="code">close </span> .</p>
<a name="t51.1.7"$class><h2>51.1.7 method fail</h2></a>
<p>Defined as:</p>
<pre class="code">method fail(Channel:D: $error)</pre>
<p>Usage:</p>
<pre class="code">CHANNEL.fail</pre>
<p>Closes the channel (that is, makes subsequent <span class="code">send </span> calls die), and enqueues the error as the final element in the channel. Method <span class="code">receive </span> will throw the error as an exception.</p>
<a name="t51.1.8"$class><h2>51.1.8 sub await</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub await(Channel:D)
multi sub await(*@)</pre>
<p>Usage:</p>
<pre class="code">await(CHANNEL)
await(CHANNELS)</pre>
<p>Waits until all of one or more channels has a value available, and returns those values (it calls <span class="code">.receive </span> on the channel). Also works with <a href="/type/Promise">promises</a> .</p>
<a name="t52"><h1 class="title">52 Code</h1></a> <p class="subtitle">Code object</p></a> <pre class="code">class Code is Any does Callable { ... }</pre>
<p> <span class="code">Code </span> 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 <span class="code">Code </span> , most code objects (such as those resulting from blocks, subroutines or methods) will be of some subclass of <span class="code">Code </span> .</p>
<a name="t52.1"$class><h1>52.1 Methods</h1></a>
<a name="t52.1.1"$class><h2>52.1.1 method ACCEPTS</h2></a>
<pre class="code">multi method ACCEPTS(Code:D: Mu $topic)</pre>
<p>Usually calls the code object and passes <span class="code">$topic </span> as an argument. However, when called on a code object that takes no arguments, the code object is invoked with no arguments and <span class="code">$topic </span> is dropped. The result of the call is returned.</p>
<a name="t52.1.2"$class><h2>52.1.2 method arity</h2></a>
<p>Defined as:</p>
<pre class="code">method arity(Code:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">CODE.arity</pre>
<p>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 <span class="code">Signature </span> do not contribute, nor do named parameters.</p>
<pre class="code">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</pre>
<a name="t52.1.3"$class><h2>52.1.3 method count</h2></a>
<p>Defined as:</p>
<pre class="code">method count(Code:D:) returns Real:D</pre>
<p>Usage:</p>
<pre class="code">CODE.count</pre>
<p>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), <span class="code">count </span> will return <span class="code">Inf </span> . Named parameters do not contribute.</p>
<pre class="code">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</pre>
<a name="t52.1.4"$class><h2>52.1.4 method signature</h2></a>
<p>Defined as:</p>
<pre class="code">multi method signature(Code:D:) returns Signature:D</pre>
<p>Usage:</p>
<pre class="code">CODE.signature</pre>
<p>Returns the <a href=""> <span class="code">Signature </span> </a> object for this code object, which describes its parameters.</p>
<a name="t52.1.5"$class><h2>52.1.5 method Str</h2></a>
<p>Defined as:</p>
<pre class="code">multi method Str(Code:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">CODE.Str</pre>
<p>Returns the name of the code object.</p>
<pre class="code">sub marine() { }
say ~&amp;marine; # marine</pre>
<a name="t52.1.6"$class><h2>52.1.6 method file</h2></a>
<p>Defined as:</p>
<pre class="code">method file(Code:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">CODE.Str</pre>
<p>Returns the name of the file in which the code object was declared.</p>
<pre class="code">say &amp;infix:&lt;+>.file;</pre>
<a name="t52.1.7"$class><h2>52.1.7 method line</h2></a>
<p>Defined as</p>
<pre class="code">method line(Code:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">CODE.Int</pre>
<p>Returns the line number in which the code object was declared.</p>
<a name="t53"><h1 class="title">53 class Complex</h1></a> <p class="subtitle">Complex number</p></a> <pre class="code">class Complex is Cool does Numeric { ... }</pre>
<p>Represents a number in the complex plane.</p>
<p>Complex objects are immutable.</p>
<a name="t53.1"$class><h1>53.1 Operators</h1></a>
<a name="t53.1.1"$class><h2>53.1.1 postfix i</h2></a>
<p>Adding a trailing <span class="code">i </span> to a number literal makes it a Complex, for example:</p>
<pre class="code">2i; # same as Complex.new(0, 2);
1-2e3i; # same as Complex.new(1, -2e3);</pre>
<a name="t53.2"$class><h1>53.2 Methods</h1></a>
<a name="t53.2.1"$class><h2>53.2.1 method new</h2></a>
<p>Defined as:</p>
<pre class="code">proto method new(*@, *%) {*} returns Complex:D
multi method new(Real $re, Real $im) returns Complex:D</pre>
<p>Usage:</p>
<pre class="code">$complex = Complex.new(REAL, IMAGINARY)</pre>
<p>Creates a new <span class="code">Complex </span> object from real and imaginary parts.</p>
<a name="t53.2.2"$class><h2>53.2.2 method re</h2></a>
<p>Defined as:</p>
<pre class="code">method re(Complex:D:) returns Real:D</pre>
<p>Usage:</p>
<pre class="code">COMPLEX.re</pre>
<p>Returns the real part of the complex number.</p>
<a name="t53.2.3"$class><h2>53.2.3 method im</h2></a>
<p>Defined as:</p>
<pre class="code">method im(Complex:D:) returns Real:D</pre>
<p>Usage:</p>
<pre class="code">COMPLEX.im</pre>
<p>Returns the imaginary part of the complex number.</p>
<a name="t53.2.4"$class><h2>53.2.4 method isNaN</h2></a>
<p>Defined as:</p>
<pre class="code">method isNaN(Complex:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">COMPLEX.isNaN</pre>
<p>Returns true if the real or imaginary part is <span class="code">NaN </span> (not a number).</p>
<a name="t53.2.5"$class><h2>53.2.5 method polar</h2></a>
<p>Defined as:</p>
<pre class="code">method polar(Complex:D:) returns Positional:D</pre>
<p>Usage:</p>
<pre class="code">COMPLEX.polar</pre>
<p>Returns a two-element list of the polar coordinates for this value, i.e. magnitude and angle in radians.</p>
<a name="t54"><h1 class="title">54 Cool</h1></a> <p class="subtitle">Value that can be treated as a string or number interchangeably</p></a> <pre class="code">class Cool is Any { }</pre>
<p> <span class="code">Cool </span> , also known as the <b>C</b> onvenient <b>OO</b> <b>L</b> oop, is a base class for strings, numbers and other built-in classes that you are supposed to use mostly interchangeably.</p>
<p>Methods in <span class="code">Cool </span> coerce the invocant to a more specific type, and then call the same method on that type. For example both <a href="">Int</a> and <a href="">Str</a> inherit from <span class="code">Cool </span> , and calling method <span class="code">substr </span> on an <span class="code">Int </span> converts the integer to <span class="code">Str </span> first.</p>
<pre class="code">123.substr(1, 1); # '2', same as 123.Str.substr(1, 1)</pre>
<p>The following built-in types inherit from <span class="code">Cool </span> : <a href="">Array</a> <a href="">Backtrace</a> <a href="">Bag</a> <a href="">Baggy</a> <a href="">Bool</a> <a href="">Complex</a> <a href="">Cool</a> <a href="">Duration</a> <a href="">Enumeration</a> <a href="">Map</a> <a href="">FatRat</a> <a href="">Hash</a> <a href="">Instant</a> <a href="">Int</a> <a href="">List</a> <a href="">Match</a> <a href="">Nil</a> <a href="">Num</a> <a href="">Numeric</a> <a href="">Range</a> <a href="">Real</a> <a href="">Seq</a> <a href="">Set</a> <a href="">Stash</a> <a href="">Str</a> <a href="">Stringy</a> </p>
<p>The following table summarizes the methods that <span class="code">Cool </span> provides, and what type they coerce to:</p>
<table>
<tr><th>method</th> <th>coercion type</th></tr>
<tr><td>abs</td> <td>Numeric</td></tr>
<tr><td>conj</td> <td>Numeric</td></tr>
<tr><td>sqrt</td> <td>Numeric</td></tr>
<tr><td>sign</td> <td>Real</td></tr>
<tr><td>rand</td> <td>Numeric</td></tr>
<tr><td>sin</td> <td>Numeric</td></tr>
<tr><td>asin</td> <td>Numeric</td></tr>
<tr><td>cos</td> <td>Numeric</td></tr>
<tr><td>acos</td> <td>Numeric</td></tr>
<tr><td>tan</td> <td>Numeric</td></tr>
<tr><td>atan</td> <td>Numeric</td></tr>
<tr><td>atan2</td> <td>Numeric</td></tr>
<tr><td>sec</td> <td>Numeric</td></tr>
<tr><td>asec</td> <td>Numeric</td></tr>
<tr><td>cosec</td> <td>Numeric</td></tr>
<tr><td>acosec</td> <td>Numeric</td></tr>
<tr><td>cotan</td> <td>Numeric</td></tr>
<tr><td>acotan</td> <td>Numeric</td></tr>
<tr><td>sinh</td> <td>Numeric</td></tr>
<tr><td>asinh</td> <td>Numeric</td></tr>
<tr><td>cosh</td> <td>Numeric</td></tr>
<tr><td>acosh</td> <td>Numeric</td></tr>
<tr><td>sech</td> <td>Numeric</td></tr>
<tr><td>asech</td> <td>Numeric</td></tr>
<tr><td>asech</td> <td>Numeric</td></tr>
<tr><td>cosech</td> <td>Numeric</td></tr>
<tr><td>acotanh</td> <td>Numeric</td></tr>
<tr><td>cis</td> <td>Numeric</td></tr>
<tr><td>log</td> <td>Numeric</td></tr>
<tr><td>exp</td> <td>Numeric</td></tr>
<tr><td>roots</td> <td>Numeric</td></tr>
<tr><td>log10</td> <td>Numeric</td></tr>
<tr><td>unpolar</td> <td>Numeric</td></tr>
<tr><td>round</td> <td>Numeric</td></tr>
<tr><td>floor</td> <td>Numeric</td></tr>
<tr><td>ceiling</td> <td>Numeric</td></tr>
<tr><td>truncate</td> <td>Numeric</td></tr>
<tr><td>chr</td> <td>Int</td></tr>
<tr><td>ord</td> <td>Str</td></tr>
<tr><td>chars</td> <td>Str</td></tr>
<tr><td>fmt</td> <td>Str</td></tr>
<tr><td>uniname</td> <td>Str</td></tr>
<tr><td>unival</td> <td>Str</td></tr>
<tr><td>univals</td> <td>Str</td></tr>
<tr><td>uniprop</td> <td>Str</td></tr>
<tr><td>uniprop-int</td> <td>Str</td></tr>
<tr><td>uniprop-str</td> <td>Str</td></tr>
<tr><td>uniprop-bool</td> <td>Str</td></tr>
<tr><td>unimatch</td> <td>Str</td></tr>
<tr><td>uc</td> <td>Str</td></tr>
<tr><td>lc</td> <td>Str</td></tr>
<tr><td>capitalize</td> <td>Str</td></tr>
<tr><td>fc</td> <td>Str</td></tr>
<tr><td>flip</td> <td>Str</td></tr>
<tr><td>trans</td> <td>Str</td></tr>
<tr><td>index</td> <td>Str</td></tr>
<tr><td>rindex</td> <td>Str</td></tr>
<tr><td>ords</td> <td>Str</td></tr>
<tr><td>split</td> <td>Str</td></tr>
<tr><td>match</td> <td>Str</td></tr>
<tr><td>comb</td> <td>Str</td></tr>
<tr><td>subst</td> <td>Str</td></tr>
<tr><td>sprintf</td> <td>Str</td></tr>
<tr><td>printf</td> <td>Str</td></tr>
<tr><td>samecase</td> <td>Str</td></tr>
<tr><td>trim</td> <td>Str</td></tr>
<tr><td>trim-leading</td> <td>Str</td></tr>
<tr><td>trim-trailing</td> <td>Str</td></tr>
<tr><td>EVAL</td> <td>Str</td></tr>
</table> <a name="t54.1"$class><h1>54.1 Methods</h1></a>
<a name="t54.1.1"$class><h2>54.1.1 routine abs</h2></a>
<p>Defined as:</p>
<pre class="code">sub abs(Numeric() $x)
method abs()</pre>
<p>Usage:</p>
<pre class="code">abs NUMERIC
NUMERIC.abs</pre>
<p>Coerces the invocant (or in the sub form, the argument) to <a href="/type/Numeric">Numeric</a> and returns the absolute value (that is, a non-negative number).</p>
<pre class="code">say (-2).abs; # 2
say abs "6+8i"; # 10</pre>
<a name="t54.1.2"$class><h2>54.1.2 method conj</h2></a>
<p>Defined as:</p>
<pre class="code">method conj()</pre>
<p>Usage:</p>
<pre class="code">NUMERIC.conj</pre>
<p>Coerces the invocant to <a href="/type/Numeric">Numeric</a> and returns the <a href="/type/Complex">complex</a> conjugate (that is, the number with the sign of the imaginary part negated).</p>
<pre class="code">say (1+2i).conj; # 1-2i</pre>
<a name="t54.1.3"$class><h2>54.1.3 routine sqrt</h2></a>
<p>Defined as:</p>
<pre class="code">sub sqrt(Numeric(Cool) $x)
method sqrt()</pre>
<p>Usage:</p>
<pre class="code">sqrt NUMERIC
NUMERIC.sqrt</pre>
<p>Coerces the invocant to <a href="/type/Numeric">Numeric</a> (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.</p>
<pre class="code">say 4.sqrt; # 2
say sqrt(2); # 1.4142135623731</pre>
<a name="t54.1.4"$class><h2>54.1.4 method sign</h2></a>
<p>Defined as:</p>
<pre class="code">method sign()</pre>
<p>Usage:</p>
<pre class="code">NUMERIC.sign</pre>
<p>Coerces the invocant to <a href="/type/Real">Numeric</a> and returns its sign, that is, 0 if the number is 0, 1 for positive and -1 for negative values.</p>
<pre class="code">say 6.sign; # 1
say (-6).sign; # -1
say "0".sign; # 0</pre>
<a name="t54.1.5"$class><h2>54.1.5 method rand</h2></a>
<p>Defined as:</p>
<pre class="code">method rand()</pre>
<p>Usage: NUMERIC.rand</p>
<p>Coerces the invocant to <a href="/type/Num">Num</a> and returns a pseudo-random value between zero and the number.</p>
<pre class="code">say 1e5.rand; # 33128.495184283</pre>
<a name="t54.1.6"$class><h2>54.1.6 routine sin</h2></a>
<p>Defined as:</p>
<pre class="code">sub sin(Numeric(Cool))
method sin()</pre>
<p>Usage:</p>
<pre class="code">sin NUMERIC
NUMERIC.sin</pre>
<p>Coerces the invocant (or in the sub firm, the argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Sine">sine</a> .</p>
<pre class="code">say sin(0); # 0
say sin(pi/4); # 0.707106781186547
say sin(pi/2); # 1</pre>
<p>Note that Perl 6 is no computer algebra system, so <span class="code">sin(pi) </span> typically does not produce an exact 0, but rather a very small <a href="/type/Num">floating-point number</a> .</p>
<a name="t54.1.7"$class><h2>54.1.7 routine asin</h2></a>
<p>Defined as:</p>
<pre class="code">sub asin(Numeric(Cool))
method asin()</pre>
<p>Usage:</p>
<pre class="code">asin NUMERIC
NUMERIC.asin</pre>
<p>Coerces the invocant (or in the sub firm, the argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-sine</a> in radians.</p>
<pre class="code">say 0.1.asin; # 0.10016742116156</pre>
<a name="t54.1.8"$class><h2>54.1.8 routine cos</h2></a>
<p>Defined as:</p>
<pre class="code">sub cos(Numeric(Cool))
method cos()</pre>
<p>Usage:</p>
<pre class="code">cos NUMERIC
NUMERIC.cos</pre>
<p>Coerces the invocant (or in sub form, the argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Cosine">cosine</a> .</p>
<pre class="code">say 0.cos; # 1
say pi.cos; # -1
say cos(pi/2); # 6.12323399573677e-17</pre>
<a name="t54.1.9"$class><h2>54.1.9 routine acos</h2></a>
<p>Defined as:</p>
<pre class="code">sub acos(Numeric(Cool))
method acos()</pre>
<p>Usage:</p>
<pre class="code">acos NUMERIC
NUMERIC.acos</pre>
<p>Coerces the invocant (or in sub form, the argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-cosine</a> in radians.</p>
<a name="t54.1.10"$class><h2>54.1.10 routine tan</h2></a>
<p>Defined as:</p>
<pre class="code">sub tan(Numeric(Cool))
method tan()</pre>
<p>Usage:</p>
<pre class="code">tan NUMERIC
NUMERIC.tan</pre>
<p>Coerces the invocant (or in sub form, the argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Tangent">tangens</a> .</p>
<a name="t54.1.11"$class><h2>54.1.11 routine atan</h2></a>
<p>Defined as:</p>
<pre class="code">sub atan(Numeric(Cool))
method atan()</pre>
<p>Usage:</p>
<pre class="code">atan NUMERIC
NUMERIC.atan</pre>
<p>Coerces the invocant (or in sub form, the argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-tangens</a> in radians.</p>
<a name="t54.1.12"$class><h2>54.1.12 routine atan2</h2></a>
<p>Defined as:</p>
<pre class="code">sub atan2(Numeric() $x, Numeric() $y = 1e0)
method atan2($y = 1e0)</pre>
<p>Usage:</p>
<pre class="code">atan2 NUMERIC, NUMERIC?
NUMERIC.atan2(NUMERIC?)</pre>
<p>Coerces the arguments (including the invocant in the method form) to <a href="/type/Numeric">Numeric</a> , and returns their two-argument <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-tangens</a> in radians.</p>
<a name="t54.1.13"$class><h2>54.1.13 method sec</h2></a>
<p>Defined as:</p>
<pre class="code">sub sec(Numeric(Cool))
method sec()</pre>
<p>Usage:</p>
<pre class="code">sec NUMERIC
NUMERIC.sec</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions">secans</a> , that is, the reciprocal of its cosine.</p>
<a name="t54.1.14"$class><h2>54.1.14 routine asec</h2></a>
<p>Defined as:</p>
<pre class="code">sub asec(Numeric(Cool))
method asec()</pre>
<p>Usage:</p>
<pre class="code">asec NUMERIC
NUMERIC.asec</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-secans</a> in radians.</p>
<a name="t54.1.15"$class><h2>54.1.15 routine cosec</h2></a>
<p>Defined as:</p>
<pre class="code">sub cosec(Numeric(Cool))
method cosec()</pre>
<p>Usage:</p>
<pre class="code">cosec NUMERIC
NUMERIC.cosec</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions">cosecans</a> , that is, the reciprocal of its sine.</p>
<a name="t54.1.16"$class><h2>54.1.16 routine acosec</h2></a>
<p>Defined as:</p>
<pre class="code">sub acosec(Numeric(Cool))
method acosec()</pre>
<p>Usage:</p>
<pre class="code">acosec NUMERIC
NUMERIC.acosec</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-cosecans</a> in radians.</p>
<a name="t54.1.17"$class><h2>54.1.17 routine cotan</h2></a>
<p>Defined as:</p>
<pre class="code">sub cotan(Numeric(Cool))
method cotan()</pre>
<p>Usage:</p>
<pre class="code">cotan NUMERIC
NUMERIC.cotan</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , interprets it as radians, returns its <a href="https://en.wikipedia.org/wiki/Trigonometric_functions#Reciprocal_functions">cotangens</a> , that is, the reciprocal of its tangens.</p>
<a name="t54.1.18"$class><h2>54.1.18 routine acotan</h2></a>
<p>Defined as:</p>
<pre class="code">sub acotan(Numeric(Cool))
method acotan()</pre>
<p>Usage:</p>
<pre class="code">acotan NUMERIC
NUMERIC.acotan</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_trigonometric_functions">arc-cotangens</a> in radians.</p>
<a name="t54.1.19"$class><h2>54.1.19 routine sinh</h2></a>
<p>Defined as:</p>
<pre class="code">sub sinh(Numeric(Cool))
method sinh()</pre>
<p>Usage:</p>
<pre class="code">sinh NUMERIC
NUMERIC.sinh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Sine hyperbolicus</a> .</p>
<a name="t54.1.20"$class><h2>54.1.20 routine asinh</h2></a>
<p>Defined as:</p>
<pre class="code">sub asinh(Numeric(Cool))
method asinh()</pre>
<p>Usage:</p>
<pre class="code">asinh NUMERIC
NUMERIC.asinh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_hyperbolic_function">Inverse Sine hyperbolicus</a> .</p>
<a name="t54.1.21"$class><h2>54.1.21 routine cosh</h2></a>
<p>Defined as:</p>
<pre class="code">sub cosh(Numeric(Cool))
method cosh()</pre>
<p>Usage:</p>
<pre class="code">cosh NUMERIC
NUMERIC.cosh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Cosine hyperbolicus</a> .</p>
<a name="t54.1.22"$class><h2>54.1.22 routine acosh</h2></a>
<p>Defined as:</p>
<pre class="code">sub acosh(Numeric(Cool))
method acosh()</pre>
<p>Usage:</p>
<pre class="code">acosh NUMERIC
NUMERIC.acosh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_hyperbolic_function">Inverse Cosine hyperbolicus</a> .</p>
<a name="t54.1.23"$class><h2>54.1.23 routine tanh</h2></a>
<p>Defined as:</p>
<pre class="code">sub tanh(Numeric(Cool))
method tanh()</pre>
<p>Usage:</p>
<pre class="code">tanh NUMERIC
NUMERIC.tanh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Hyperbolic_function">Tangens hyperbolicus</a> .</p>
<a name="t54.1.24"$class><h2>54.1.24 routine atanh</h2></a>
<p>Defined as:</p>
<pre class="code">sub atanh(Numeric(Cool))
method atanh()</pre>
<p>Usage:</p>
<pre class="code">atanh NUMERIC
NUMERIC.atanh</pre>
<p>Coerces the invocant (or in method form, its argument) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Inverse_hyperbolic_function">Inverse tangens hyperbolicus</a> .</p>
<a name="t54.1.25"$class><h2>54.1.25 routine log</h2></a>
<p>Defined as:</p>
<p>Defined as:</p>
<pre class="code">multi sub log(Numeric(Cool) $number, Numeric(Cool) $base?)
multi method log(Cool:D: Cool:D $base?)</pre>
<p>Usage:</p>
<pre class="code">log NUMERIC, NUMERIC?
NUMERIC.log(NUMERIC?)</pre>
<p>Coerces the arguments (including the invocant in the method form) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Logarithm">Logarithm</a> to base <span class="code">$base </span> , or to base <span class="code">e </span> (Euler's Number) if no base was supplied ( <a href="https://en.wikipedia.org/wiki/Natural_logarithm">Natural logarithm</a> .</p>
<pre class="code">say (e*e).log; # 2</pre>
<a name="t54.1.26"$class><h2>54.1.26 routine log10</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub log10(Cool(Numeric))
multi method log10()</pre>
<p>Usage:</p>
<pre class="code">log10 NUMERIC
NUMERIC.log10</pre>
<p>Coerces the invocant (or in the sub form, the invocant) to <a href="/type/Numeric">Numeric</a> , and returns its <a href="https://en.wikipedia.org/wiki/Logarithm">Logarithm</a> to base 10, that is, a number that approximately produces the original number when raised to the power of 10.</p>
<pre class="code">say log10(1001); # 3.00043407747932</pre>
<a name="t54.1.27"$class><h2>54.1.27 method exp</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub exp(Cool:D $pow, Cool:D $base?)
multi method exp(Cool:D: Cool:D $base?)</pre>
<p>Usage:</p>
<pre class="code">exp NUMERIC, NUMERIC?
NUMERIC.exp(NUMERIC?)</pre>
<p>Coerces the arguments (including the invocant in the method from) to <a href="/type/Numeric">Numeric</a> , and returns <span class="code">$base </span> raised to the power of the first number. If no <span class="code">$base </span> is supplied, <span class="code">e </span> (Euler's Number) is used.</p>
<pre class="code">say 0.exp; # 1
say 1.exp; # 2.71828182845905
say 10.exp; # 22026.4657948067</pre>
<a name="t54.1.28"$class><h2>54.1.28 routine round</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub round(Numeric(Cool))
multi method round(Cool:D: $unit = 1)</pre>
<p>Usage:</p>
<pre class="code">round NUMERIC, NUMERIC?
NUMERIC.round(NUMERIC?)</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and rounds it to the unit of <span class="code">$unit </span> . If <span class="code">$unit </span> is 1, rounds to the nearest integer.</p>
<pre class="code">say 1.7.round; # 2
say 1.07.round(0.1); # 1.1
say 21.round(10); # 20</pre>
<a name="t54.1.29"$class><h2>54.1.29 routine floor</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub floor(Numeric(Cool))
multi method floor</pre>
<p>Usage:</p>
<pre class="code">floor NUMERIC
NUMERIC.floor</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and rounds it downwards to the nearest integer.</p>
<pre class="code">say "1.99".floor; # 1
say "-1.9".floor; # -2
say 0.floor; # 0</pre>
<a name="t54.1.30"$class><h2>54.1.30 routine ceiling</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub ceiling(Numeric(Cool))
multi method ceiling</pre>
<p>Usage:</p>
<pre class="code">ceiling NUMERIC
NUMERIC.ceiling</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and rounds it upwards to the nearest integer.</p>
<pre class="code">say "1".ceiling; # 1
say "-0.9".ceiling; # 0
say "42.1".ceiling; # 43</pre>
<a name="t54.1.31"$class><h2>54.1.31 routine truncate</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub truncate(Numeric(Cool))
multi method truncate()</pre>
<p>Usage:</p>
<pre class="code">truncate NUMERIC
NUMERIC.truncate</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Numeric">Numeric</a> , and rounds it towards zero.</p>
<pre class="code">say 1.2.truncate # 1
say truncate -1.2; # -1</pre>
<a name="t54.1.32"$class><h2>54.1.32 routine ord</h2></a>
<p>Defined as:</p>
<pre class="code">sub ord(Str(Cool))
method ord()</pre>
<p>Usage:</p>
<pre class="code">ord STRING
STRING.ord</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the <a href="https://en.wikipedia.org/wiki/Code_point">Unicode code point</a> , number of the code point.</p>
<pre class="code">say 'a'.ord; # 65</pre>
<p>The inverse operation is <a href="#method chr">chr</a> .</p>
<p>Mnemonic: returns an ordinal number</p>
<a name="t54.1.33"$class><h2>54.1.33 routine chr</h2></a>
<p>Defined as:</p>
<pre class="code">sub chr(Int(Cool))
method chr()</pre>
<p>Usage:</p>
<pre class="code">chr INTEGER
INTEGER.chr</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Int">Int</a> , interprets it as a <a href="https://en.wikipedia.org/wiki/Code_point">Unicode code points</a> , and returns a <a href="/type/Str">string</a> made of that code point.</p>
<pre class="code">say '65'.chr; # A</pre>
<p>The inverse operation is <a href="#method ord">ord</a> .</p>
<p>Mnemonic: turns an integer into a <i>char</i> acter.</p>
<a name="t54.1.34"$class><h2>54.1.34 routine chars</h2></a>
<p>Defined as:</p>
<pre class="code">sub chars(Str(Cool))
method chars()</pre>
<p>Usage:</p>
<pre class="code">chars STRING
STRING.chars</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the number of characters in the string. Characters should actually be grapheme clusters, though current implementations erroneously count codepoints instead.</p>
<pre class="code">say 'møp'.chars; # 3</pre>
<a name="t54.1.35"$class><h2>54.1.35 routine codes</h2></a>
<p>Defined as:</p>
<pre class="code">sub codes(Str(Cool))
method codes()</pre>
<p>Usage:</p>
<pre class="code">codes STRING
STRING.codes</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the number of <a href="https://en.wikipedia.org/wiki/Code_point">Unicode code points</a> .</p>
<pre class="code">say 'møp'.codes; # 3</pre>
<a name="t54.1.36"$class><h2>54.1.36 routine flip</h2></a>
<p>Defined as:</p>
<pre class="code">sub flip(Str(Cool))
method flip()</pre>
<p>Usage:</p>
<pre class="code">flip STRING
STRING.flip</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns a reversed version.</p>
<pre class="code">say 421.flip; # 124</pre>
<a name="t54.1.37"$class><h2>54.1.37 routine trim</h2></a>
<p>Defined as:</p>
<pre class="code">sub trim(Str(Cool))
method trim()</pre>
<p>Usage:</p>
<pre class="code">trim STRING
STRING.trim</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the string with both leading and trailing whitespace stripped.</p>
<pre class="code">my $stripped = ' abc '.trim;
say "&lt;$stripped>"; # &lt;abc></pre>
<a name="t54.1.38"$class><h2>54.1.38 routine trim-leading</h2></a>
<p>Defined as:</p>
<pre class="code">sub trim-leading(Str(Cool))
method trim-leading()</pre>
<p>Usage:</p>
<pre class="code">trim-leading STRING
STRING.trim-leading</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the string with leading whitespace stripped.</p>
<pre class="code">my $stripped = ' abc '.trim-leading;
say "&lt;$stripped>"; # &lt;abc ></pre>
<a name="t54.1.39"$class><h2>54.1.39 routine trim-trailing</h2></a>
<p>Defined as:</p>
<pre class="code">sub trim-trailing(Str(Cool))
method trim-trailing()</pre>
<p>Usage:</p>
<pre class="code">trim-trailing STRING
STRING.trim-trailing</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns the string with trailing whitespace stripped.</p>
<pre class="code">my $stripped = ' abc '.trim-trailing;
say "&lt;$stripped>"; # &lt; abc></pre>
<a name="t54.1.40"$class><h2>54.1.40 routine lc</h2></a>
<p>Defined as:</p>
<pre class="code">sub lc(Str(Cool))
method lc()</pre>
<p>Usage:</p>
<pre class="code">lc STRING
STRING.lc</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns it case-folded to lower case.</p>
<pre class="code">say "ABC".lc; # abc</pre>
<a name="t54.1.41"$class><h2>54.1.41 routine uc</h2></a>
<p>Defined as:</p>
<pre class="code">sub uc(Str(Cool))
method uc()</pre>
<p>Usage:</p>
<pre class="code">uc STRING
STRING.uc</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns it case-folded to upper case (capital letters).</p>
<pre class="code">say "Abc".uc; # ABC</pre>
<a name="t54.1.42"$class><h2>54.1.42 routine tc</h2></a>
<p>Defined as:</p>
<pre class="code">sub tc(Str(Cool))
method tc()</pre>
<p>Usage:</p>
<pre class="code">tc STRING
STRING.tc</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns it with the first letter case-folded to title case (or where not available, upper case).</p>
<pre class="code">say "abC".tc; # AbC</pre>
<a name="t54.1.43"$class><h2>54.1.43 routine tclc</h2></a>
<p>Defined as:</p>
<pre class="code">sub tclc(Str(Cool))
method tclc()</pre>
<p>Usage:</p>
<pre class="code">tclc STRING
STRING.tclc</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , 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..</p>
<pre class="code">say 'abC'.tclc; # Abc</pre>
<a name="t54.1.44"$class><h2>54.1.44 routine wordcase</h2></a>
<p>Defined as:</p>
<pre class="code">sub wordcase(Str(Cool) $input, :&amp;filter = &amp;tclc, Mu :$where = True)
method wordcase(:&amp;filter = &amp;tclc, Mu :$where = True)</pre>
<p>Usage:</p>
<pre class="code">wordcase STRING, FILTER?, WHERE?
STRING.wordcase(FILTER?, WHERE?)</pre>
<p>Coerces the invocant (or in sub form, the first argument) to <a href="/type/Str">Str</a> , and filters each word that smart-matches against <span class="code">$where </span> through the <span class="code">&amp;filter </span> . With the default filter (first character to upper case, rest to lower) and matcher (which accepts everything), this title-cases each word:</p>
<pre class="code">say "perl 6 programming".wordcase; # Perl 6 Programming</pre>
<p>With a matcher:</p>
<pre class="code">say "have fun working on perl".wordcase(:where({ .chars > 3 }));
# Have fun Working on Perl</pre>
<p>With a customer filter too:</p>
<pre class="code">say "have fun working on perl".wordcase(:filter(&amp;uc), :where({ .chars > 3 }));
# HAVE fun WORKING on PERL</pre>
<a name="t54.1.45"$class><h2>54.1.45 routine uniname</h2></a>
<p>Defined as:</p>
<pre class="code">sub uniname(Str(Cool) returns Str
method uniname() returns Str</pre>
<p>Usage:</p>
<pre class="code">uniname STRING
STRING.uniname</pre>
<p>Interprets the invocant / first argument as a <a href="">/type/Str</a> , and returns the Unicode codepoint name of the first character.</p>
<a name="t54.1.46"$class><h2>54.1.46 routine chop</h2></a>
<p>Defined as:</p>
<pre class="code">sub chop(Str(Cool))
method chop()</pre>
<p>Usage:</p>
<pre class="code">chop STRING
STRING.chop</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns it with the last character removed.</p>
<pre class="code">say 'perl'.chop; # per</pre>
<a name="t54.1.47"$class><h2>54.1.47 routine chomp</h2></a>
<p>Defined as:</p>
<pre class="code">sub chomp(Str(Cool))
method chomp()</pre>
<p>Usage:</p>
<pre class="code">chomp STRING
STRING.chomp</pre>
<p>Coerces the invocant (or in sub form, its argument) to <a href="/type/Str">Str</a> , and returns it with the last character removed, if it is a logical newline.</p>
<pre class="code">say 'ab'.chomp.chars; # 2
say "a\n".chomp.chars; # 1</pre>
<a name="t54.1.48"$class><h2>54.1.48 routine substr</h2></a>
<p>Defined as:</p>
<pre class="code">sub substr(Str(Cool) $str, $from, $chars?)
method substr($from, $chars?)</pre>
<p>Usage:</p>
<pre class="code">substr(STRING, FROM, CHARS?)
STRING.substr(FROM, CHARS?)</pre>
<p>Coerces the invocant (or in the sub form, the first argument) to <a href="/type/Str">Str</a> , and returns the string starting from offset <span class="code">$from </span> . If <span class="code">$chars </span> is supplied, at most <span class="code">$chars </span> characters are returned.</p>
<pre class="code">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</pre>
<p>If the <span class="code">$from </span> parameter is a <a href="/type/Callable">Callable</a> , it is called with the number of chars in the string as argument. This allows easy indexing relative to the end:</p>
<pre class="code">say 20151224.substr(*-2); # 24</pre>
<a name="t54.1.49"$class><h2>54.1.49 routine ords</h2></a>
<p>Defined as:</p>
<pre class="code">sub ords(Str(Cool) $str)
method ords()</pre>
<p>Usage:</p>
<pre class="code">ords(STRING)
STRING.ords</pre>
<p>Coerces the invocant (or in the sub form, the first argument) to <a href="/type/Str">Str</a> , and returns a list of Unicode codepoints for each character.</p>
<pre class="code">say "Perl 6".ords; # 80 101 114 108 32 54
say ords 10; # 49 48</pre>
<p>This is the list-returning version of <a href="">ord</a> . The inverse operation in <a href="">chrs</a> .</p>
<a name="t54.1.50"$class><h2>54.1.50 routine chrs</h2></a>
<p>Defined as:</p>
<pre class="code">sub chrs(*@codepoints) return Str:D
method chrs()</pre>
<p>Usage:</p>
<pre class="code">chrs LIST
LIST.chrs</pre>
<p>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.</p>
<pre class="code">say &lt;80 101 114 108 32 54>.chrs; # Perl 6</pre>
<p>This is the list-input version of <a href="">chr</a> . The inverse operation is <a href="">ords</a> .</p>
<a name="t54.1.51"$class><h2>54.1.51 routine split</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub split( Str:D $delimiter, Str(Cool) $input, $limit = Inf, :$all)
multi sub split(Regex:D $delimiter, Str(Cool) $input, $limit = Inf, :$all)
multi method split( Str:D $delimiter, $limit = Inf, :$all)
multi method split(Regex:D $delimiter, $limit = Inf, :$all)</pre>
<p>Usage:</p>
<pre class="code">split DELIMITER, STRING, LIMIT?, :all?
split /PATTERN/, STRING, LIMIT?, :all?
STRING.split(DELIMITER, LIMIT?, :all?)
STRING.split(/PATTERN/, LIMIT?, :all?)</pre>
<p>Coerces the invocant (or in the sub form, the second argument) to <a href="/type/Str">Str</a> , and splits it into pieces based on delimiters found in the string.</p>
<p>If <span class="code">$delimiter </span> is a string, it is searched for literally and not treated as a regex.</p>
<p>If the named parameter <span class="code">:all </span> is passed, the matches from <span class="code">$delimiter </span> are included in the result list.</p>
<p>Note that unlike in Perl 5, empty chunks are not removed from the result list. If you want that behavior, consider using <a href="">comb</a> instead.</p>
<pre class="code">say split(';', "a;b;c").perl; # ("a", "b", "c").list
say split(';', "a;b;c", :all).perl; # ("a", ";", "b", ";", "c").list
say split(';', "a;b;c", 2).perl; # ("a", "b;c").list
say split(';', "a;b;c", 2, :all).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</pre>
<a name="t54.1.52"$class><h2>54.1.52 routine lines</h2></a>
<p>Defined as:</p>
<pre class="code">sub lines(Str(Cool))
method lines()</pre>
<p>Usage:</p>
<pre class="code">lines STRING
STRING.lines</pre>
<p>Coerces the invocant (and in sub form, the argument) to <a href="/type/Str">Str</a> , decomposes it into lines (with the newline characters stripped), and returns the list of lines.</p>
<pre class="code">say lines("a\nb\n").join('|'); # a|b
say "some\nmore\nlines".lines.elems; # 3</pre>
<p>This method can be used as part of an <span class="code">IO::Path </span> to process a file line-by-line, since <span class="code">IO::Path </span> objects inherit from <span class="code">Cool </span> , e.g.:</p>
<pre class="code">for 'huge-csv'.IO.lines -> $line {
# Do something with $line
}
# or if you'll be processing later
my @lines = 'huge-csv'.IO.lines;
</pre>
<a name="t54.1.53"$class><h2>54.1.53 method words</h2></a>
<p>Defined as:</p>
<pre class="code">method words(Int() $limit)</pre>
<p>Usage:</p>
<pre class="code">INTEGER.words(LIMIT?)</pre>
<p>Coerces the invocant to <a href="/type/Str">Str</a> , and returns a list of words that make up the string (and if <span class="code">$limit </span> is supplied, only the first <span class="code">$limit </span> words).</p>
<pre class="code">say 'The quick brown fox'.words.join('|'); # The|quick|brown|fox
say 'The quick brown fox'.words(2).join('|'); # The|quick</pre>
<p>Only whitespace counts as word boundaries</p>
<pre class="code">say "isn't, can't".words.join('|'); # isn't,|can't</pre>
<a name="t54.1.54"$class><h2>54.1.54 routine comb</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub comb(Regex $matcher, Str(Cool) $input, $limit = *) returns List:D
multi method comb(Regex $matcher, $limit = *) returns List:D</pre>
<p>Usage:</p>
<pre class="code">comb /PATTERN/, STRING, LIMIT?
STRING.comb(/PATTERN/, LIMIT?)</pre>
<p>Returns all (or if supplied, at most <span class="code">$limit </span> ) matches of the invocant (method form) or the second argument (sub form) against the <a href="/type/Regex">Regex</a> as a list of strings.</p>
<pre class="code">say "6 or 12".comb(/\d+/).join(", "); # 6, 12</pre>
<a name="t54.1.55"$class><h2>54.1.55 routine index</h2></a>
<p>Defined as:</p>
<pre class="code">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</pre>
<p>Usage:</p>
<pre class="code">index STRING, NEEDLE, STARTPOS?
STRING.comb(NEEDLE, STARTPOS?)</pre>
<p>Coerces the first two arguments (in method form, also counting the invocant) to <a href="/type/Str">Str</a> , and searches for <span class="code">$needle </span> in the string starting from <span class="code">$startpos </span> . It returns the offset into the string where <span class="code">$needle </span> was found, and an undefined value if it was not found.</p>
<p>See <a href="/type/Str#routine index">the documentation in type Str</a> for examples.</p>
<a name="t54.1.56"$class><h2>54.1.56 routine rindex</h2></a>
<p>Defined as:</p>
<pre class="code">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)</pre>
<p>Usage:</p>
<pre class="code">rindex STRING, NEEDLE, STARTPOS?
STRING.rindex(NEEDLE, STARTPOS?)</pre>
<p>Coerces the first two arguments (including the invocant in method form) to <a href="/type/Str">Str</a> and <span class="code">$startpos </span> to <a href="/type/Int">Int</a> , and returns the last position of <span class="code">$needle </span> in <span class="code">$haystack </span> not after <span class="code">$startpos </span> . Returns an undefined value if <span class="code">$needle </span> wasn't found.</p>
<p>See <a href="/type/Str#routine rindex">the documentation in type Str</a> for examples.</p>
<a name="t54.1.57"$class><h2>54.1.57 routine roots</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub roots(Numeric(Cool) $x, Int(Cool) $n)
multi method roots(Int(Cool) $n)</pre>
<p>Usage:</p>
<pre class="code">roots NUMERIC, INTEGER
NUMERIC.roots(INTEGER)</pre>
<p>Coerces the first argument (and in method form, the invocant) to <a href="/type/Numeric">Numeric</a> and the second ( <span class="code">$n </span> ) to <a href="/type/Int">Int</a> , and produces a list of <span class="code">$n </span> <a href="/type/Complex">Complex</a> <span class="code">$n </span> -roots, which means numbers that, raised to the <span class="code">$n </span> th power, approximately produce the original number.</p>
<p>For example</p>
<pre class="code">my $original = 16;
my @roots = $original.roots(4);
say @roots;
for @roots -> $r {
say abs($r ** 4 - $original);
}
</pre>
<p>produces this output:</p>
<pre class="code">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
</pre>
<a name="t54.1.58"$class><h2>54.1.58 method IO</h2></a>
<p>Defined as:</p>
<pre class="code">method IO() returns IO::Path:D</pre>
<p>Usage:</p>
<pre class="code">EXPR.IO</pre>
<p>Coerces the invocant to <a href="">IO::Path</a> .</p>
<pre class="code">.say for '.'.IO.dir; # gives a directory listing</pre>
<a name="t54.1.59"$class><h2>54.1.59 routine EVAL</h2></a>
<p>Defined as:</p>
<pre class="code">sub EVAL(Cool $code, :$lang = { ... })</pre>
<p>Usage:</p>
<pre class="code">EVAL "say 'hello'";</pre>
<p>Coerces the invocant to <a href="">Str</a> .</p>
<p>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 <span class="code">MONKEY-SEE-NO-EVAL </span> pragma:</p>
<pre class="code">use MONKEY-SEE-NO-EVAL;
EVAL "say { 5 + 5 }";</pre>
<p> <span class="code">EVAL </span> is also a gateway for executing code in other languages:</p>
<pre class="code">EVAL "use v5.20; say 'Hello from perl5!'", :lang&lt;Perl5>;</pre>
TODO: sech, asech, cosech, acosech, cotanh, acotanh, cis,
unpolar, fmt, substr-rw, trans,
match, subst, sprintf, printf, samecase
<a name="t55"><h1 class="title">55 class CurrentThreadScheduler</h1></a> <p class="subtitle">Scheduler that blockingly executes code on the current thread</p></a> <pre class="code">class CurrentThreadScheduler does Scheduler { ... }</pre>
<p> <span class="code">CurrentThreadScheduler </span> executes tasks on the current threads. This means that <a href="">#method cue</a> blocks until the code has finished executing.</p>
<a name="t56"><h1 class="title">56 class Cursor</h1></a> <p class="subtitle">Internal state of the regex engine during parsing</p></a> <pre class="code">class Cursor { }</pre>
<p>A <span class="code">Cursor </span> 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.</p>
<p>A user-space program usually doesn't need to deal with <span class="code">Cursor </span> objects, just with their relatives, <a href="">Match</a> objects.</p>
<a name="t57"><h1 class="title">57 class Date</h1></a> <p class="subtitle">Calendar date</p></a> <pre class="code">class Date { }</pre>
<p>A <span class="code">Date </span> is an immutable object identifying a day in the Gregorian calendar.</p>
<p>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 <span class="code">==, &lt;, &lt;=, >, >=, != </span> . Their stringification in <span class="code">YYYY-MM-DD </span> format means that comparing them with the string operators <span class="code">eq, lt, le </span> etc. also gives the right result.</p>
<p> <span class="code">Date.today </span> creates an object the current day according to the system clock.</p>
<pre class="code">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</pre>
<a name="t57.1"$class><h1>57.1 Methods</h1></a>
<a name="t57.1.1"$class><h2>57.1.1 method new</h2></a>
<p>Defined as:</p>
<pre class="code">proto method new() {*}
multi method new($year, $month, $day) 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</pre>
<p>Usage:</p>
<pre class="code">$date = Date.new(YEAR, MONTH, DAY)
$date = Date.new(year => YEAR, month => MONTH?, day => DAY?)
$date = Date.new(YYYY-MM-DD)
$date = Date.new(now)
$date = Date.new(DateTime.now)</pre>
<p>Creates a new <span class="code">Date </span> object, either from a triple of (year, month, day) that can be coerced to integers, or from a string of the form <span class="code">YYYY-MM-DD </span> ( <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> ), or from an Instant or DateTime object.</p>
<a name="t57.1.2"$class><h2>57.1.2 method today</h2></a>
<p>Defined as:</p>
<pre class="code">method today() returns Date:D</pre>
<p>Usage:</p>
<pre class="code">Date.today</pre>
<p>Returns a <span class="code">Date </span> object for the current day.</p>
<a name="t57.1.3"$class><h2>57.1.3 method later</h2></a>
<p>Defined as:</p>
<pre class="code">method later(Date:D: *%unit)</pre>
<p>Usage:</p>
<pre class="code">DATE.later(DELTA)</pre>
<p>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.</p>
<p>Allowed units are <span class="code">day </span> , <span class="code">days </span> , <span class="code">week </span> , <span class="code">weeks </span> , <span class="code">month </span> , <span class="code">months </span> , <span class="code">year </span> , <span class="code">years </span> .</p>
<p>Please note that the special ":2nd" named parameter syntax can be a compact and self-documenting way of specifying the delta</p>
<pre class="code">say Date.new('2015-12-24').later(:2years);
# 2017-12-24</pre>
<p>Since addition of several different time units is not commutative, only one unit may be passed.</p>
<pre class="code">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</pre>
<p>Negative offsets are allowed, though <a href="">#method earlier</a> is more idiomatic for that.</p>
<a name="t57.1.4"$class><h2>57.1.4 method earlier</h2></a>
<p>Defined as:</p>
<pre class="code">method earlier(Date:D: *%unit)</pre>
<p>Usage:</p>
<pre class="code">DATE.earlier(DELTA)</pre>
<p>Returns a Date object based on the current one, but with a date delta towards the past applied. See <a href="">#method later</a> for usage.</p>
<a name="t57.1.5"$class><h2>57.1.5 method truncated-to</h2></a>
<p>Defined as:</p>
<pre class="code">method truncated-to(Date:D: Cool $unit)</pre>
<p>Usage:</p>
<pre class="code">DATE.truncated-to(UNIT)</pre>
<p>Returns a <span class="code">Date </span> truncated to the first day of its year, month or week. For example</p>
<pre class="code">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)</pre>
<a name="t57.1.6"$class><h2>57.1.6 method succ</h2></a>
<p>Defined as:</p>
<pre class="code">method succ(Date:D:) returns Date:D</pre>
<p>Usage:</p>
<pre class="code">DATE.succ</pre>
<p>Returns a <span class="code">Date </span> of the following day.</p>
<a name="t57.1.7"$class><h2>57.1.7 method pred</h2></a>
<p>Defined as:</p>
<pre class="code">method pred(Date:D:) return Date:D</pre>
<p>Usage:</p>
<pre class="code">DATE.pred</pre>
<p>Returns a <span class="code">Date </span> of the previous day.</p>
<a name="t57.1.8"$class><h2>57.1.8 method Str</h2></a>
<p>Defined as:</p>
<pre class="code">multi method Str(Date:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">DATE.Str</pre>
<p>Returns the date in <span class="code">YYYY-MM-DD </span> format ( <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> )</p>
<a name="t57.1.9"$class><h2>57.1.9 method gist</h2></a>
<p>Defined as:</p>
<pre class="code">multi method gist(Date:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">DATE.gist</pre>
<p>Returns the date in <span class="code">YYYY-MM-DD </span> format ( <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> )</p>
<a name="t58"><h1 class="title">58 class DateTime</h1></a> <p class="subtitle">Calendar date with time</p></a> <pre class="code">class DateTime does Dateish { ... }</pre>
<p>For handling points in civil time, a <span class="code">DateTime </span> object stores year, month, day, hour, minute (all <a href="/type/Int">Int</a> ), second (potentially fractional) and a time zone.</p>
<p>It provides methods for calculating with date and time.</p>
<p> <span class="code">DateTime </span> methods are immutable; if you are tempted to modify one, create a modified copy instead.</p>
<p>Time zones are handled as <a href="/type/Int">Integers</a> in <b>seconds</b> offset from UTC, not by time zone name.</p>
<pre class="code">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
</pre>
<a name="t58.1"$class><h1>58.1 Methods</h1></a>
<a name="t58.1.1"$class><h2>58.1.1 method new</h2></a>
<p>Defined as:</p>
<pre class="code">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, :&amp;formatter)
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)</pre>
<p>Usage:</p>
<pre class="code">$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?)
$datetime = DateTime.new(INSTANT, TIMEZONE?, FORMATTER?)
$datetime = DateTime.new(TIMESTAMP, TIMEZONE?, FORMATTER?)
$datetime = DateTime.new(FORMAT, TIMEZONE?, FORMATTER?)</pre>
<p>Creates a new <span class="code">DateTime </span> object. One option for creating a new DateTime object is from the components (year, month, day, hour, ...) separately. Another is to pass a <a href="/type/Date">Date</a> object for the date component, and specify the time component-wise. Yet another is to obtain the time from an <a href="/type/Instant">Instant</a> , and only supply the time zone and formatter. Or instead of an Instant you can supply an <a href="/type/Int">Int</a> as a UNIX timestamp.</p>
<p>You can also supply a <span class="code">Str|/type/Str </span> formatted in ISO 8601 timestamp notation or as a full <a href="http://tools.ietf.org/html/rfc3339">RFC 3339</a> date and time. Strings should be formatted as <span class="code">yyyy-mm-ddThh:mm::ssZ </span> or <span class="code">yyyy-mm-ddThh:mm:ss+0100 </span> . We are somewhat less restrictive than the ISO 8601 standard, as we allow Unicode digits and mixing of condensed and extended time formats.</p>
<p>An invalid input string throws an exception of type <a href="">X::Temporal::InvalidFormat</a> . If you supply a string that includes a time zone and supply the <span class="code">timezone </span> named argument, an exception of type <a href="">X::DateTime:TimezoneClash</a> is thrown.</p>
<a name="t58.1.2"$class><h2>58.1.2 method now</h2></a>
<p>Defined as:</p>
<pre class="code">method now(:$timezone=$*TZ, &amp;formatter) returns DateTime:D</pre>
<p>Usage:</p>
<pre class="code">DateTime.now</pre>
<p>Creates a new <span class="code">DateTime </span> object from the current system time, optionally with a different timezone than the default attached.</p>
<a name="t58.1.3"$class><h2>58.1.3 method clone</h2></a>
<p>Defined as:</p>
<pre class="code">method clone(:$year, :$month, :$day, :$hour, :$minute, :$second,
:$timezone, :&amp;formatter)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.clone(YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, TIMEZONE,
FORMATTER)</pre>
<p>Creates a new <span class="code">DateTime </span> object based on the invocant, but with the given arguments overriding the values from the invocant.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00Z').clone(hour => 0);
# 2015-12-24T00:23:00Z</pre>
<p>Note that this can lead to invalid dates in some circumstances:</p>
<pre class="code">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</pre>
<a name="t58.1.4"$class><h2>58.1.4 method hour</h2></a>
<p>Defined as:</p>
<pre class="code">method hour(DateTime:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.hour</pre>
<p>Returns the hour component.</p>
<pre class="code">say DateTime.new('2012-02-29T12:34:56Z').hour; # 12</pre>
<a name="t58.1.5"$class><h2>58.1.5 method minute</h2></a>
<p>Defined as:</p>
<pre class="code">method minute(DateTime:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.minute</pre>
<p>Returns the minute component.</p>
<pre class="code">say DateTime.new('2012-02-29T12:34:56Z').minute; # 34</pre>
<a name="t58.1.6"$class><h2>58.1.6 method second</h2></a>
<p>Defined as:</p>
<pre class="code">method second(DateTime:D:)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.second</pre>
<p>Returns the second component, including potentially fractional seconds.</p>
<pre class="code">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</pre>
<a name="t58.1.7"$class><h2>58.1.7 method whole-second</h2></a>
<p>Defined as:</p>
<pre class="code">method whole-second(DateTime:D:)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.whole-second</pre>
<p>Returns the second component, rounded down to an <a href="/type/Int">Int</a> .</p>
<pre class="code">say DateTime.new('2012-02-29T12:34:56.789Z').whole-second; # 56</pre>
<a name="t58.1.8"$class><h2>58.1.8 method timezone</h2></a>
<p>Defined as:</p>
<pre class="code">method timezone(DateTime:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.timezone</pre>
<p>Returns the time zone in seconds as an offset from UTC.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00+0200').timezone; # 7200</pre>
<a name="t58.1.9"$class><h2>58.1.9 method offset</h2></a>
<p>Defined as:</p>
<pre class="code">method offset(DateTime:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.offset</pre>
<p>Returns the time zone in seconds as an offset from UTC. This is an alias for <a href="">#method timezone</a> .</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00+0200').offset; # 7200</pre>
<a name="t58.1.10"$class><h2>58.1.10 method offset-in-minutes</h2></a>
<p>Defined as:</p>
<pre class="code">method offset-in-minutes(DateTime:D:) returns Real:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.offset-in-minutes</pre>
<p>Returns the time zone in minutes as an offset from UTC.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00+0200').offset-in-minutes; # 120</pre>
<a name="t58.1.11"$class><h2>58.1.11 method offset-in-hours</h2></a>
<p>Defined as:</p>
<pre class="code">method offset-in-hours(DateTime:D:) returns Real:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.offset-in-hours</pre>
<p>Returns the time zone in hours as an offset from UTC.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00+0200').offset-in-hours; # 2</pre>
<a name="t58.1.12"$class><h2>58.1.12 method formatter</h2></a>
<p>Defined as:</p>
<pre class="code">method formatter(DateTime:D:)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.formatter</pre>
<p>Returns the formatting function which is used for conversion to <a href="/type/Str">Str</a> . If none was provided at object construction, a default formatter is used which produces an ISO 8601 timestamp. In that case the method will return a Callable type object.</p>
<p>The formatting function is called by <a href="">#method Str</a> with the invocant as its only argument.</p>
<a name="t58.1.13"$class><h2>58.1.13 method Str</h2></a>
<p>Defined as:</p>
<pre class="code">method Str(DateTime:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.Str</pre>
<p>Returns a string representation of the invocant, as done by <a href="#method formatter">the formatter</a> .</p>
<a name="t58.1.14"$class><h2>58.1.14 method Instant</h2></a>
<p>Defined as:</p>
<pre class="code">method Instant(DateTime:D:) returns Instant:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.Instant</pre>
<p>Returns an <a href="/type/Instant">Instant</a> object based on the invocant.</p>
<a name="t58.1.15"$class><h2>58.1.15 method posix</h2></a>
<p>Defined as:</p>
<pre class="code">method posix(DateTime:D: $ignore-timezone = False) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.posix</pre>
<p>Returns the date and time as a POSIX/UNIX timestamp.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00Z').posix; # 1450959780</pre>
<a name="t58.1.16"$class><h2>58.1.16 method later</h2></a>
<p>Defined as:</p>
<pre class="code">method later(DateTime:D: *%unit)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.later(DELTA)</pre>
<p>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.</p>
<p>Allowed units are <span class="code">second </span> , <span class="code">seconds </span> , <span class="code">minute </span> , <span class="code">minutes </span> , <span class="code">hour </span> , <span class="code">hours </span> , <span class="code">day </span> , <span class="code">days </span> , <span class="code">week </span> , <span class="code">weeks </span> , <span class="code">month </span> , <span class="code">months </span> , <span class="code">year </span> , <span class="code">years </span> .</p>
<p>Please note that the special ":2nd" named parameter syntax can be a compact and self-documenting way of specifying the delta</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00Z').later(:2years);
# 2017-12-24T12:23:00Z</pre>
<p>Since addition of several different time units is not commutative, only one unit may be passed.</p>
<pre class="code">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</pre>
<p>Negative offsets are allowed, though <a href="">#method earlier</a> is more idiomatic for that.</p>
<a name="t58.1.17"$class><h2>58.1.17 method earlier</h2></a>
<p>Defined as:</p>
<pre class="code">method earlier(DateTime:D: *%unit)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.earlier(DELTA)</pre>
<p>Returns a DateTime object based on the current one, but with a time delta towards the past applied. See <a href="">#method later</a> for usage.</p>
<a name="t58.1.18"$class><h2>58.1.18 method truncated-to</h2></a>
<p>Defined as:</p>
<pre class="code">method truncated-to(DateTime:D: Cool $unit)</pre>
<p>Usage:</p>
<pre class="code">DATETIME.truncated-to(UNIT)</pre>
<p>Returns a copy of the invocant, with everything smaller than the specified unit truncated to the smallest possible value.</p>
<pre class="code">my $d = DateTime.new("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</pre>
<p>DateTimes with fractional seconds can be truncated to whole seconds with <span class="code">.truncated-to('second') </span> .</p>
<a name="t58.1.19"$class><h2>58.1.19 method Date</h2></a>
<p>Defined as:</p>
<pre class="code">method Date(DateTime:D:) returns Date:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.Date</pre>
<p>Returns a <a href="/type/Date">Date</a> object for this DateTime object. Which obviously lacks the time component.</p>
<a name="t58.1.20"$class><h2>58.1.20 method utc</h2></a>
<p>Defined as:</p>
<pre class="code">method utc(DateTime:D:) returns DateTime:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.utc</pre>
<p>Returns a DateTime object for the same time, but in time zone UTC.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00+0200').utc"; # 2015-12-24T10:23:00Z</pre>
<a name="t58.1.21"$class><h2>58.1.21 method in-timezone</h2></a>
<p>Defined as:</p>
<pre class="code">method in-timezone(DateTime:D: $timezone = 0) returns DateTime:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.in-timezone</pre>
<p>Returns a DateTime object for the same time, but in the specified time zone.</p>
<pre class="code">say DateTime.new('2015-12-24T12:23:00Z').in-timezone(3600 + 1800);
# 2015-12-24T13:53:00+0130</pre>
<a name="t58.1.22"$class><h2>58.1.22 method local</h2></a>
<p>Defined as:</p>
<pre class="code">method local(DateTime:D:) returns DateTime:D</pre>
<p>Usage:</p>
<pre class="code">DATETIME.local</pre>
<p>Returns a DateTime object for the same time, but in the local time zone ( <span class="code">$*TZ </span> ).</p>
<pre class="code">my $*TZ = -3600;
say DateTime.new('2015-12-24T12:23:00+0200').local;
# 2015-12-24T09:23:00-0100</pre>
<a name="t59"><h1 class="title">59 role Dateish</h1></a> <p class="subtitle">Object that can be treated as a date</p></a> <pre class="code">role Dateish { ... }</pre>
<p>Both <a href="/type/Date">Date</a> and <a href="/type/DateTime">DateTime</a> support accessing a year, month and day-of-month, as well as related functionality such as calculating the day of the week.</p>
<a name="t59.1"$class><h1>59.1 Methods</h1></a>
<a name="t59.1.1"$class><h2>59.1.1 method year</h2></a>
<p>Defined as:</p>
<pre class="code">method year(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.year</pre>
<p>Returns the year of the date</p>
<a name="t59.1.2"$class><h2>59.1.2 method month</h2></a>
<p>Defined as:</p>
<pre class="code">method month(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.month</pre>
<p>Returns the month of the date (1..12)</p>
<a name="t59.1.3"$class><h2>59.1.3 method day</h2></a>
<p>Defined as:</p>
<pre class="code">method day(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.day</pre>
<p>Returns the day of the month of the date (1..31)</p>
<a name="t59.1.4"$class><h2>59.1.4 method is-leap-year</h2></a>
<p>Defined as:</p>
<pre class="code">method is-leap-year($year = self.year) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.is-leap-year(YEAR?)</pre>
<p>Returns <span class="code">True </span> if <span class="code">$year </span> is a leap year. Can be called as a class method if the year is provided.</p>
<a name="t59.1.5"$class><h2>59.1.5 method day-of-month</h2></a>
<p>Defined as:</p>
<pre class="code">method day-of-month(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.day-of-month</pre>
<p>Returns the day of the month of the date (1..31). Synonymous to the <span class="code">day </span> method.</p>
<a name="t59.1.6"$class><h2>59.1.6 method day-of-week</h2></a>
<p>Defined as:</p>
<pre class="code">method day-of-week(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.day-of-week</pre>
<p>Returns the day of the week, where 1 is Monday, 2 is Tuesday and Sunday is 7.</p>
<a name="t59.1.7"$class><h2>59.1.7 method day-of-year</h2></a>
<p>Defined as:</p>
<pre class="code">method day-of-year(Date:D:) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.day-of-year</pre>
<p>Returns the day of the year (1..366).</p>
<a name="t59.1.8"$class><h2>59.1.8 method days-in-month</h2></a>
<p>Defined as:</p>
<pre class="code">method days-in-month(year = self.year, month = self.month) returns Int:D</pre>
<p>Usage:</p>
<pre class="code">Dateish.days-in-month(YEAR?, MONTH?)</pre>
<p>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.</p>
<a name="t59.1.9"$class><h2>59.1.9 method week</h2></a>
<p>Defined as:</p>
<pre class="code">method week()</pre>
<p>Usage:</p>
<pre class="code">Dateish.week</pre>
<p>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.</p>
<pre class="code">my ($year, $week) = Date.new("2014-12-31").week;
say $year; # 2015
say $week; # 1
say Date.new('2015-01-31').week; # 2014 5</pre>
<a name="t60"><h1 class="title">60 Duration</h1></a> <p class="subtitle">Length of time</p></a> <pre class="code">class Duration is Cool does Real { }</pre>
<p>A <span class="code">Duration </span> represents a length of time in atomic seconds, with fractions. Like an <a href="">Instant</a> , it is epoch-agnostic. In numeric contexts (situations where a <span class="code">Duration </span> is used as a number), a <span class="code">Duration </span> will return either a <a href="">Rat</a> or a <a href="">FatRat</a> representing the number of seconds it holds.</p>
<p> <span class="code">Duration </span> s can be subtracted from or added to <span class="code">Instant </span> s to yield another, new <span class="code">Instant </span> . Subtracting one <span class="code">Instant </span> from another yields a <span class="code">Duration </span> . A <span class="code">Duration </span> can also result from mathematical operations between two <span class="code">Duration </span> s when it makes sense (namely, the addition, subtraction, or modulus of two <span class="code">Duration </span> s). The type of object returned for other numeric operations is currently unspecified.</p>
<a name="t61"><h1 class="title">61 class Enum</h1></a> <p class="subtitle">Immutable key/value pair</p></a> <pre class="code">class Enum does Associative { ... }</pre>
<p>An <span class="code">Enum </span> consists of a key and a value. It is the immutable version of <span class="code">Pair </span> (which inherits from Enum).</p>
<a name="t61.1"$class><h1>61.1 Methods</h1></a>
<a name="t61.1.1"$class><h2>61.1.1 method key</h2></a>
<p>Defined as:</p>
<pre class="code">multi method key(Enum:D:)</pre>
<p>Usage:</p>
<pre class="code">ENUM.key</pre>
<p>Returns the key part of the Enum.</p>
<a name="t61.1.2"$class><h2>61.1.2 method value</h2></a>
<p>Defined as:</p>
<pre class="code">multi method value(Enum:D:)</pre>
<p>Usage:</p>
<pre class="code">ENUM.value</pre>
<p>Returns the value part of the Enum.</p>
<a name="t61.1.3"$class><h2>61.1.3 method invert</h2></a>
<p>Defined as:</p>
<pre class="code">multi method invert(Enum:D:) returns Enum:D</pre>
<p>Usage:</p>
<pre class="code">ENUM.invert</pre>
<p>Returns a new <span class="code">Enum </span> with the original enum's value as the key, and the original enum's key as value.</p>
<a name="t62"><h1 class="title">62 class Exception</h1></a> <p class="subtitle">Anomalous event capable of interrupting normal control-flow</p></a> <pre class="code">class Exception { ... }</pre>
<p>All exceptions that are placed into the <span class="code">$! </span> variable (or into <span class="code">$_ </span> in <span class="code">CATCH </span> blocks) inherit from <span class="code">Exception </span> . When you call <span class="code">die </span> or <span class="code">fail </span> with a non-Exception argument, it is wrapped into an <span class="code">X::AdHoc </span> object, which also inherits from <span class="code">Exception </span> .</p>
<p>User-defined exception classes should inherit from <span class="code">Exception </span> too, and define at least a method <span class="code">message </span> .</p>
<pre class="code">class X::YourApp::SomeError is Exception {
method message() {
"A YourApp-Specific error occurred: out of coffee!";
}
}</pre>
<a name="t62.1"$class><h1>62.1 Methods</h1></a>
<a name="t62.1.1"$class><h2>62.1.1 method message</h2></a>
<p>Defined as:</p>
<pre class="code">method message(Exception:D:) returns Str:D</pre>
<p>Usage:</p>
<pre class="code">EXCEPTION.message</pre>
<p>This is a stub that must be overwritten by subclasses, and should return the exception message.</p>
<p>Special care should be taken that this method does not produce an exception itself.</p>
<a name="t62.1.2"$class><h2>62.1.2 method backtrace</h2></a>
<p>Defined as:</p>
<pre class="code">method backtrace(Exception:D:) returns Backtrace:D</pre>
<p>Usage:</p>
<pre class="code">EXCEPTION.backtrace</pre>
<p>Returns the backtrace associated with the exception. Only makes sense on exceptions that have been thrown at least once.</p>
<a name="t62.1.3"$class><h2>62.1.3 method throw</h2></a>
<p>Defined as:</p>
<pre class="code">method throw(Exception:D:)</pre>
<p>Usage:</p>
<pre class="code">EXCEPTION.throw</pre>
<p>Throws the exception.</p>
<a name="t62.1.4"$class><h2>62.1.4 method rethrow</h2></a>
<p>Defined as:</p>
<pre class="code">method rethrow(Exception:D:)</pre>
<p>Usage:</p>
<pre class="code">EXCEPTION.rethrow</pre>
<p>Rethrows an exception that has already been thrown at least once. This is different from <span class="code">throw </span> in that it preserves the original backtrace.</p>
<a name="t62.1.5"$class><h2>62.1.5 method fail</h2></a>
<p>Defined as:</p>
<pre class="code">sub fail(*@text)
sub fail(Exception $e)
method fail(Exception:D $e:)</pre>
<p>Usage:</p>
<pre class="code">fail(TEXT)
fail(EXCEPTION)
EXCEPTION.fail</pre>
<p>Exits the calling <span class="code">Routine </span> and returns a <a href="">Failure</a> object wrapping the exception <span class="code">$e </span> - or, for the <span class="code">*@text </span> form, an <a href="">X::AdHoc</a> exception constructed from the concatenation of <span class="code">@text </span> .</p>
<pre class="code">sub copy-directory-tree ($dir) {
fail "$dir is not a directory" if !$dir.IO.d;
...
}</pre>
<a name="t62.1.6"$class><h2>62.1.6 method gist</h2></a>
<p>Defined as:</p>
<pre class="code">multi method gist(Exception:D:)</pre>
<p>Usage:</p>
<pre class="code">EXCEPTION.gist</pre>
<p>Returns whatever the exception printer should produce for this exception. The default implementation returns message and backtrace separated by a newline.</p>
<a name="t62.1.7"$class><h2>62.1.7 sub die</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub die(*@message)
multi sub die(Exception:D $e:)
method die(Exception:D $e:)</pre>
<p>Usage:</p>
<pre class="code">die(MESSAGE)
die(EXCEPTION)
EXCEPTION.die</pre>
<p>Throws a fatal <span class="code">Exception </span> . The default exception handler prints each element of the list to <span class="code">$*ERR </span> (STDERR).</p>
<a name="t62.1.8"$class><h2>62.1.8 sub warn</h2></a>
<p>Defined as:</p>
<pre class="code">multi sub warn(*@message)</pre>
<p>Usage:</p>
<pre class="code">warn(MESSAGE)</pre>
<p>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 <span class="code">$*ERR </span> . After printing the warning, the exception is resumed where it was thrown. To override this behavior, catch the exception in a <span class="code">CONTROL </span> block. A <span class="code">quietly {...} </span> block is the opposite of a <span class="code">try {...} </span> block in that it will suppress any warnings but pass fatal exceptions through.</p>
<p>To simply print to <span class="code">$*ERR </span> , please use <span class="code">note </span> instead. <span class="code">warn </span> should be reserved for use in threatening situations when you don't quite want to throw an exception.</p>
<a name="t63"><h1 class="title">63 class Failure</h1></a> <p class="subtitle">Delayed exception</p></a> <pre class="code">class Failure { }</pre>
<p>A <span class="code">Failure </span> is a <i>soft</i> or <i>unthrown</i> exception, usually generated by calling <span class="code">&amp;fail </span> . It acts as a wrapper around an <a href="">Exception</a> object.</p>
<p>Sink (void) context causes a Failure to throw, i.e. turn into a normal exception.</p>
<p>Checking a Failure for truth (with the <span class="code">Bool </span> method) or definedness (with the <span class="code">defined </span> method) marks the failure as handled, and causes it not to throw in sink context anymore.</p>
<p>You can call the <span class="code">handled </span> method to check if a failure has been handled.</p>
<p>Calling methods on unhandled failures propagates the failure. The specification says the result is another <span class="code">Failure </span> , in Rakudo it causes the failure to throw.</p>
<a name="t63.1"$class><h1>63.1 Methods</h1></a>
<a name="t63.1.1"$class><h2>63.1.1 method handled</h2></a>
<p>Defined as:</p>
<pre class="code">method handled(Failure:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">FAILURE.handled</pre>
<p>Returns <span class="code">True </span> for handled failures, <span class="code">False </span> otherwise.</p>
<a name="t63.1.2"$class><h2>63.1.2 method exception</h2></a>
<p>Defined as:</p>
<pre class="code">method exception(Failure:D:) returns Exception</pre>
<p>Usage:</p>
<pre class="code">FAILURE.exception</pre>
<p>Returns the <a href="">Exception</a> object that the failure wraps.</p>
<a name="t63.1.3"$class><h2>63.1.3 method Bool</h2></a>
<p>Defined as:</p>
<pre class="code">multi method Bool(Failure:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">FAILURE.Bool</pre>
<p>Returns <span class="code">False </span> , and marks the failure as handled.</p>
<a name="t63.1.4"$class><h2>63.1.4 method defined</h2></a>
<p>Defined as:</p>
<pre class="code">multi method defined(Failure:D:) returns Bool:D</pre>
<p>Usage:</p>
<pre class="code">FAILURE.defined</pre>
<p>Returns <span class="code">False </span> (failures are officially undefined), and marks the failure as handled.</p>
<a name="t64"><h1 class="title">64 class FatRat</h1></a> <p class="subtitle">Rational number (arbitrary-precision)</p></a> <pre class="code">class FatRat is Cool does Rational[Int, Int]</pre>
<p>A <span class="code">FatRat </span> is a rational number stored with arbitrary size numerator and denominator. Arithmetic operations involving a <span class="code">FatRat </span> and optionally <a href="">Int</a> or <a href="">Rat</a> objects return a <span class="code">FatRat </span> , avoiding loss of precision.</p>
<p>Since, unlike <a href="">Rat</a> , FatRat arithmetics do not fall back <a href="">Num</a> at some point, there is a risk that repeated arithmetic operations generate pathologically large numerators and denominators.</p>
<p>There are two common ways to generate <span class="code">FatRat </span> objects: through the <span class="code">FatRat.new(Int, Int) </span> constructor, which generates them from numerator and denominator, or by calling the <span class="code">.FatRat </span> method on an <a href="">Int</a> or <a href="">Rat</a> object.</p>
<a name="t65"><h1 class="title">65 class Grammar</h1></a> <p class="subtitle">Formal grammar made up of named regexes</p></a> <pre class="code">class Grammar is Cursor { ... }</pre>
<p>Every type declared with <span class="code">grammar </span> (which doesn't explicitly states its superclass) becomes a subclass of <i>Grammar</i> .</p>
<pre class="code">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</pre>
<p>More <a href="/language/grammars">documentation on grammars</a> is available.</p>
<a name="t65.1"$class><h1>65.1 Methods</h1></a>
<a name="t65.1.1"$class><h2>65.1.1 method parse</h2></a>
<p>Defined as:</p>
<pre class="code">method parse($target, :$rule = 'TOP', Capture() :$args = \(), Mu :$actions = Mu, *%opt) {</pre>
<p>Usage:</p>
<pre class="code">GRAMMAR.parse(TARGET, RULE?, ARGS?, ACTIONS?, OPTIONS?)</pre>
<p>Parses the <span class="code">$target </span> (which will be coerced to <a href="/type/Str">Str</a> if it isn't one), using <span class="code">$rule </span> as the starting rule. Additional <span class="code">$args </span> will be given to the starting rule if provided.</p>
<p>If the <span class="code">action </span> 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.</p>
<p>Additional named arguments are used as options for matching, so you can specify things like <span class="code">:c(4) </span> to start parsing from the fourth character. All <a href="/language/regexes#Adverbs">matching adverbs</a> are allowed.</p>
<p>Method <span class="code">parse </span> only succeeds if the cursor has arrived at the end of the target string when the match is over. Use <a href="/routine/subparse">method subparse</a> if you want to be able to stop in the middle.</p>
<p>Returns a <a href="/type/Match">Match object</a> on success, and <a href="/type/Nil">Nil</a> on failure.</p>
<pre class="code">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</pre>
<p>This outputs:</p>
<pre class="code">「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 」</pre>
<a name="t65.1.2"$class><h2>65.1.2 method subparse</h2></a>
<p>Defined as:</p>
<pre class="code">method subparse($target, :$rule = 'TOP', Capture() :$args = \(), Mu :$actions = Mu, *%opt) {</pre>
<p>Usage:</p>
<pre class="code">GRAMMAR.subparse(TARGET, RULE?, ARGS?, ACTIONS?, OPTIONS?)</pre>
<p>Does exactly the same as <a href="/routine/parse">method parse</a> , 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).</p>
<pre class="code">grammar A {
token as { a+ };
}
my $match = A.subparse('aaab', :rule&lt;as>);
say ~$match; # aaa
say $match.to; # 3</pre>
<a name="t65.1.3"$class><h2>65.1.3 method parsefile</h2></a>
<p>Defined as:</p>
<pre class="code">method parsefile(Str(Cool) $filename, :$enc, *%opts) {</pre>
<p>Usage:</p>
<pre class="code">GRAMMAR.parsefile(FILE, OPTIONS?)</pre>
<p>Reads file <span class="code">$filename </span> , and parses it. All named arguments are passed on to <a href="/routine/parse">method parse</a> .</p>
<a name="t66"><h1 class="title">66 class Hash</h1></a> <p class="subtitle">Mapping from strings to itemized values</p></a> <pre class="code">class Hash is Map { }</pre>
<p>A Hash is a mutable mapping from keys to values (called <i>dictionary</i> , <i>hash table</i> or <i>map</i> in other programming languages). The values are all scalar containers, which means you can assign to them.</p>
<p>Hashes are usually stored in variables with the percent <span class="code">% </span> sigil.</p>
<p>Hash elements are accessed by key via the <span class="code">{ } </span> postcircumfix operator:</p>
<pre class="code">my $home = %*ENV{'HOME'};</pre>
<p>For literal string keys without whitespace, <span class="code">&lt; > </span> can be used instead:</p>
<pre class="code">my $home = %*ENV&lt;HOME>;</pre>
<p>You can add new pairs simply by assigning to an unused key:</p>
<pre class="code">my %h;
%h{'new key'} = 'new value';</pre>
<a name="t66.1"$class><h1>66.1 Hash assignment</h1></a>
<p>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 an <a href="">Enum</a> (or a subclass like <a href="">Pair</a> ), 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 <a href="">Str</a> and used as a hash key, while the next element of the list is taken as the corresponding value.</p>
<pre class="code">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>;</pre>
<p>If an <a href="">Enum</a> is encountered where a value is expected, it is used as a hash value:</p>
<pre class="code">my %h = 'a', 'b' => 'c';
say %h&lt;a>.WHAT; # Pair();
say %h&lt;a>.key; # b</pre>
<p>If the same key appears more than once, the value associated with its last occurrence is stored in the hash:</p>
<pre class="code">my %h = a => 1, a => 2;
say %h&lt;a>; # 2</pre>
<p>To assign to a variable without the <span class="code">% </span> sigil, you may use curly braces:</p>
<pre class="code">my $h = { a => 1, b => 2 };</pre>
<p>By default keys in <span class="code">{ } </span> are forced to strings. To compose a hash with non-string keys, use a colon prefix:</p>
<pre class="code">my $when = :{ (now) => "Instant", (DateTime.now) => "DateTime" };</pre>
<p>Note that with objects as keys, you cannot access non-string keys as strings:</p>
<pre class="code">:{ -1 => 41, 0 => 42, 1 => 43 }&lt;0> # Any
:{ -1 => 41, 0 => 42, 1 => 43 }{0} # 42</pre>
<a name="t66.2"$class><h1>66.2 Looping over hash keys and values</h1></a>
<p>A common idiom for processing the elements in a hash is to loop over the keys and values, for instance,</p>
<pre class="code">my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
for %vowels.kv -> $vowel, $index {</pre>
<pre class="code">"$vowel: $index".say;</pre>
<pre class="code">}</pre>
<p>gives output similar to this:</p>
<pre class="code">a: 1
e: 2
o: 4
u: 5
i: 3</pre>
<p>where we have used the <span class="code">kv </span> method to extract the keys and their respective values from the hash, so that we can pass these values into the loop.</p>
<p>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</p>
<pre class="code">my %vowels = 'a' => 1, 'e' => 2, 'i' => 3, 'o' => 4, 'u' => 5;
for %vowels.sort(*.key)>>.kv -> ($vowel, $index) {</pre>
<pre class="code">"$vowel: $index".say;</pre>
<pre class="code">}</pre>
<p>which prints</p>
<pre class="code">a: 1
e: 2
i: 3
o: 4
u: 5</pre>
<p>and is in alphabetical order as desired. To achieve this result, we sorted the hash of vowels by key ( <span class="code">%vowels.sort(*.key) </span> ) which we then ask for its keys and values by applying the <span class="code">.kv </span> method to each element via the unary <span class="code"> </span> > > hyperoperator. The output of this operation is a <a href="">Seq</a> , the items of which need to be passed into the <span class="code">for </span> loop's block as arguments, which is why you will find the key/value pairs wrapped in parentheses. The signature of the point block could also be a single argument.</p>
<pre class="code">for %vowels.kv -> $vowel {
say $vowel;
}</pre>
<p>This would print the list one line at a time.</p>
<a name="t66.2.1"$class><h2>66.2.1 Object hashes and type constraints</h2></a>
<p>Hash keys are stored as <a href="">Str</a> 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 <i>as the *exact* objects you are providing to the hash to use as keys</i> . In these moments you want an object hash!</p>
<pre class="code">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;
}</pre>
<p>This example uses an object hash that only accepts keys of type <a href="">Instant</a> to implement a rudimentary, yet type-safe, logging mechanism. We utilize a named <a href="">state</a> variable for keeping track of the previous <span class="code">Instant </span> so that we can provide an interval.</p>
<p>The whole point of object hashes is to keep keys as objects-in-themselves. Currently object hashes utilize the <a href="">WHICH</a> method of an object, which returns a unique identifier for every mutable object. This is the keystone upon which the object identity operator ( <a href="">===</a> ) rests. Order and containers really matter here as the order of <span class="code">.keys </span> is undefined and one anonymous list is never <a href="">===</a> to another.</p>
<pre class="code">> ($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</pre>
<p>Since <span class="code">Instant </span> defines its own comparison methods, in our example a sort according to <a href="">cmp</a> will always provide the earliest instant object as the first element in the <a href="">List</a> it returns.</p>
<p>If you would like to accept any object whatsoever in your hash, you can use <a href="">Any</a> !</p>
<pre class="code">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";</pre>
<p>There is a more concise syntax which uses binding.</p>
<pre class="code">my %h := :{ (now) => "Instant", (DateTime.now) => "DateTime" }</pre>
<p>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.</p>
<a name="t66.2.2"$class><h2>66.2.2 In place editing of values</h2></a>
<p>There may be times when you would like to modify the values of a hash while iterating over them.</p>
<pre class="code">> 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</pre>
<p>This is traditionally accomplished by sending both the key and the value as follows.</p>
<pre class="code">for %answers.kv -> $k,$v { %answers{$k} = $v + 10 }</pre>
<p>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.</p>
<pre class="code">for %answers.values -> $v is rw { $v += 10 }</pre>
<p>It is not, however, possible to do in-place editing of hash keys, even in the case of object hashes.</p>
<a name="t66.3"$class><h1>66.3 Methods</h1></a>
<a name="t66.3.1"$class><h2>66.3.1 method push</h2></a>
<p>Defined as:</p>
<pre class="code">multi method push(Hash:D: *@new)</pre>
<p>Usage:</p>
<pre class="code">push HASH, VALUES
HASH.push(VALUES)
HASH.push: (VALUES)</pre>
<p>Adds the <span class="code">@new </span> elements to the hash with the same semantics as hash assignment, but with three exceptions:</p>
<ul><li><p>The hash isn't emptied first, i.e. old pairs are not deleted.</p>
</li></ul> <ul><li><p>If a key already exists in the hash, and the corresponding value is an <a href="">Array</a> , the new value is pushed onto the array (instead of replacing it).</p>
</li></ul> <ul><li><p>If a key already exists in the hash, and the corresponding value is not an <a href="">Array</a> , old and new value are both placed into an array in the place of the old value.</p>
</li></ul> <p>Example:</p>
<pre class="code">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</pre>
<p>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:</p>
<pre class="code">my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
(my %inv).push: %wc.invert.unique;
say %inv; # 322 => 'pair', 323 => ['hash','pipe']</pre>
<p>Note that such a initialization could also be written as</p>
<pre class="code">my %inv .= push: %wc.invert.unique;</pre>
<a name="t67"><h1 class="title">67 role IO</h1></a> <p class="subtitle">Input/output related object</p></a> <pre class="code">role IO { }</pre>
<p>The IO role provides no functionality itself; it simply marks that a particular object relates to input/output.</p>
<a name="t67.1"$class><h1>67.1 Routines</h1></a>
<a name="t67.1.1"$class><h2>67.1.1 sub print</h2></a>
<p>Print the given text on <span class="code">$*OUT </span> (standard output), e.g.:</p>
<pre class="code">print "Hi there!\n"; # Hi there!</pre>
<p>Note that the <span class="code">print </span> function does <i>not</i> (in contrast to some other languages) append a newline character to the text. Thus the following code</p>
<pre class="code">print "Hi there!";
print "How are you?";
print (0..101).list;</pre>
<p>displays</p>
<pre class="code">Hi there!How are you?0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101</pre>
<p>To print text implicitly including the trailing newline character, use <a href="/type/IO#sub_say">say</a> .</p>
<a name="t67.1.2"$class><h2>67.1.2 sub put</h2></a>
<p>Print the given text on <span class="code">$*OUT </span> (standard output) with appended <span class="code">$*OUT.nl-out </span> . The default for the latter is the platform dependent newline sequence. </p>
<pre class="code">put 'Merry 1.0!';
put (0..101).list;</pre>
<p>outputs</p>
<pre class="code">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␤</pre>
<a name="t67.1.3"$class><h2>67.1.3 sub say</h2></a>
<p>Print the given text in human readable form, followed by a <span class="code">$*OUT.nl-out </span> (platform dependent newline) on <span class="code">$*OUT </span> (standard output). Long output may be truncted. For machine readable output use <span class="code">put </span> .</p>
<p>With <span class="code">say </span> , the example code as mentioned in the <span class="code">print </span> section will be displayed as the user likely intended:</p>
<pre class="code">say "Hi there!";
say "How are you?";
say (0..101).list; </pre>
<p>displays</p>
<pre class="code">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 ...)␤</pre>
<p> <span class="code">say </span> prints non- <span class="code">Str </span> objects by calling their <span class="code">.gist </span> method before printing. Hence the following <span class="code">say </span> statements for the respective containers are equivalent:</p>
<pre class="code">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␤</pre>
<a name="t67.1.4"$class><h2>67.1.4 sub note</h2></a>
<p>Print the given text, followed by a newline <span class="code">"\n" </span> on <span class="code">$*ERR </span> (standard error). Before printing, call the <span class="code">.gist </span> method on any non- <span class="code">Str </span> objects.</p>
<p> <span class="code">note </span> is effectively <span class="code">say </span> , only it writes its output to the standard error stream. For instance:</p>
<pre class="code">if ("path/to/pirate/treasure".IO.e) {</pre>
<pre class="code">say "Found pirate treasure!";</pre>
<pre class="code">}
else {</pre>
<pre class="code">note "Could not find pirate treasure. Are you sure it exists?";</pre>
<pre class="code">}</pre>
<p>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.</p>
<a name="t67.1.5"$class><h2>67.1.5 sub dd</h2></a>
<p>The Tiny Data Dumper. This function takes the input list of variables and <span class="code">note </span> s them (on <span class="code">$*ERR </span> ) in an easy to read format, along with the <span class="code">name </span> of the variable. Thus,</p>
<pre class="code">my $a = 42;
my %hash = "a" => 1, "b" => 2, "c" => 3;
dd %hash, $a;</pre>
<p>prints</p>
<pre class="code">%hash = ("a" => 1, "c" => 3, "b" => 2).hash, $a = 42␤</pre>
<p>to the standard error stream.</p>
<p>This is in spirit similar to Perl 5's <a href="http://perldoc.perl.org/Data/Dumper.html">Data::Dumper module</a> .</p>
<p>Please note that <span class="code">dd </span> will ignore named parameters. You can use a capture to force it to dump everything passed to it.</p>
<pre class="code">dd \((:a(1), :b(2)), :c(3));</pre>
<a name="t67.1.6"$class><h2>67.1.6 sub prompt</h2></a>
<pre class="code">sub prompt($msg)</pre>
<p>Prints <span class="code">$msg </span> 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.</p>
<pre class="code">my $name = prompt("Hi, what's your name? ");</pre>
<a name="t67.1.7"$class><h2>67.1.7 sub open</h2></a>
<pre class="code">my $fh = open(IO::Path() $path, :$r, :$w, :$a, :$rw,
:$bin, :$enc, :$nl, :$chomp)</pre>
<p>Opens the <span class="code">$path </span> (by default in text mode) with the given options, returning an <a href="">IO::Handle</a> object.</p>
<a name="t67.1.7.1"$class><h3>67.1.7.1 File mode options</h3></a>
<ul><li><p>read-only mode, <span class="code">:r </span> </p>
</li></ul> <p>Open the file as read only, e.g.:</p>
<pre class="code">my $fh = open("path/to/file", :r);</pre>
<p>This is the default mode for <span class="code">open </span> .</p>
<p>Write-related methods on the returned <span class="code">IO::Handle </span> object will fail in this mode:</p>
<pre class="code">my $fh = open("test"); # the file "test" already exists
spurt $fh, "new text\n";
Failed to write bytes to filehandle: bad file descriptor</pre>
<ul><li><p>write-only mode, <span class="code">:w </span> </p>
</li></ul> <p>Open the file for writing, creating it if it doesn't exist or overwriting the file if it does exist, e.g.:</p>
<pre class="code">my $fh = open("path/to/file", :w);</pre>
<p>Read-related methods will fail in this mode:</p>
<pre class="code">my $fh = open("test", :w);
spurt $fh, "stuff\n";
spurt $fh, "more stuff\n";
$fh.seek(0, 0); # return to the start of the file
$fh.get(); # Reading from filehandle failed: bad file descriptor</pre>
<ul><li><p>read-write mode, <span class="code">:rw </span> </p>
</li></ul> <p>Open the file for reading and writing, creating the file if it doesn't exist or overwriting the file if it already exists.</p>
<pre class="code">my $fh = open("path/to/file", :w);</pre>
<ul><li><p>append mode, <span class="code">:a </span> </p>
</li></ul> <p>Open the file for appending. If the file does not exist, create it. If the file already exists, append data to it.</p>
<pre class="code">my $fh = open("path/to/file", :a);</pre>
<a name="t67.1.7.2"$class><h3>67.1.7.2 Encoding options</h3></a>
<ul><li><p>binary mode, <span class="code">:bin </span> </p>
</li></ul> <p>Open the file in binary mode (byte mode):</p>
<pre class="code">my $fh = open("path/to/file", :bin);</pre>
<p>A file opened with <span class="code">:bin </span> may still be processed line-by-line, but IO will be in terms of <a href="/type/Buf">Buf</a> rather than <a href="/type/Str">Str</a> types. Default is <span class="code">False </span> , implying text semantics.</p>
<ul><li><p>text mode encoding, <span class="code">:enc </span> </p>
</li></ul> <p>The encoding to use if opened in text mode.</p>
<pre class="code"># 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");</pre>
<p>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:</p>
<pre class="code">my $fh = open("path/to/file", enc => "Unicode");</pre>
<p>This is because one needs to specify a specific unicode encoding, e.g. "utf8".</p>
<a name="t67.1.7.3"$class><h3>67.1.7.3 Newline options</h3></a>
<ul><li><p>end-of-line (EOL) marker, <span class="code">:nl </span> </p>
</li></ul> <p>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 <span class="code">"\n" </span> , <span class="code">"\r\n" </span> or <span class="code">"\r" </span> or any other Unicode character that has the <span class="code">Zl </span> (Separator, Line) property.</p>
<pre class="code"># explicitly use CR-LF as EOL character
my $fh = open("path/to/file", nl => "\r\n");</pre>
<ul><li><p>chomp mode, <span class="code">:chomp </span> </p>
</li></ul> <p>Whether or not to remove newline characters from text obtained with <span class="code">.lines </span> and <span class="code">.get </span> . Defaults to <span class="code">True </span> .</p>
<pre class="code"># don't remove newline characters from input
my $fh = open("path/to/file", chomp => False);
say $fh.get(); # returns line including newline char</pre>
<a name="t67.1.8"$class><h2>67.1.8 method close</h2></a>
<p>To close an open file handle, simply call its <a href="/type/IO::Handle#method_close">close</a> method:</p>
<pre class="code">my $fh = open("path/to/file");
# ... do stuff with the file
$fh.close;</pre>
<p>It is also possible to call this as a sub, thus the example above can be written equivalently like so:</p>
<pre class="code">my $fh = open("path/to/file");
# ... do stuff with the file
close $fh;</pre>
<p>When a file was opened for writing, closing it is important to ensure that all contents are actually written to the file.</p>
<a name="t67.1.9"$class><h2>67.1.9 sub slurp</h2></a>
<p>Slurps the contents of the entire file into a <span class="code">Str </span> (or <span class="code">Buf </span> if <span class="code">:bin </span> ). Accepts <span class="code">:bin </span> and <span class="code">:enc </span> optional named parameters, with the same meaning as <a href="">/open()</a> . The routine will <span class="code">fail </span> if the file does not exist, or is a directory.</p>
<pre class="code"># 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;</pre>
<a name="t67.1.10"$class><h2>67.1.10 sub spurt</h2></a>
<pre class="code">sub spurt ($where, $what,
Str :$enc = $*ENC,
Bool :append = False,
Bool :$createonly = False,
--> Bool ) is export</pre>
<p>Writes the indicated contents (2nd positional parameter, <span class="code">$what </span> ) to the location indicated by the first positional parameter, <span class="code">$where </span> (which can either be a string or an <span class="code">IO::Path </span> object). To write to an <span class="code">IO::Handle </span> , use the <a href="">print</a> method.</p>
<p>If a file needs to be opened for writing, it will also be <span class="code">close </span> d. Returns <span class="code">True </span> on success, or the appropriate <span class="code">Failure </span> if something went wrong.</p>
<p>These named parameters are optional and only have meaning if the first positional parameter was <b>not</b> an <span class="code">IO::Handle </span> :</p>
<a name="t67.1.10.1"$class><h3>67.1.10.1 Options</h3></a>
<ul><li><p>:enc</p>
</li></ul> <p>The encoding with which the contents will be written.</p>
<ul><li><p>:append</p>
</li></ul> <p>Boolean indicating whether to append to a (potentially) existing file. If the file did not exist yet, it will be created. Defaults to <span class="code">False </span> .</p>
<ul><li><p>:createonly</p>
</li></ul> <p>Boolean indicating whether to fail if the file already exists. Defaults to <span class="code">False </span> .</p>
<a name="t67.1.10.2"$class><h3>67.1.10.2 Examples</h3></a>
<pre class="code"># 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</pre>
<a name="t67.1.11"$class><h2>67.1.11 sub run</h2></a>
<pre class="code">sub run(*@args ($, *@)) returns Proc</pre>
<p>Runs an external command without involving a shell (if possible).</p>
<p>See <a href="/type/Proc">Proc</a> for more details, for example on how to capture output.</p>
<a name="t67.1.12"$class><h2>67.1.12 sub shell</h2></a>
<pre class="code">sub shell($cmd) returns Proc</pre>
<p>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 <a href="/type/IO#sub_run">run</a> if you don't want that.</p>
<p>The return value is of <a href="/type/Proc">type Proc</a> .</p>
<pre class="code">shell 'ls -lR | gzip -9 > ls-lR.gz';</pre>
<p>See <a href="/type/Proc">Proc</a> for more details, for example on how to capture output.</p>
<a name="t67.2"$class><h1>67.2 Related classes</h1></a>
<p>See also the related classes <a href="">IO::Handle</a> and <a href="">IO::Path</a> .</p>
<a name="t68"><h1 class="title">68 class IO::Handle</h1></a> <p class="subtitle">Opened file or stream</p></a> <pre class="code">class IO::Handle does IO { }</pre>
<a name="t68.1"$class><h1>68.1 Methods</h1></a>
<a name="t68.1.1"$class><h2>68.1.1 method get</h2></a>
<p>Reads a single line from the input stream (usually the Standard Input or a file).</p>
<p>Read one line from the standard input:</p>
<pre class="code">$*IN.get;</pre>
<p>Read one line from a file:</p>
<pre class="code">my $fh = open 'filename';
my $line = $fh.get;</pre>
<a name="t68.1.2"$class><h2>68.1.2 method getc</h2></a>
<p>Read a single character from the input stream or return Nil. The operation is blocking and the stream may be buffered.</p>
<a name="t68.1.3"$class><h2>68.1.3 method eof</h2></a>
<p>Returns <a href="">Bool::True</a> if the read operations have exhausted the content of the file.</p>
<a name="t68.1.4"$class><h2>68.1.4 method lines</h2></a>
<pre class="code">method lines($limit = Inf)</pre>
<p>Return a lazy list of the file's lines read via <a href="">get</a> , limited to <span class="code">$limit </span> lines. The new line separator (e.g. $*IN.nl-in) will be excluded.</p>
<pre class="code"> my @data;
my $data-file = open 'readings.csv';
for <b>$data-file.lines</b> -> $line {
@data.push($line.split(','))
}
</pre>
<a name="t68.1.5"$class><h2>68.1.5 method words</h2></a>
<pre class="code">method words($count = Inf)</pre>
<p>Return a lazy list of the file's words (separated on whitespace), limited to <span class="code">$count </span> words.</p>
<pre class="code"> my %dict;
++%dict{$_} for $*IN.words;
say "Most common words: ", %dict.sort(*.value).reverse.[^5];
</pre>
<a name="t68.1.6"$class><h2>68.1.6 method split</h2></a>
<pre class="code">method split(splitter = "")</pre>
<p>Returns a lazy list of strings found between the splitter, just like <span class="code">split </span> on strings.</p>
<a name="t68.1.7"$class><h2>68.1.7 method comb</h2></a>
<pre class="code">method comb(comber = "")</pre>
<p>Returns a lazy list of strings combed from the handle, just like <span class="code">comb </span> on strings.</p>
<a name="t68.1.8"$class><h2>68.1.8 method print</h2></a>
<pre class="code">method print(*@text --> Bool)</pre>
<p>Text writing; writes the given <span class="code">@text </span> to the filehandle. See <a href="">write</a> to write bytes.</p>
<pre class="code">my $fh = open 'path/to/file', :w;
$fh.print("some text\n");
$fh.close;</pre>
<a name="t68.1.9"$class><h2>68.1.9 method read</h2></a>
<pre class="code">method read(IO::Handle:D: Int(Cool:D) $bytes --> Blob)</pre>
<p>Binary reading; reads and returns up to <span class="code">$bytes </span> bytes from the filehandle.</p>
<a name="t68.1.10"$class><h2>68.1.10 method readchars</h2></a>
<pre class="code">method readchars(IO::Handle:D: Int(Cool:D) $chars --> Str)</pre>
<p>Reading chars; reads and returns up to <span class="code">$chars </span> chars (graphemes) from the filehandle.</p>
<a name="t68.1.11"$class><h2>68.1.11 method write</h2></a>
<pre class="code">method write(IO::Handle:D: Blob:D $buf)</pre>
<p>Binary writing; writes <span class="code">$buf </span> to the filehandle. See <a href="">print</a> to write characters.</p>
<a name="t68.1.12"$class><h2>68.1.12 method seek</h2></a>
<pre class="code">method seek(IO::Handle:D: Int:D $offset, SeekType:D $whence --> True)</pre>
<p>Move the file pointer (that is the position at which any subsequent read or write operations will begin,) to the byte position specified by <span class="code">$offset </span> relative to the location specified by <span class="code">$whence </span> which may be one of:</p>
<ul><li><p>SeekFromBeginning</p>
</li></ul> <p>The beginning of the file.</p>
<ul><li><p>SeekFromCurrent</p>
</li></ul> <p>The current position in the file.</p>
<ul><li><p>SeekFromEnd</p>
</li></ul> <p>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.</p>
<a name="t68.1.13"$class><h2>68.1.13 method tell</h2></a>
<pre class="code">method tell(IO::Handle:D: --> Int)</pre>
<p>Return the current position of the file pointer in bytes.</p>
<a name="t68.1.14"$class><h2>68.1.14 method ins</h2></a>
<pre class="code">method ins(IO::Handle:D: --> Int)</pre>
<p>Return the number of lines read from the file.</p>
<a name="t68.1.15"$class><h2>68.1.15 method slurp-rest</h2></a>
<pre class="code">multi method slurp-rest(IO::Handle:D: :$bin! --> Buf)
multi method slurp-rest(IO::Handle:D: :$enc --> Str)</pre>
<p>Return the remaining content of the file from the current file position (which may have been set by previous reads or by <span class="code">seek </span> .) If the adverb <span class="code">:bin </span> is provided a <a href="">Buf</a> will be returned, otherwise the return will be a <span class="code">Str </span> with the optional encoding <span class="code">:enc </span> .</p>
<a name="t68.1.16"$class><h2>68.1.16 method Supply</h2></a>
<pre class="code">multi method Supply(IO::Handle:D: :$size = 65536, :$bin --> Supply)</pre>
<p>Returns a <span class="code">Supply </span> that will emit the contents of the handle in chunks. The size of the chunks is determined by the optional <span class="code">:size </span> named parameter and defaults to 64K. The optional <span class="code">:bin </span> named parameter can be specified to indicate binary reading of the contents, rather than character based reading.</p>
<a name="t68.1.17"$class><h2>68.1.17 method close</h2></a>
<p>Will close a previously opened filehandle.</p>
<pre class="code">$fh.close;</pre>
<a name="t68.1.18"$class><h2>68.1.18 method flush</h2></a>
<p>Will flush the filehandle to disk.</p>
<pre class="code">$fh.flush;</pre>
<a name="t68.1.19"$class><h2>68.1.19 method native-descriptor</h2></a>
<pre class="code">method native-descriptor()</pre>
<p>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 <span class="code">fcntl </span> or <span class="code">ioctl </span> . </p>
<a name="t68.2"$class><h1>68.2 Related roles and classes</h1></a>
<p>See also the related role <a href="">IO</a> and the related class <a href="">IO::Path</a> .</p>
<a name="t69"><h1 class="title">69 class IO::Notification</h1></a> <p class="subtitle">Asynchronous notification for file and directory changes</p></a> <pre class="code">enum FileChangeEvent (:FileChanged(1), :FileRenamed(2));
class IO::Notification {
class Change {
has $.path;
has $.event;
}
...
}</pre>
<p> <span class="code">IO::Notification.watch-path($path) </span> produces a <a href="/type/Supply">Supply</a> of <span class="code">IO::Notification::Change </span> events for a file or directory.</p>
<p>Here is a small example that prints the first ten notifications for the current directory:</p>
<pre class="code">my $finish = Promise.new;
my $count = 0;
IO::Notification.watch-path($?FILE).act( -> $change {
$count++;
say "($count) $change.path(): $change.event()";
$finish.keep if $count >= 10;
});
await $finish;</pre>
<p>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.</p>
<a name="t69.1"$class><h1>69.1 Methods</h1></a>
<a name="t69.1.1"$class><h2>69.1.1 method watch-path</h2></a>
<pre class="code">method watch-path(IO::Notification: Str() $path, :$scheduler = $*SCHDEULER)</pre>
<p>Returns a <a href="/type/Supply">Supply</a> that emits <span class="code">IO::Notification::Change </span> objects.</p>
<p>If <span class="code">$path </span> is a file, only modifications of that file are reported. If <span class="code">$path </span> 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.</p>
<p> <span class="code">:$scheduler </span> allows you to specify which thread scheduler is responsible for the notification stream.</p>
<a name="t70"><h1 class="title">70 class IO::Path</h1></a> <p class="subtitle">File or directory path</p></a> <pre class="code">class IO::Path is Cool does IO { }</pre>
<p>Built-in class for file and directory paths.</p>
<p>Conceptually, an <span class="code">IO::Path </span> object consists of a volume (think <span class="code">C: </span> on windows), a directory, and a basename.</p>
<p> <span class="code">IO::Path </span> supports both purely textual operations, and operations that access the file system.</p>
<p>The current working directory is available as an IO::Path object in <span class="code">$*CWD </span> .</p>
<p>The behavior of <span class="code">IO::Path </span> is dependent on the operating system it runs on; to get reproducible behavior across operating systems, you can use one of its subclasses instead: <a href="">IO::Path::Unix</a> , <a href="">IO::Path::Win32</a> , <a href="">IO::Path::Cygwin</a> , <a href="">IO::Path::QNX</a> .</p>
<p>The rest of this document silently assumes Unix semantics in its examples, unless when stated otherwise.</p>
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.
<a name="t70.1"$class><h1>70.1 Methods</h1></a>
<a name="t70.1.1"$class><h2>70.1.1 method new</h2></a>
<pre class="code">multi method new(Str:D $path)
multi method new(:$basename!, :$dirname = '.', :$volume = '')</pre>
<p>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.</p>
<a name="t70.1.2"$class><h2>70.1.2 method abspath</h2></a>
<p>Returns the absolute path as a string.</p>
<a name="t70.1.3"$class><h2>70.1.3 method basename</h2></a>
<pre class="code">method basename(IO::Path:D:)</pre>
<p>Returns the basename part of the path object. That is, it returns the name of the file relative to its directory.</p>
<pre class="code">say IO::Path.new("/etc/passwd").basename; # passwd</pre>
<a name="t70.1.4"$class><h2>70.1.4 method extension</h2></a>
<pre class="code">method extension(IO::Path:D:)</pre>
<p>Returns the extension (if any) of the path object.</p>
<pre class="code">say IO::Path.new("docs/README.pod").extension; # pod</pre>
<a name="t70.1.5"$class><h2>70.1.5 method dirname</h2></a>
<pre class="code">method dirname(IO::Path:D:)</pre>
<p>Returns the directory name portion of the path object. That is, it returns the path excluding the volume and the base name.</p>
<pre class="code">say IO::Path.new("/etc/passwd").dirname; # /etc</pre>
<a name="t70.1.6"$class><h2>70.1.6 method volume</h2></a>
<pre class="code">method volume(IO::Path:D:)</pre>
<p>Returns the volume portion of the path object. On Unix system, this is always the empty string.</p>
<pre class="code">say IO::Path::Win32.new("C:\\Windows\\registry.ini").volume; # C:</pre>
<a name="t70.1.7"$class><h2>70.1.7 method parts</h2></a>
<pre class="code">method parts(IO::Path:D:) returns Hash</pre>
<p>Returns a hash with the keys <span class="code">dirname </span> , <span class="code">path </span> and <span class="code">volume </span> , and as values the return values of the methods with the same names.</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment