Skip to content

Instantly share code, notes, and snippets.

@gfldex
Created June 16, 2018 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfldex/5a5f7898d4e2ea83cc0480d0653c220a to your computer and use it in GitHub Desktop.
Save gfldex/5a5f7898d4e2ea83cc0480d0653c220a to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
<html>
<head>
<title>Converted POD6 documentation</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
body { margin-left: 4em; margin-right: 4em; }
p {
text-rendering: optimizeLegibility;
font-feature-settings: "kern" 1;
-webkit-font-feature-settings: "kern" 1;
-moz-font-feature-settings: "kern" 1;
font-kerning: normal;
text-align: justify;
}
div.pod-content { padding-left: 20em; }
div.pod-body { width: 60em }
div.marginale { float: right; margin-right: -4em; width: 18em; font-size: 66%; text-align: left; }
span.filename { font-family: monospace; font-stretch: condensed; }
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; }
#left-side-menu {
width: 20em; margin-left: -22em;
float: left;
position: fixed;
top: 0;
overflow: scroll;
height: 100%;
padding: 0;
white-space: nowrap;
}
#left-side-menu-header {
transform: rotate(90deg);
transform-origin: left bottom 0;
z-index: 1;
position: fixed;
float: left;
top: 0;
margin-left: -23.5em;
}
#left-side-menu-header span.selection { padding-left: 1em; padding-right: 1em; }
.code { font-family: monospace; background-color: #f9f9f9; }
ul.numbered {
list-style: none;
}
span.numbered-prefix {
float: left;
}
span.numbered-prefix::after {
content: ")\00a0";
}
@media print {
div.pod-content { padding-left: 0; width: 100% }
div.pod-body { width: 90%; }
#left-side-menu {
width: unset;
margin-left: unset;
float: unset;
position: unset;
top: unset;
overflow: unset;
height: unset;
padding: unset;
white-space: unset;
}
div.left-side-menu-header, #index { display: none; }
}
</style>
</head>
<body>
<div class="pod-content">
<!-- /HomePage.pod6 --><div class="pod-body"><a id="_HomePage.pod6"></a><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 href="/perl6.xhtml">view everything in one file</a> or <a href="https://github.com/perl6/doc">contribute</a> by reporting mistakes or sending patches. <hr/> <dl> <dt><a href="/language.html">Language Reference &amp; 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="/programs.html">Perl 6 Programs</a></dt> <dd> A collection of documents describing how to run the Perl 6 executable program and other utilities, how to debug Perl 6 programs, and how to hack on Perl 6 source code. </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/resources/">a comprehensive list of Perl 6 resources</a>, including tutorials, how-tos 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="https://www.perl.org/">Perl 5</a> language can be found on the <a href="http://perldoc.perl.org/">Perl 5 documentation website</a>. </p>
</div>
<!-- /language/5to6-nutshell.pod6 --><div class="pod-body"><a id="_language_5to6-nutshell.pod6"></a><a name="t1"></a><h1 class="title">1 5to6-nutshell</h1> <p class="subtitle">Perl 5 to Perl 6, in a nutshell: How do I do what I used to do?</p> <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="#0-Automated Translation">#Automated Translation</a> might be more convenient).</p>
<p>A note on semantics; when we say &quot;now&quot; in this document, we mostly just mean &quot;now that you are trying out Perl 6.&quot; 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 &quot;now&quot; 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="t1.1"></a> <h1 id="_language_5to6-nutshell.pod6-CPAN">CPAN</h1>
<p>See <a href="https://modules.perl6.org/">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>The <a href="https://github.com/niner/Inline-Perl5/">Inline::Perl5</a> project makes it possible to <span class="code">use</span> Perl 5 modules directly from Perl 6 code by using an embedded instance of the <span class="code">perl</span> interpreter to run Perl 5 code.</p>
<a name="t1.2"></a> <h1 id="_language_5to6-nutshell.pod6-Syntax">Syntax</h1>
<a name="t1.2.1"></a> <h2 id="_language_5to6-nutshell.pod6-Identifiers">Identifiers</h2>
<p>In identifiers, Perl 6 allows the use of dashes (<span class="code">-</span>), underscores (<span class="code">_</span>), apostrophes (<span class="code">'</span>), and alphanumerics:</p>
<pre class="code">sub test-doesn't-hang { ... }
my $ความสงบ = 42;
my \Δ = 72; say 72 - Δ;</pre>
<a name="t1.2.2"></a> <h2 id="_language_5to6-nutshell.pod6--&gt;_Method_calls"><span class="code">-&gt;</span> Method calls</h2>
<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-&gt;name # Perl 5
</pre>
<pre class="code"> $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-&gt;$methodname(@args); # Perl 5
</pre>
<pre class="code"> $object.&quot;$methodname&quot;(@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="t1.2.3"></a> <h2 id="_language_5to6-nutshell.pod6-Whitespace">Whitespace</h2>
<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&quot;Hello &quot;.ucfirst ($people
[$ i]
-&gt;
name).&quot;!&quot;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 &quot;code golf&quot; 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)
</pre>
<pre class="code"> 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
</pre>
<pre class="code"> my ($alpha, $beta); # Perl 6
</pre>
<pre class="code"> if($a &lt; 0) { ... } # Perl 5, dies in Perl 6
</pre>
<pre class="code"> if ($a &lt; 0) { ... } # Perl 6
if $a &lt; 0 { ... } # Perl 6, more idiomatic
</pre>
<pre class="code"> while($x-- &gt; 5) { ... } # Perl 5, dies in Perl 6
</pre>
<pre class="code"> while ($x-- &gt; 5) { ... } # Perl 6
while $x-- &gt; 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
</pre>
<pre class="code"> %seen{$_}++; # Perl 6
</pre>
</li></ul> <ul><li><p><i>No space allowed around the method call operator.</i></p>
<pre class="code"> $customer -&gt; name; # Perl 5
</pre>
<pre class="code"> $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; &gt;)
</pre>
<pre class="code"> $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-&gt;parse_file($file) # some comment
-&gt;findnodes(&quot;/library/book&quot;);
</pre>
<pre class="code"> # Perl 6
my @books = $xml.parse-file($file)\ # some comment
.findnodes(&quot;/library/book&quot;);
</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="t1.2.4"></a> <h2 id="_language_5to6-nutshell.pod6-Sigils">Sigils</h2>
<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="#0-Dereferencing">#Dereferencing</a>).</p>
<a name="t1.2.4.1"></a> <h3 id="_language_5to6-nutshell.pod6-$_Scalar"><span class="code">$</span> Scalar</h3>
<p>The <span class="code">$</span> sigil is now always used with &quot;scalar&quot; variables (e.g. <span class="code">$name</span>), and no longer for <a href="#0-[]_Array_indexing/slicing">array indexing</a> and <a href="#0-{}_Hash_indexing/slicing">Hash indexing</a>. That is, you can still use <span class="code">$x[1]</span> and <span class="code">$x{&quot;foo&quot;}</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{&quot;foo&quot;}.</p>
<a name="t1.2.4.2"></a> <h3 id="_language_5to6-nutshell.pod6-@_Array"><span class="code">@</span> Array</h3>
<p>The <span class="code">@</span> sigil is now always used with &quot;array&quot; 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="#0-{}_Hash_indexing/slicing">value-slicing hashes</a>.</p>
<a name="t1.2.4.3"></a> <h3 id="_language_5to6-nutshell.pod6-%_Hash"><span class="code">%</span> Hash</h3>
<p>The <span class="code">%</span> sigil is now always used with &quot;hash&quot; variables (e.g. <span class="code">%calories</span>, <span class="code">%calories&lt;apple&gt;</span>, <span class="code">%calories&lt;pear plum&gt;</span>), and no longer for <a href="#0-[]_Array_indexing/slicing">key/value-slicing arrays</a>.</p>
<a name="t1.2.4.4"></a> <h3 id="_language_5to6-nutshell.pod6-&amp;_Sub"><span class="code">&amp;</span> Sub</h3>
<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 &quot;noun&quot; instead of a &quot;verb&quot;:</p>
<pre class="code"> my $sub = \&amp;foo; # Perl 5
</pre>
<pre class="code"> my $sub = &amp;foo; # Perl 6
</pre>
<pre class="code"> callback =&gt; sub { say @_ } # Perl 5 - can't pass built-in sub directly
</pre>
<pre class="code"> callback =&gt; &amp;say # Perl 6 - &amp; gives &quot;noun&quot; 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;::(&quot;foo&quot;)</span> (which uses the &quot;dynamic symbol lookup&quot; 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 { $_ &gt; 5 } @values;
&amp;first_index($coderef, @values); # (disabling the prototype that parses a
# literal block as the first argument)
</pre>
<pre class="code"> # Perl 6:
first { $_ &gt; 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>
# TODO: Suggest .callsame once it has been implemented in Rakudo.
# TODO: Suggest .nextsame and .nextwith once they've been implemented in Rakudo.
<pre class="code"> sub foo { say &quot;before&quot;; &amp;bar; say &quot;after&quot; } # Perl 5
</pre>
<pre class="code"> sub foo { say &quot;before&quot;; bar(|@_); say &quot;after&quot; } # Perl 6 - have to be explicit
</pre>
<pre class="code"> sub foo { say &quot;before&quot;; goto &amp;bar } # Perl 5
</pre>
</li></ul> <a name="t1.2.4.5"></a> <h3 id="_language_5to6-nutshell.pod6-*_Glob"><span class="code">*</span> Glob</h3>
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&gt;), scalar(&lt;H&gt;);
}
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&gt;), scalar(&lt;$fh&gt;);
}
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="t1.2.5"></a> <h2 id="_language_5to6-nutshell.pod6-[]_Array_indexing/slicing">[] Array indexing/slicing</h2>
<p>Index and slice operations on arrays no longer inflect the variable's <a href="#0-@_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
</pre>
<pre class="code"> 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
</pre>
<pre class="code"> 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="#0-exists">checking for existence of elements</a> and <a href="#0-delete">unsetting elements</a> is done with adverbs.</p>
<a name="t1.2.6"></a> <h2 id="_language_5to6-nutshell.pod6-{}_Hash_indexing/slicing">{} Hash indexing/slicing</h2>
<p>Index and slice operations on hashes no longer inflect the variable's <a href="#0-%_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{&quot;apple&quot;}; # Perl 5
</pre>
<pre class="code"> say %calories{&quot;apple&quot;}; # Perl 6 - % instead of $
</pre>
<pre class="code"> say $calories{apple}; # Perl 5
</pre>
<pre class="code"> say %calories&lt;apple&gt;; # Perl 6 - angle brackets; % instead of $
say %calories«&quot;$key&quot;»; # 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
</pre>
<pre class="code"> say join ',', %calories{'pear', 'plum'}; # Perl 6 - % instead of @
say join ',', %calories&lt;pear plum&gt;; # 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
</pre>
<pre class="code"> say join ',', %calories{'pear', 'plum'}:kv; # Perl 6 - use :kv adverb
say join ',', %calories&lt;pear plum&gt;: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="#0-exists">checking for existence of keys</a> and <a href="#0-delete">removing keys</a> is done with adverbs.</p>
<a name="t1.2.7"></a> <h2 id="_language_5to6-nutshell.pod6-Reference_creation">Reference creation</h2>
TODO: Rewrite this section to make it clear that the &quot;referencing/
dereferencing&quot; 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 =&gt; 98, Q =&gt; 99 }; # Both Perl 5&amp;6 [*See Note*]
</pre>
<pre class="code"> my $aref = \@aaa ; # Perl 5
</pre>
<pre class="code"> my $aref = item(@aaa) ; # Perl 6
</pre>
<pre class="code"> my $href = \%hhh ; # Perl 5
</pre>
<pre class="code"> my $href = item(%hhh) ; # Perl 6
</pre>
<pre class="code"> my $sref = \&amp;foo ; # Perl 5
</pre>
<pre class="code"> my $sref = &amp;foo ; # Perl 6
</pre>
<p><b>NOTE:</b> If one or more values reference the topic variable, <span class="code">$_</span>, the right-hand side of the assignment will be interpreted as a <a href="#_type_Block.pod6">Block</a>, not a Hash:</p>
<pre class="code">my @people = [
%( id =&gt; &quot;1A&quot;, firstName =&gt; &quot;Andy&quot;, lastName =&gt; &quot;Adams&quot; ),
%( id =&gt; &quot;2B&quot;, firstName =&gt; &quot;Beth&quot;, lastName =&gt; &quot;Burke&quot; ),
# ...
];
sub lookup-user (Hash $h) { #`(Do something...) $h }
my @names = map {
my $query = { name =&gt; &quot;$_&lt;firstName&gt; $_&lt;lastName&gt;&quot; };
say $query.^name; # Block
say $query&lt;name&gt;; # ERROR: Type Block does not support associative indexing
lookup-user($query); # Type check failed in binding $h; expected Hash but got Block
}, @people;</pre>
<p>Instead, you should either:</p>
<ul><li><p>1) use the <span class="code">%()</span> hash constructor:</p>
<pre class="code">my $query = %( name =&gt; &quot;$_&lt;firstName&gt; $_&lt;lastName&gt;&quot; );</pre>
</li></ul> <ul><li><p>2) assign to a Hash type (<span class="code">%</span>) directly:</p>
<pre class="code">my %query = name =&gt; &quot;$_&lt;firstName&gt; $_&lt;lastName&gt;&quot;; # No braces required</pre>
</li></ul> <ul><li><p>or 3) simply avoid the issue altogether by explicitly providing a name for the topic variable:</p>
<pre class="code">my @names = @people.map: -&gt; $person {
lookup-user( %( name =&gt; &quot;$person&lt;firstName&gt; $person&lt;lastName&gt;&quot; ) );
};</pre>
</li></ul> <p>See <a href="#_type_Hash.pod6-Hash_assignment">Hash assignment</a> for more details.</p>
<a name="t1.2.8"></a> <h2 id="_language_5to6-nutshell.pod6-Dereferencing">Dereferencing</h2>
<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 };
</pre>
<pre class="code"> # 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 parentheses can often be omitted, though the omission can reduce readability.</p>
<p>In Perl 5, the arrow operator, <span class="code">-&gt;</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-&gt;[7];
say $hashref-&gt;{'fire bad'};
say $subref-&gt;($foo, $bar);
</pre>
<pre class="code"> # 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 operator for dereferencing: see <a href="http://search.cpan.org/~shay/perl-5.20.1/pod/perl5200delta.pod#Experimental_Postfix_Dereferencing">Postfix Dereferencing</a> Such feature corresponds to 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 &gt;;
my @a = $arrayref-&gt;@*;
my %h = $hashref-&gt;%*;
my @slice = $arrayref-&gt;@[3..7];
</pre>
<pre class="code"> # Perl 6
my @a = $arrayref.list; # or @($arrayref)
my %h = $hashref.hash; # or %($hashref)
my @slice = $arrayref[3..7];
</pre>
<p>The &quot;Zen&quot; slice does the same thing:</p>
<pre class="code"> # Perl 6
my @a = $arrayref[];
my %h = $hashref{};
</pre>
<p>See <a href="https://design.perl6.org/S32/Containers.html">S32/Containers</a></p>
<a name="t1.3"></a> <h1 id="_language_5to6-nutshell.pod6-Operators">Operators</h1>
<p>See <a href="https://design.perl6.org/S03.html#Overview">S03/Operators</a> for full details on all operators.</p>
<p>Unchanged:</p>
<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; &gt; &lt;= &gt;=</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="t1.3.1"></a> <h2 id="_language_5to6-nutshell.pod6-,_(Comma)_List_Separator"><span class="code">,</span> (Comma) List Separator</h2>
<p>Unchanged, but note that in order to flatten an array variable to a list (in order to append or prefix more items) one should use the <span class="code">|</span> operator (see also <a href="#_type_Slip.pod6">Slip</a>). For instance:</p>
<pre class="code"> my @numbers = (100, 200, 300);
my @more_numbers = (500, 600, 700);
my @all_numbers = [|@numbers, 400, |@more_numbers];
</pre>
<p>That way one can concatenate arrays.</p>
<a name="t1.3.2"></a> <h2 id="_language_5to6-nutshell.pod6-&lt;=&gt;_cmp_Three-way_comparisons"><span class="code">&lt;=&gt; cmp</span> Three-way comparisons</h2>
<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;=&gt;</span> still forces numeric context.</p>
<p><span class="code">cmp</span> in Perl 6 does either <span class="code">&lt;=&gt;</span> or <span class="code">leg</span>, depending on the existing type of its arguments.</p>
<a name="t1.3.3"></a> <h2 id="_language_5to6-nutshell.pod6-~~_Smart-match_operator"><span class="code">~~</span> Smart-match operator</h2>
<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="#_routine_~~.pod6">~~</a> and <a href="https://design.perl6.org/S03.html#Smart_matching">S03/Smart matching</a></p>
<a name="t1.3.4"></a> <h2 id="_language_5to6-nutshell.pod6-&amp;_|_^_String_Bitwise_ops"><span class="code">&amp; | ^</span> String Bitwise ops</h2>
<a name="t1.3.5"></a> <h2 id="_language_5to6-nutshell.pod6-&amp;_|_^_Numeric_Bitwise_ops"><span class="code">&amp; | ^</span> Numeric Bitwise ops</h2>
<a name="t1.3.6"></a> <h2 id="_language_5to6-nutshell.pod6-&amp;_|_^_Boolean_ops"><span class="code">&amp; | ^</span> Boolean ops</h2>
<p>In Perl 5, <span class="code">&amp; | ^</span> were invoked according to the contents of their arguments. For example, <span class="code">31 | 33</span> returns a different result than <span class="code">&quot;31&quot; | &quot;33&quot;</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="t1.3.7"></a> <h2 id="_language_5to6-nutshell.pod6-&lt;&lt;_&gt;&gt;_Numeric_shift_left|right_ops"><span class="code">&lt;&lt; &gt;&gt;</span> Numeric shift left|right ops</h2>
<p>Replaced by <span class="code">+&lt;</span> and <span class="code">+&gt;</span> .</p>
<pre class="code"> say 42 &lt;&lt; 3; # Perl 5
</pre>
<pre class="code"> say 42 +&lt; 3; # Perl 6
</pre>
<a name="t1.3.8"></a> <h2 id="_language_5to6-nutshell.pod6-=&gt;_Fat_comma"><span class="code">=&gt;</span> Fat comma</h2>
<p>In Perl 5, <span class="code">=&gt;</span> acted just like a comma, but also quoted its left-hand side.</p>
<p>In Perl 6, <span class="code">=&gt;</span> is the <a href="#_type_Pair.pod6">Pair</a> operator, which is quite different in principle, but works the same in many situations.</p>
<p>If you were using <span class="code">=&gt;</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">sub get_the_loot { ... }; # Perl 6 stub
# Works in Perl 5 and Perl 6
my %hash = ( AAA =&gt; 1, BBB =&gt; 2 );
get_the_loot( 'diamonds', { quiet_level =&gt; 'very', quantity =&gt; 9 }); # Note the curly braces</pre>
<p>If you were using <span class="code">=&gt;</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">=&gt;</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 <a href="#_type_Signature.pod6-Slurpy_(A.K.A._Variadic)_Parameters">slurp a hash</a>. A better long-term solution is to change the sub's API to expect <a href="#_type_Pair.pod6">Pair</a>s; 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 =&gt; 'very', quantity =&gt; 9 );
</pre>
<pre class="code"> # Perl 6, original API
sub get_the_loot( $loot, *%options ) { # The * means to slurp everything
...
}
get_the_loot( 'diamonds', quiet_level =&gt; 'very', quantity =&gt; 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 =&gt; 'very' ); # Throws error for misspelled parameter name
</pre>
<a name="t1.3.9"></a> <h2 id="_language_5to6-nutshell.pod6-?_:_Ternary_operator"><span class="code">? :</span> Ternary operator</h2>
<p>The conditional operator <span class="code">? :</span> has been replaced by <span class="code">?? !!</span>:</p>
<pre class="code">my $result = ( $score &gt; 60 ) ? 'Pass' : 'Fail'; # Perl 5
</pre>
<pre class="code">my $result = ( $score &gt; 60 ) ?? 'Pass' !! 'Fail'; # Perl 6
</pre>
<a name="t1.3.10"></a> <h2 id="_language_5to6-nutshell.pod6-._(Dot)_String_Concatenation"><span class="code">.</span> (Dot) String Concatenation</h2>
<p>Replaced by the tilde.</p>
<p>Mnemonic: think of &quot;stitching&quot; together the two strings with needle and thread.</p>
<pre class="code"> $food = 'grape' . 'fruit'; # Perl 5
</pre>
<pre class="code"> $food = 'grape' ~ 'fruit'; # Perl 6
</pre>
<a name="t1.3.11"></a> <h2 id="_language_5to6-nutshell.pod6-x_List_Repetition_or_String_Repetition_operator"><span class="code">x</span> List Repetition or String Repetition operator</h2>
<p>In Perl 5, <span class="code">x</span> is the Repetition operator, which behaves differently in scalar or list contexts:</p>
<ul><li><p>in scalar context <span class="code">x</span> repeats a string;</p>
</li></ul> <ul><li><p>in list context <span class="code">x</span> repeats a list, but only if the left argument is parenthesized!</p>
</li></ul> <p>Perl 6 uses two different Repetition operators to achieve the above:</p>
<ul><li><p><span class="code">x</span> for string repetitions (in any context);</p>
</li></ul> <ul><li><p><span class="code">xx</span> for list repetitions (in any context).</p>
</li></ul> <p>Mnemonic: <span class="code">x</span> is short and <span class="code">xx</span> is long, so <span class="code">xx</span> 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
</pre>
<pre class="code"> # Perl 6
print '-' x 80; # Unchanged
@ones = 1 xx 80; # Parentheses no longer needed
@ones = 5 xx @ones; # Parentheses no longer needed
</pre>
<a name="t1.3.12"></a> <h2 id="_language_5to6-nutshell.pod6-.._..._Two_Dots_or_Three_Dots,_Range_op_or_Flipflop_op"><span class="code">..</span> <span class="code">...</span> Two Dots or Three Dots, Range op or Flipflop op</h2>
<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 <b>not</b> require 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="t1.3.13"></a> <h2 id="_language_5to6-nutshell.pod6-String_interpolation">String interpolation</h2>
<p>In Perl 5, <span class="code">&quot;${foo}s&quot;</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">&quot;{$foo}s&quot;</span></p>
<a name="t1.4"></a> <h1 id="_language_5to6-nutshell.pod6-Compound_Statements">Compound Statements</h1>
<a name="t1.4.1"></a> <h2 id="_language_5to6-nutshell.pod6-Conditionals">Conditionals</h2>
<a name="t1.4.1.1"></a> <h3 id="_language_5to6-nutshell.pod6-if_elsif_else_unless"><span class="code">if</span> <span class="code">elsif</span> <span class="code">else</span> <span class="code">unless</span></h3>
<p>Mostly unchanged; parentheses around the conditions are now optional, but if used, must not immediately follow the keyword, or it will be taken as a function call instead. Binding the conditional expression to a variable is also a little different:</p>
<pre class="code"> if (my $x = dostuff()) {...} # Perl 5
</pre>
<pre class="code"> if dostuff() -&gt; $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="t1.4.1.2"></a> <h3 id="_language_5to6-nutshell.pod6-given-when"><span class="code">given</span>-<span class="code">when</span></h3>
<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 &quot;a match&quot; {
# do-something();
}
when &quot;another match&quot; {
# 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="t1.4.2"></a> <h2 id="_language_5to6-nutshell.pod6-Loops">Loops</h2>
<a name="t1.4.2.1"></a> <h3 id="_language_5to6-nutshell.pod6-while_until"><span class="code">while</span> <span class="code">until</span></h3>
<p>Mostly unchanged; parentheses around the conditions are now optional, but if used, must not immediately follow the keyword, or it will be taken as a function call instead. Binding the conditional expression to a variable is also a little different:</p>
<pre class="code"> while (my $x = dostuff()) {...} # Perl 5
</pre>
<pre class="code"> while dostuff() -&gt; $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&gt;) { } # Perl 5
</pre>
<pre class="code"> for $IN_FH.lines { } # Perl 6
</pre>
<a name="t1.4.2.2"></a> <h3 id="_language_5to6-nutshell.pod6-do_while/until"><span class="code">do</span> <span class="code">while</span>/<span class="code">until</span></h3>
<pre class="code"> # Perl 5
do {
...
} while $x &lt; 10;
do {
...
} until $x &gt;= 10;
</pre>
<p>The construct is still present, but <span class="code">do</span> was renamed to <span class="code">repeat</span>, to better represent what the construct does:</p>
<pre class="code"> # Perl 6
repeat {
...
} while $x &lt; 10;
repeat {
...
} until $x &gt;= 10;
</pre>
<a name="t1.4.2.3"></a> <h3 id="_language_5to6-nutshell.pod6-for_foreach"><span class="code">for</span> <span class="code">foreach</span></h3>
<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, the keywords are interchangeable; the Perl 5 compiler looks for the semi-colons within the parentheses 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 parentheses <b>are</b> still required.</p>
<pre class="code"> for ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 5
</pre>
<pre class="code"> loop ( my $i = 1; $i &lt;= 10; $i++ ) { ... } # Perl 6
</pre>
<p>The loop-iterator form is named <span class="code">for</span> in Perl 6 and <span class="code">foreach</span> is no longer a keyword. The <span class="code">for</span> loop has the following rules:</p>
<ul><li><p>parentheses are optional;</p>
</li></ul> <ul><li><p>the iteration variable, if any, has been moved from appearing before the list, to appearing after the list and an added arrow operator;</p>
</li></ul> <ul><li><p>the iteration variable is now always lexical: <span class="code">my</span> is neither needed nor allowed;</p>
</li></ul> <ul><li><p>the iteration variable is a <i>read-only</i> alias to the current list element (in Perl 5 it is a <i>read-write</i> alias!). If a read-write alias is required, change the <span class="code">-&gt;</span> before the iteration variable to a <span class="code">&lt;-&gt;</span>. When translating from Perl 5, inspect the use of the loop variable to decide if read-write is needed.</p>
</li></ul> <pre class="code"> for my $car (@cars) {...} # Perl 5; read-write
</pre>
<pre class="code"> for @cars -&gt; $car {...} # Perl 6; read-only
for @cars &lt;-&gt; $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;-&gt;</span> and explicitly specify <span class="code">$_</span>.</p>
<pre class="code"> for (@cars) {...} # Perl 5; $_ is read-write
</pre>
<pre class="code"> for @cars {...} # Perl 6; $_ is read-only
for @cars &lt;-&gt; $_ {...} # Perl 6; $_ is read-write
</pre>
<p>It is possible to consume more than one element of the list in each iteration simply specifying more than one variable after the arrow operator:</p>
<pre class="code">my @array = 1..10;
for @array -&gt; $first, $second {
say &quot;First is $first, second is $second&quot;;
}
</pre>
<a name="t1.4.2.3.1"></a> <h4 id="_language_5to6-nutshell.pod6-each"><span class="code">each</span></h4>
<p>Here is the equivalent to Perl 5’s <span class="code">while…each(%hash)</span> or <span class="code">while…each(@array)</span> (i.e., iterating over both the keys/indices and values of a data structure) in Perl 6:</p>
<pre class="code"> while (my ($i, $v) = each(@array)) { ... } # Perl 5
</pre>
<pre class="code"> for @array.kv -&gt; $i, $v { ... } # Perl 6
</pre>
<pre class="code"> while (my ($k, $v) = each(%hash)) { ... } # Perl 5
</pre>
<pre class="code"> for %hash.kv -&gt; $k, $v { ... } # Perl 6
</pre>
<a name="t1.4.3"></a> <h2 id="_language_5to6-nutshell.pod6-Flow_Control_statements">Flow Control statements</h2>
<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="t1.4.3.1"></a> <h3 id="_language_5to6-nutshell.pod6-continue"><span class="code">continue</span></h3>
<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 .= ':'
}
</pre>
<pre class="code"> # Perl 6
my $str = '';
for 1..5 {
next if $_ % 2 == 1;
$str ~= $_;
NEXT {
$str ~= ':'
}
}
</pre>
<a name="t1.5"></a> <h1 id="_language_5to6-nutshell.pod6-Functions">Functions</h1>
NOTE FOR EDITORS: When adding functions, please place them in
alphabetical order.
<a name="t1.5.1"></a> <h2 id="_language_5to6-nutshell.pod6-Built-ins_with_bare_blocks">Built-ins with bare blocks</h2>
<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 &quot;bars&quot; } @foo; # Perl 5
</pre>
<pre class="code"> my @results = grep { $_ eq &quot;bars&quot; }, @foo; # Perl 6
</pre>
<a name="t1.5.2"></a> <h2 id="_language_5to6-nutshell.pod6-delete"><span class="code">delete</span></h2>
<p>Turned into an adverb of the <a href="#0-{}_Hash_indexing/slicing"><span class="code">{}</span> hash subscripting</a> and <a href="#0-[]_Array_indexing/slicing"><span class="code">[]</span> array subscripting</a> operators.</p>
<pre class="code"> my $deleted_value = delete $hash{$key}; # Perl 5
</pre>
<pre class="code"> my $deleted_value = %hash{$key}:delete; # Perl 6 - use :delete adverb
</pre>
<pre class="code"> my $deleted_value = delete $array[$i]; # Perl 5
</pre>
<pre class="code"> my $deleted_value = @array[$i]:delete; # Perl 6 - use :delete adverb
</pre>
<a name="t1.5.3"></a> <h2 id="_language_5to6-nutshell.pod6-exists"><span class="code">exists</span></h2>
<p>Turned into an adverb of the <a href="#0-{}_Hash_indexing/slicing"><span class="code">{}</span> hash subscripting</a> and <a href="#0-[]_Array_indexing/slicing"><span class="code">[]</span> array subscripting</a> operators.</p>
<pre class="code"> say &quot;element exists&quot; if exists $hash{$key}; # Perl 5
</pre>
<pre class="code"> say &quot;element exists&quot; if %hash{$key}:exists; # Perl 6 - use :exists adverb
</pre>
<pre class="code"> say &quot;element exists&quot; if exists $array[$i]; # Perl 5
</pre>
<pre class="code"> say &quot;element exists&quot; if @array[$i]:exists; # Perl 6 - use :exists adverb
</pre>
<a name="t1.6"></a> <h1 id="_language_5to6-nutshell.pod6-Regular_Expressions_(_Regex_/_Regexp_)">Regular Expressions ( Regex / Regexp )</h1>
<a name="t1.6.1"></a> <h2 id="_language_5to6-nutshell.pod6-Change_=~_and_!~_to_~~_and_!~~_.">Change <span class="code">=~</span> and <span class="code">!~</span> to <span class="code">~~</span> and <span class="code">!~~</span> .</h2>
<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
</pre>
<pre class="code"> next if $line ~~ /static/ ; # Perl 6
</pre>
<pre class="code"> next if $line !~ /dynamic/ ; # Perl 5
</pre>
<pre class="code"> next if $line !~~ /dynamic/ ; # Perl 6
</pre>
<pre class="code"> $line =~ s/abc/123/; # Perl 5
</pre>
<pre class="code"> $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="t1.6.2"></a> <h2 id="_language_5to6-nutshell.pod6-Captures_start_with_0,_not_1">Captures start with 0, not 1</h2>
<pre class="code"> /(.+)/ and print $1; # Perl 5
</pre>
<pre class="code"> /(.+)/ and print $0; # Perl 6
</pre>
<a name="t1.6.3"></a> <h2 id="_language_5to6-nutshell.pod6-Move_modifiers">Move modifiers</h2>
<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
</pre>
<pre class="code"> next if $line ~~ m:i/static/ ; # Perl 6
</pre>
<a name="t1.6.4"></a> <h2 id="_language_5to6-nutshell.pod6-Add_:P5_or_:Perl5_adverb">Add :P5 or :Perl5 adverb</h2>
<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
</pre>
<pre class="code"> next if $line ~~ m:P5/[aeiou]/ ; # Perl 6, using P5 modifier
next if $line ~~ m/ &lt;[aeiou]&gt; / ; # Perl 6, native new syntax
</pre>
<a name="t1.6.5"></a> <h2 id="_language_5to6-nutshell.pod6-Special_matchers_generally_fall_under_the_&lt;&gt;_syntax">Special matchers generally fall under the &lt;&gt; syntax</h2>
<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;&gt;</span>.</p>
<p>For character classes, this means that:</p>
<ul><li><p><span class="code">[abc]</span> becomes <span class="code">&lt;[abc]&gt;</span></p>
</li></ul> <ul><li><p><span class="code">[^abc]</span> becomes <span class="code">&lt;-[abc]&gt;</span></p>
</li></ul> <ul><li><p><span class="code">[a-zA-Z]</span> becomes <span class="code">&lt;[a..zA..Z]&gt;</span></p>
</li></ul> <ul><li><p><span class="code">[[:upper:]]</span> becomes <span class="code">&lt;:Upper&gt;</span></p>
</li></ul> <ul><li><p><span class="code">[abc[:upper:]]</span> becomes <span class="code">&lt;[abc]+:Upper&gt;</span></p>
</li></ul> <p>For lookaround assertions:</p>
<ul><li><p><span class="code">(?=[abc])</span> becomes <span class="code">&lt;?[abc]&gt;</span></p>
</li></ul> <ul><li><p><span class="code">(?=ar?bitrary* pattern)</span> becomes <span class="code">&lt;before ar?bitrary* pattern&gt;</span></p>
</li></ul> <ul><li><p><span class="code">(?!=[abc])</span> becomes <span class="code">&lt;![abc]&gt;</span></p>
</li></ul> <ul><li><p><span class="code">(?!=ar?bitrary* pattern)</span> becomes <span class="code">&lt;!before ar?bitrary* pattern&gt;</span></p>
</li></ul> <ul><li><p><span class="code">(?&lt;=ar?bitrary* pattern)</span> becomes <span class="code">&lt;after ar?bitrary* pattern&gt;</span></p>
</li></ul> <ul><li><p><span class="code">(?&lt;!ar?bitrary* pattern)</span> becomes <span class="code">&lt;!after ar?bitrary* pattern&gt;</span></p>
</li></ul> <p>For more info see <a href="#_language_regexes.pod6-Lookahead_assertions_&lt;?before_pattern&gt;">lookahead assertions</a>.</p>
<p>(Unrelated to &lt;&gt; syntax, the &quot;lookaround&quot; <span class="code">/foo\Kbar/</span> becomes <span class="code">/foo &lt;( bar )&gt; /</span></p>
<ul><li><p><span class="code">(?(?{condition))yes-pattern|no-pattern)</span> becomes <span class="code">[ &lt;?{condition}&gt; yes-pattern | no-pattern ]</span></p>
</li></ul> <a name="t1.6.6"></a> <h2 id="_language_5to6-nutshell.pod6-Longest_token_matching_(LTM)_displaces_alternation">Longest token matching (LTM) displaces alternation</h2>
<p>In Perl 6 regexes, <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>However, if a regex written with <span class="code">||</span> is inherited or composed into a grammar that uses <span class="code">|</span> either by design or typo, the result may not work as expected. So when the matching process becomes complex, you finally need to have some understanding of both, especially how LTM strategy works. Besides, <span class="code">|</span> may be a better choice for grammar reuse.</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="t1.6.6.1"></a> <h3 id="_language_5to6-nutshell.pod6-Comments">Comments</h3>
<p>As with Perl 5, comments work as usual in regexes.</p>
<pre class="code">/ word #`(match lexical &quot;word&quot;) /</pre>
<a name="t1.7"></a> <h1 id="_language_5to6-nutshell.pod6-Pragmas">Pragmas</h1>
<a name="t1.7.0.1"></a> <h3 id="_language_5to6-nutshell.pod6-strict"><span class="code">strict</span></h3>
<p>Strict mode is now on by default.</p>
<a name="t1.7.0.2"></a> <h3 id="_language_5to6-nutshell.pod6-warnings"><span class="code">warnings</span></h3>
<p>Warnings are now on by default.</p>
<p><span class="code">no warnings</span> is currently <a href="#_language_glossary.pod6-NYI">NYI</a>, but putting things in a quietly {} block will silence.</p>
<a name="t1.7.0.3"></a> <h3 id="_language_5to6-nutshell.pod6-autodie"><span class="code">autodie</span></h3>
<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, '&gt;', $output_path; # Throws exception on error
</pre>
<pre class="code"> # 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="t1.7.0.4"></a> <h3 id="_language_5to6-nutshell.pod6-base"><span class="code">base</span></h3>
<a name="t1.7.0.5"></a> <h3 id="_language_5to6-nutshell.pod6-parent"><span class="code">parent</span></h3>
<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);
</pre>
<pre class="code"> # Perl 6
class Cat is Animal {};
</pre>
<a name="t1.7.0.6"></a> <h3 id="_language_5to6-nutshell.pod6-bigint_bignum_bigrat"><span class="code">bigint</span> <span class="code">bignum</span> <span class="code">bigrat</span></h3>
<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="t1.7.0.7"></a> <h3 id="_language_5to6-nutshell.pod6-constant"><a name="1"></a><span class="code">constant</span></h3>
<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">=&gt;</span> to <span class="code">=</span>.</p>
<pre class="code"> use constant DEBUG =&gt; 0; # Perl 5
</pre>
<pre class="code"> constant DEBUG = 0; # Perl 6
</pre>
<pre class="code"> use constant pi =&gt; 4 * atan2(1, 1); # Perl 5
</pre>
<pre class="code"> pi, e, i; # built-in constants in Perl 6
</pre>
<a name="t1.7.0.8"></a> <h3 id="_language_5to6-nutshell.pod6-encoding"><span class="code">encoding</span></h3>
<p>TODO Allows you to write your script in non-ascii or non-utf8</p>
<a name="t1.7.0.9"></a> <h3 id="_language_5to6-nutshell.pod6-integer"><span class="code">integer</span></h3>
<p>Perl pragma to use integer arithmetic instead of floating point</p>
<a name="t1.7.0.10"></a> <h3 id="_language_5to6-nutshell.pod6-lib"><span class="code">lib</span></h3>
<p>Manipulate @INC at compile time</p>
<a name="t1.7.0.11"></a> <h3 id="_language_5to6-nutshell.pod6-mro"><span class="code">mro</span></h3>
<p>No longer relevant.</p>
<p>In Perl 6, method calls now always use the C3 method resolution order.</p>
<a name="t1.7.0.12"></a> <h3 id="_language_5to6-nutshell.pod6-utf8"><span class="code">utf8</span></h3>
<p>No longer relevant.</p>
<p>In Perl 6, source code is expected to be in utf8 encoding.</p>
<a name="t1.7.0.13"></a> <h3 id="_language_5to6-nutshell.pod6-vars"><span class="code">vars</span></h3>
<p>Discouraged in Perl 5. See <a href="http://perldoc.perl.org/vars.html">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="t1.8"></a> <h1 id="_language_5to6-nutshell.pod6-Command-line_flags">Command-line flags</h1>
<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="t1.8.0.1"></a> <h3 id="_language_5to6-nutshell.pod6--a"><span class="code">-a</span></h3>
<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="t1.8.0.2"></a> <h3 id="_language_5to6-nutshell.pod6--F"><span class="code">-F</span></h3>
<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="t1.8.0.3"></a> <h3 id="_language_5to6-nutshell.pod6--l"><span class="code">-l</span></h3>
<p>This is now the default behavior.</p>
<a name="t1.8.0.4"></a> <h3 id="_language_5to6-nutshell.pod6--M_-m"><span class="code">-M</span> <span class="code">-m</span></h3>
<p>Only <span class="code">-M</span> remains. And, as you can no longer use the &quot;no Module&quot; syntax, the use of <span class="code">-</span> with <span class="code">-M</span> to &quot;no&quot; a module is no longer available.</p>
<a name="t1.8.0.5"></a> <h3 id="_language_5to6-nutshell.pod6--E"><span class="code">-E</span></h3>
<p>Since all features are already enabled, just use lowercase <span class="code">-e</span> .</p>
<a name="t1.8.0.6"></a> <h3 id="_language_5to6-nutshell.pod6--d,_-dt,_-d:foo,_-D,_etc."><span class="code">-d</span>, <span class="code">-dt</span>, <span class="code">-d:foo</span>, <span class="code">-D</span>, etc.</h3>
<p>Replaced with the <span class="code">++BUG</span> metasyntactic option.</p>
<a name="t1.8.0.7"></a> <h3 id="_language_5to6-nutshell.pod6--s">-s</h3>
<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 &quot;$xyz\n&quot; }
./example.pl -xyz=5
5
</pre>
<pre class="code"> # Perl 6
sub MAIN( Int :$xyz ) {
say $xyz if $xyz.defined;
}
</pre>
<pre class="code"> 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>Removed.</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 <a href="https://design.perl6.org/S19.html#Removed_Syntactic_Features">S19#Removed Syntactic Features</a>.</p>
<ul><li><p><span class="code">-w</span></p>
</li></ul> <p>This is now the default behavior.</p>
<a name="t1.9"></a> <h1 id="_language_5to6-nutshell.pod6-File-related_operations">File-related operations</h1>
<a name="t1.9.1"></a> <h2 id="_language_5to6-nutshell.pod6-Reading_the_lines_of_a_text_file_into_an_array">Reading the lines of a text file into an array</h2>
<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, &quot;&lt;&quot;, &quot;file&quot; or die &quot;$!&quot;;
my @lines = &lt;$fh&gt;;
close $fh;
</pre>
<p>In Perl 6, this has been simplified to</p>
<pre class="code">my @lines = &quot;file&quot;.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 &quot;test-file&quot;, q:to/END/;
first line
second line
third line
END
# read the file
my @lines = &quot;test-file&quot;.IO.slurp.split(/\n/);
say @lines.elems; #-&gt; 4</pre>
<a name="t1.9.2"></a> <h2 id="_language_5to6-nutshell.pod6-Trapping_the_standard_output_of_executables.">Trapping the standard output of executables.</h2>
<p>Whereas in Perl 5 you would do:</p>
<pre class="code"> my $arg = 'Hello';
my $captured = `echo \Q$arg\E`;
my $captured = qx(echo \Q$arg\E);
</pre>
<p>Or using String::ShellQuote (because <span class="code">\Q…\E</span> is not completely right):</p>
<pre class="code"> my $arg = shell_quote 'Hello';
my $captured = `echo $arg`;
my $captured = qx(echo $arg);
</pre>
<p>In Perl 6, you will probably want to run commands without using the shell:</p>
<pre class="code">my $arg = 'Hello';
my $captured = run('echo', $arg, :out).out.slurp-rest;
my $captured = run(«echo &quot;$arg&quot;», :out).out.slurp-rest;</pre>
<p>You can also use the shell if you really want to:</p>
<pre class="code">my $arg = 'Hello';
my $captured = shell(&quot;echo $arg&quot;, :out).out.slurp-rest;
my $captured = qqx{echo $arg};</pre>
<p>But beware that in this case there is <b>no protection at all</b>! <span class="code">run</span> does not use the shell, so there is no need to escape the arguments (arguments are passed directly). If you are using <span class="code">shell</span> or <span class="code">qqx</span>, then everything ends up being one long string which is then passed to the shell. Unless you validate your arguments very carefully, there is a high chance to introduce shell injection vulnerabilities with such code.</p>
<a name="t1.10"></a> <h1 id="_language_5to6-nutshell.pod6-Environment_variables">Environment variables</h1>
<a name="t1.10.1"></a> <h2 id="_language_5to6-nutshell.pod6-Perl_module_library_path">Perl module library path</h2>
<p>In Perl 5 one of the environment variables to specify extra search paths for Perl modules is <span class="code">PERL5LIB</span>.</p>
<pre class="code"> $ PERL5LIB=&quot;/some/module/lib&quot; 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 <a id="i2" name="PERL6LIB"></a><span class="indexed"><span class="code">PERL6LIB</span></span>:</p>
<pre class="code"> $ PERL6LIB=&quot;/some/module/lib&quot; perl6 program.p6
</pre>
<p>In Perl 5 one uses the ':' (colon) as a directory separator for <span class="code">PERL5LIB</span>, but in Perl 6 one uses the ',' (comma). For example:</p>
<pre class="code"> $ export PERL5LIB=/module/dir1:/module/dir2;
</pre>
<p>but</p>
<pre class="code"> $ export PERL6LIB=/module/dir1,/module/dir2;
</pre>
<p>(Perl 6 does not recognize either the <span class="code">PERL5LIB</span> or the older Perl environment variable <span class="code">PERLLIB</span>.)</p>
<p>As with Perl 5, 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="t1.11"></a> <h1 id="_language_5to6-nutshell.pod6-Misc.">Misc.</h1>
<a name="t1.11.1"></a> <h2 id="_language_5to6-nutshell.pod6-'0'_is_True"><span class="code">'0'</span> is True</h2>
<p>Unlike Perl 5, a string containing nothing but zero ('0') is <span class="code">True</span>. As Perl 6 has types in core, that makes more sense. This also means the common pattern:</p>
<pre class="code"> ... if defined $x and length $x; # or just length() in modern perls
</pre>
<p>In Perl 6 becomes a simple</p>
<pre class="code"> ... if $x;
</pre>
<a name="t1.11.2"></a> <h2 id="_language_5to6-nutshell.pod6-dump"><span class="code">dump</span></h2>
<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="t1.11.3"></a> <h2 id="_language_5to6-nutshell.pod6-AUTOLOAD">AUTOLOAD</h2>
<p>The <a href="#_language_typesystem.pod6-index-entry-FALLBACK_(method)"><span class="code">FALLBACK</span> method</a> provides similar functionality.</p>
<a name="t1.11.4"></a> <h2 id="_language_5to6-nutshell.pod6-Importing_specific_functions_from_a_module">Importing specific functions from a module <a name="3"></a></h2>
<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 &quot;foo $a&quot; }
sub bar($b) is export { say &quot;bar $b&quot; }
sub baz($z) { say &quot;baz $z&quot; }
</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); #=&gt; &quot;foo 1&quot;
bar(2); #=&gt; &quot;bar 2&quot;
</pre>
<p>If one tries to use <span class="code">baz</span> an &quot;Undeclared routine&quot; 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.c;
sub EXPORT(*@import-list) {
my %exportable-subs =
'&amp;foo' =&gt; &amp;foo,
'&amp;bar' =&gt; &amp;bar,
;
my %subs-to-export;
for @import-list -&gt; $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 &quot;foo, $a, $b, $c&quot; }
sub bar($a) { say &quot;bar, $a&quot; }
sub baz($z) { say &quot;baz, $z&quot; }
</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&gt;;
foo(1); #=&gt; &quot;foo 1&quot;
</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 &quot;Undeclared routine&quot; error at compile time:</p>
<pre class="code"> use Bar &lt;foo&gt;;
foo(1);
bar(5); #!&gt; &quot;Undeclared routine: bar used at line 3&quot;
</pre>
<p>however, this will work</p>
<pre class="code"> use Bar &lt;foo bar&gt;;
foo(1); #=&gt; &quot;foo 1&quot;
bar(5); #=&gt; &quot;bar 5&quot;
</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&gt;;
baz(3); #!&gt; &quot;Undeclared routine: baz used at line 2&quot;
</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="t1.12"></a> <h1 id="_language_5to6-nutshell.pod6-Core_modules">Core modules</h1>
<a name="t1.12.0.1"></a> <h3 id="_language_5to6-nutshell.pod6-Data::Dumper"><span class="code">Data::Dumper</span></h3>
<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 =&gt; 'apple', type =&gt; 'fruit' },
{ NAME =&gt; 'cabbage', type =&gt; 'no, please no' },
);
# Perl 5
use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper \@array_of_hashes; # Note the backslash.
</pre>
<pre class="code"> # 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-&gt;Dump(
[ $foo, $bar, \@baz ],
[ qw( foo bar *baz ) ],
);
# Output
$foo = 42;
$bar = 44;
@baz = (
16,
32,
64,
'Hike!'
);
</pre>
<pre class="code"> # Perl 6
say [ :$foo, :$bar, :@baz ].perl;
# Output
[&quot;foo&quot; =&gt; 42, &quot;bar&quot; =&gt; 44, &quot;baz&quot; =&gt; [16, 32, 64, &quot;Hike!&quot;]]
</pre>
<a name="t1.12.0.2"></a> <h3 id="_language_5to6-nutshell.pod6-Getopt::Long"><span class="code">Getopt::Long</span></h3>
<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' =&gt; \( my $length = 24 ), # numeric
'file=s' =&gt; \( my $data = 'file.dat' ), # string
'verbose' =&gt; \( 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 &quot;abc&quot; invalid for option length (number expected)
Died at c.pl line 3.
</pre>
<pre class="code"> # 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');
}
</pre>
<pre class="code"> 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&gt;] [--file=&lt;Any&gt;] [--verbose]
</pre>
<p>Note that Perl 6 auto-generates a full usage message on error in command-line parsing.</p>
<a name="t1.13"></a> <h1 id="_language_5to6-nutshell.pod6-Automated_Translation">Automated Translation</h1>
<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="t1.13.1"></a> <h2 id="_language_5to6-nutshell.pod6-Blue_Tiger">Blue Tiger</h2>
<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/">https://github.com/Util/Blue_Tiger/</a></p>
<a name="t1.13.2"></a> <h2 id="_language_5to6-nutshell.pod6-Perlito">Perlito</h2>
<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://fglock.github.io/Perlito/perlito/perlito5.html">http://fglock.github.io/Perlito/perlito/perlito5.html</a></p>
<a name="t1.13.3"></a> <h2 id="_language_5to6-nutshell.pod6-MAD">MAD</h2>
<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="t1.13.4"></a> <h2 id="_language_5to6-nutshell.pod6-Perl-ToPerl6">Perl-ToPerl6</h2>
<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="t1.14"></a> <h1 id="_language_5to6-nutshell.pod6-Other_sources_of_translation_knowledge">Other sources of translation knowledge</h1>
<ul><li><p><a href="https://perlgeek.de/en/article/5-to-6">https://perlgeek.de/en/article/5-to-6</a></p>
</li></ul> <ul><li><p><a href="https://github.com/Util/Blue_Tiger/">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/">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">http://www.perlfoundation.org/perl6/index.cgi?perl_6_delta_tablet</a></p>
</li></ul></div>
<!-- /language/5to6-perlfunc.pod6 --><div class="pod-body"><a id="_language_5to6-perlfunc.pod6"></a><a name="t2"></a><h1 class="title">2 5to6-perlfunc</h1> <p class="subtitle">Perl 5 to Perl 6 guide - functions</p> <a name="t2.1"></a> <h1 id="_language_5to6-perlfunc.pod6-DESCRIPTION">DESCRIPTION</h1>
<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="t2.2"></a> <h1 id="_language_5to6-perlfunc.pod6-NOTE">NOTE</h1>
<p>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, follow the links in this document to their respective 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 &quot;function&quot; here will mean a function in the style of <span class="code">func(@args)</span>, while &quot;method&quot; will refer to a function in the style of <span class="code">@args.func</span>.</p>
<a name="t2.3"></a> <h1 id="_language_5to6-perlfunc.pod6-Alphabetical_Listing_of_Perl_Functions">Alphabetical Listing of Perl Functions</h1>
<a name="t2.3.1"></a> <h2 id="_language_5to6-perlfunc.pod6-Filetests">Filetests</h2>
<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">'/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"> $fh.r
</pre>
<p>Most of the former filetests have colon equivalents for use with smart match:</p>
<table>
<tr><td>:e Exists</td></tr>
<tr><td>:d Directory</td></tr>
<tr><td>:f File</td></tr>
<tr><td>:l Symbolic link</td></tr>
<tr><td>:r Readable</td></tr>
<tr><td>:w Writable</td></tr>
<tr><td>:x Executable</td></tr>
<tr><td>:s Size</td></tr>
<tr><td>:z Zero size</td></tr>
</table> <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"> $fh.modified; # -M $fh
$fh.accessed; # -A $fh
$fh.changed; # -C $fh
</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="#_type_IO::Path.pod6-File_test_operators">File test operators</a>.</p>
<p>There is more information on reading and writing files at <a href="#_language_io.pod6">io</a>. Also, the section on <span class="code">open()</span> below may be helpful.</p>
<a name="t2.3.2"></a> <h2 id="_language_5to6-perlfunc.pod6-abs">abs</h2>
<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="t2.3.3"></a> <h2 id="_language_5to6-perlfunc.pod6-accept">accept</h2>
<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="t2.3.4"></a> <h2 id="_language_5to6-perlfunc.pod6-alarm">alarm</h2>
<ul><li><p>alarm SECONDS</p>
</li></ul> <p><span class="code">alarm()</span> is no more. But it is possible to have code execute after a certain time has elapsed, or at a given time:</p>
<pre class="code">Promise.in(5).then: { say &quot;five seconds have passed&quot; }
Promise.at(now + 5).then: { say &quot;five seconds have passed&quot; }</pre>
<p>In Perl 6, this does *not* involve any (dummy) signals.</p>
<a name="t2.3.5"></a> <h2 id="_language_5to6-perlfunc.pod6-atan2">atan2</h2>
<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">atan2(100);
100.atan2;</pre>
<a name="t2.3.6"></a> <h2 id="_language_5to6-perlfunc.pod6-bind">bind</h2>
<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="t2.3.7"></a> <h2 id="_language_5to6-perlfunc.pod6-binmode">binmode</h2>
<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(&quot;path/to/file&quot;, :bin);</span></p>
<a name="t2.3.8"></a> <h2 id="_language_5to6-perlfunc.pod6-bless">bless</h2>
<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 &quot;Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.&quot; 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="t2.3.9"></a> <h2 id="_language_5to6-perlfunc.pod6-break">break</h2>
<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="#_language_control.pod6-proceed">here</a>.</p>
<a name="t2.3.10"></a> <h2 id="_language_5to6-perlfunc.pod6-caller">caller</h2>
<ul><li><p>caller EXPR</p>
</li></ul> <p>There are a couple different ways to get at caller information in Perl 6. The basic functionality is provided through <a href="#_routine_callframe.pod6">callframe</a> now. However, Perl 6 constructs call frames for regular blocks, not just for subroutines, so there are more frames to look through. The following will retrieve the basic information that <span class="code">caller</span> can return:</p>
<pre class="code">my $frame = callframe(0); # OR just callframe()
my ($subroutine, $package);
if $frame.code ~~ Routine {
$subroutine = $frame.code.name;
$package = $frame.code.package;
}
my $file = $frame.file;
my $line = $frame.line;</pre>
<p>Many of the other details returned by <span class="code">caller</span> are specific to Perl 5 and have no meaning in Perl 6.</p>
<p>You can also get some of the information for the current frame or routine frame by using the dynamic variables <a href="#_language_variables.pod6-Compile-time_variables"><span class="code">&amp;?ROUTINE</span></a>, <a href="#_language_variables.pod6-Compile-time_variables"><span class="code">&amp;?BLOCK</span></a>, <a href="#_language_variables.pod6-Compile-time_variables"><span class="code">$?PACKAGE</span></a>, <a href="#_language_variables.pod6-Compile-time_variables"><span class="code">$?FILE</span></a>, and <a href="#_language_variables.pod6-Compile-time_variables"><span class="code">$?LINE</span></a>. For many purposes, <a href="#_type_Backtrace.pod6">Backtrace</a> may provide an easier way to browse through the call stack.</p>
<a name="t2.3.11"></a> <h2 id="_language_5to6-perlfunc.pod6-chdir">chdir</h2>
<ul><li><p>chdir EXPR</p>
</li></ul> <p>Works as it does in Perl 5.</p>
<a name="t2.3.12"></a> <h2 id="_language_5to6-perlfunc.pod6-chmod">chmod</h2>
<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="t2.3.13"></a> <h2 id="_language_5to6-perlfunc.pod6-chomp">chomp</h2>
<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> a copy of the target with a final logical newline removed, e.g. <span class="code">$x = &quot;howdy\n&quot;;$y = chomp($x);</span> results in <span class="code">$x</span> containing &quot;howdy\n&quot; and <span class="code">$y</span> containing &quot;howdy&quot;. Also works as a method, e.g. <span class="code">$y = $x.chomp</span>. As with many other methods, also works with assignment to modify the target in place, e.g. <span class="code">$x.=chomp</span> results in <span class="code">$x</span> containing &quot;howdy&quot;.</p>
<a name="t2.3.14"></a> <h2 id="_language_5to6-perlfunc.pod6-chop">chop</h2>
<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 = &quot;howdy&quot;;$y = chop($x);</span> results in <span class="code">$x</span> being &quot;howdy&quot; and <span class="code">$y</span> being &quot;howd&quot;. Also works as a method: <span class="code">$y = $x.chop</span></p>
<a name="t2.3.15"></a> <h2 id="_language_5to6-perlfunc.pod6-chown">chown</h2>
<ul><li><p>chown LIST</p>
</li></ul> <p><span class="code">chown</span> is not in Perl 6.</p>
<a name="t2.3.16"></a> <h2 id="_language_5to6-perlfunc.pod6-chr">chr</h2>
<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">chr(65); # &quot;A&quot;
65.chr; # &quot;A&quot;</pre>
<a name="t2.3.17"></a> <h2 id="_language_5to6-perlfunc.pod6-chroot">chroot</h2>
<ul><li><p>chroot FILENAME</p>
</li></ul> <p>Apparently this is not in Perl 6.</p>
<a name="t2.3.18"></a> <h2 id="_language_5to6-perlfunc.pod6-close">close</h2>
<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="t2.3.19"></a> <h2 id="_language_5to6-perlfunc.pod6-closedir">closedir</h2>
<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="t2.3.20"></a> <h2 id="_language_5to6-perlfunc.pod6-connect">connect</h2>
<ul><li><p>connect SOCKET, NAME</p>
</li></ul> <p>Use <a href="#_routine_connect.pod6">connect</a> from <a href="#_type_IO::Socket::Async.pod6">IO::Socket::Async</a> for an asynchronous socket or create a <a href="#_type_IO::Socket::INET.pod6">IO::Socket::INET</a> socket for a synchronous one.</p>
<a name="t2.3.21"></a> <h2 id="_language_5to6-perlfunc.pod6-continue">continue</h2>
<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="t2.3.22"></a> <h2 id="_language_5to6-perlfunc.pod6-cos">cos</h2>
<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="t2.3.23"></a> <h2 id="_language_5to6-perlfunc.pod6-crypt">crypt</h2>
<ul><li><p>crypt PLAINTEXT, SALT</p>
</li></ul> <p>This appears not to have made it into Perl 6.</p>
<a name="t2.3.24"></a> <h2 id="_language_5to6-perlfunc.pod6-dbm_functions">dbm functions</h2>
<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="t2.3.25"></a> <h2 id="_language_5to6-perlfunc.pod6-defined">defined</h2>
<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="t2.3.26"></a> <h2 id="_language_5to6-perlfunc.pod6-delete">delete</h2>
<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="t2.3.27"></a> <h2 id="_language_5to6-perlfunc.pod6-die">die</h2>
<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="#_language_exceptions.pod6">exceptions</a>. To omit the stacktrace and location, like Perl 5's <span class="code">die &quot;...\n&quot;</span>, use:</p>
<pre class="code">note &quot;...&quot;;
exit 1;</pre>
<a name="t2.3.28"></a> <h2 id="_language_5to6-perlfunc.pod6-do">do</h2>
<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="t2.3.29"></a> <h2 id="_language_5to6-perlfunc.pod6-dump">dump</h2>
<ul><li><p>dump LABEL</p>
</li></ul> <p>According to S29, <span class="code">dump</span> has been... dumped.</p>
<a name="t2.3.30"></a> <h2 id="_language_5to6-perlfunc.pod6-each">each</h2>
<ul><li><p>each HASH</p>
</li></ul> <p>There is no exact equivalent, but you can use <span class="code">%hash.kv</span> which returns a list of keys and values. For example: <span class="code">for %hash.kv -&gt; $k, $v { say &quot;$k: $v&quot; } </span></p>
<p>Incidentally, what we have there with the <span class="code">-&gt; </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">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">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">https://en.wikibooks.org/wiki/Perl_6_Programming/Blocks_and_Closures#Pointy_Blocks</a></p>
<a name="t2.3.31"></a> <h2 id="_language_5to6-perlfunc.pod6-eof">eof</h2>
<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="t2.3.32"></a> <h2 id="_language_5to6-perlfunc.pod6-eval">eval</h2>
<ul><li><p>eval EXPR</p>
</li></ul> <ul><li><p>eval EXPR</p>
</li></ul> <p>Replaced by <a href="#_routine_EVAL.pod6">EVAL</a>. Note that <span class="code">EVAL</span> does not do any <a href="#_language_exceptions.pod6">exception handling</a>!</p>
<a name="t2.3.33"></a> <h2 id="_language_5to6-perlfunc.pod6-evalbytes">evalbytes</h2>
<ul><li><p>evalbytes EXPR</p>
</li></ul> <p>No equivalent.</p>
<a name="t2.3.34"></a> <h2 id="_language_5to6-perlfunc.pod6-exec">exec</h2>
<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>
<p>Neither of these workarounds have the behavior (on Unix-like systems) of <i>replacing</i> your Perl program's process with the new program; notably, they will not work for the practice in some long-running daemons of periodically redoing exec on themselves to reset their state or force operating-system cleanup. Nor will they serve <span class="code">exec</span>'s function of returning stale resources to the operating system.</p>
<p>If you want <span class="code">exec</span> for these behaviors, you can use an <span class="code">exec*</span> function via the <span class="code">NativeCall</span> interface. Consult your operating system manual pages for <span class="code">exec</span> (or other similarly-named calls such as <span class="code">execl</span>, <span class="code">execv</span>, <span class="code">execvp</span>, or <span class="code">execvpe</span>). (Beware: these calls are not generally portable between Unix-like operating system families.)</p>
<a name="t2.3.35"></a> <h2 id="_language_5to6-perlfunc.pod6-exists">exists</h2>
<ul><li><p>exists EXPR</p>
</li></ul> <p>In Perl 6, this is not a function, but an adverb:</p>
<pre class="code"> %hash{$key}:exists;
@array[$i]:exists;
</pre>
<a name="t2.3.36"></a> <h2 id="_language_5to6-perlfunc.pod6-exit">exit</h2>
<ul><li><p>exit EXPR</p>
</li></ul> <p>Appears to do the same thing as in Perl 5.</p>
<a name="t2.3.37"></a> <h2 id="_language_5to6-perlfunc.pod6-exp">exp</h2>
<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="t2.3.38"></a> <h2 id="_language_5to6-perlfunc.pod6-fc">fc</h2>
<ul><li><p>fc EXPR</p>
</li></ul> <p>Looks like it does the same thing as in Perl 5.</p>
<a name="t2.3.39"></a> <h2 id="_language_5to6-perlfunc.pod6-fcntl">fcntl</h2>
<ul><li><p>fcntl FILEHANDLE, FUNCTION, SCALAR</p>
</li></ul> <p>Appears not to be in Perl 6.</p>
<a name="t2.3.40"></a> <h2 id="_language_5to6-perlfunc.pod6-__FILE__">__FILE__</h2>
<ul><li><p>__FILE__</p>
</li></ul> <p>Replaced by <span class="code">$?FILE</span>.</p>
<a name="t2.3.41"></a> <h2 id="_language_5to6-perlfunc.pod6-fileno">fileno</h2>
<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="t2.3.42"></a> <h2 id="_language_5to6-perlfunc.pod6-flock">flock</h2>
<ul><li><p>flock FILEHANDLE, OPERATION</p>
</li></ul> <p>Currently unimplemented.</p>
<a name="t2.3.43"></a> <h2 id="_language_5to6-perlfunc.pod6-fork">fork</h2>
<ul><li><p>fork</p>
</li></ul> <p>There is no built-in `fork` function. While it's possible to call it using NativeCall, it's highly unlikely that the resulting process will be usable.</p>
<p>Perl 6 provides extensive support for, and internally uses, threads. However, `fork` only clones the thread that called `fork`, resulting in a process that will be missing its other threads, which will have been in unknown states and probably holding locks. Even if a Perl 6 program doesn't knowingly start any threads, the compiler may create some of its own in the process of precompilation, and the VMs that Perl 6 runs on also create their own internal worker threads for doing things like optimization and GC in the background. Thus, the presence of threads is pretty much assured, and there's no reasonable way to make `fork` reliably work in this case.</p>
<a name="t2.3.44"></a> <h2 id="_language_5to6-perlfunc.pod6-formats">formats</h2>
<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="t2.3.45"></a> <h2 id="_language_5to6-perlfunc.pod6-getc">getc</h2>
<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="t2.3.46"></a> <h2 id="_language_5to6-perlfunc.pod6-getlogin">getlogin</h2>
<ul><li><p>getlogin</p>
</li></ul> <p>S29 lists it, but it does not seem to be implemented yet.</p>
<a name="t2.3.47"></a> <h2 id="_language_5to6-perlfunc.pod6-getpeername">getpeername</h2>
<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="t2.3.48"></a> <h2 id="_language_5to6-perlfunc.pod6-getpgrp">getpgrp</h2>
<ul><li><p>getpgrp PID</p>
</li></ul> <p>Does not appear to be implemented.</p>
<a name="t2.3.49"></a> <h2 id="_language_5to6-perlfunc.pod6-getpriority">getpriority</h2>
<ul><li><p>getpriority WHICH, WHO</p>
</li></ul> <p>Does not appear to be implemented.</p>
<a name="t2.3.50"></a> <h2 id="_language_5to6-perlfunc.pod6-get_and_set_functions">get and set functions</h2>
<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="t2.3.51"></a> <h2 id="_language_5to6-perlfunc.pod6-getsock*">getsock*</h2>
<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="t2.3.52"></a> <h2 id="_language_5to6-perlfunc.pod6-glob">glob</h2>
<ul><li><p>glob EXPR</p>
</li></ul> <p>Used in an example in S32, but apparently unimplemented.</p>
<a name="t2.3.53"></a> <h2 id="_language_5to6-perlfunc.pod6-gmtime">gmtime</h2>
<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="t2.3.54"></a> <h2 id="_language_5to6-perlfunc.pod6-goto">goto</h2>
<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>goto is not yet implemented</p>
<a name="t2.3.55"></a> <h2 id="_language_5to6-perlfunc.pod6-grep">grep</h2>
<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 { $_ = &quot;bars&quot; }, @baz</span>. Can also be used as a method: <span class="code">@foo = @bar.grep(/^f/)</span></p>
<a name="t2.3.56"></a> <h2 id="_language_5to6-perlfunc.pod6-hex">hex</h2>
<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(&quot;aF&quot;)</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="t2.3.57"></a> <h2 id="_language_5to6-perlfunc.pod6-import">import</h2>
<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="#_language_5to6-nutshell.pod6-Importing_specific_functions_from_a_module">this section</a>.</p>
<a name="t2.3.58"></a> <h2 id="_language_5to6-perlfunc.pod6-index">index</h2>
<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">&quot;howdy!&quot;.index(&quot;how&quot;); # 0</span></p>
<a name="t2.3.59"></a> <h2 id="_language_5to6-perlfunc.pod6-int">int</h2>
<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="t2.3.60"></a> <h2 id="_language_5to6-perlfunc.pod6-ioctl">ioctl</h2>
<ul><li><p>ioctl FILEHANDLE, FUNCTION, SCALAR</p>
</li></ul> <p>Currently unimplemented in Perl 6.</p>
<a name="t2.3.61"></a> <h2 id="_language_5to6-perlfunc.pod6-join">join</h2>
<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(&quot;,&quot;)</span></p>
<a name="t2.3.62"></a> <h2 id="_language_5to6-perlfunc.pod6-keys">keys</h2>
<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="t2.3.63"></a> <h2 id="_language_5to6-perlfunc.pod6-kill">kill</h2>
<ul><li><p>kill SIGNAL, LIST</p>
</li></ul> <ul><li><p>kill SIGNAL</p>
</li></ul> <p>No pre-defined core alternative exists. A non-portable method can be to use <a href="#_language_nativecall.pod6">NativeCall</a>:</p>
<pre class="code">use NativeCall;
sub kill(int32, int32) is native {*};
kill $*PID, 9; # OUTPUT: «Killed␤»</pre>
<p>To kill processes that were started by creating a <a href="#_type_Proc::Async.pod6">Proc::Async</a>, use <a href="#_type_Proc::Async.pod6-method_kill"><span class="code">Proc::Async.kill</span> method</a>.</p>
<a name="t2.3.64"></a> <h2 id="_language_5to6-perlfunc.pod6-last">last</h2>
<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="t2.3.65"></a> <h2 id="_language_5to6-perlfunc.pod6-lc">lc</h2>
<ul><li><p>lc EXPR</p>
</li></ul> <p>Works as in Perl 5, and also as a method: <span class="code">&quot;UGH&quot;.lc</span></p>
<a name="t2.3.66"></a> <h2 id="_language_5to6-perlfunc.pod6-lcfirst">lcfirst</h2>
<ul><li><p>lcfirst EXPR</p>
</li></ul> <p>Does not exist in Perl 6.</p>
<a name="t2.3.67"></a> <h2 id="_language_5to6-perlfunc.pod6-length">length</h2>
<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="t2.3.68"></a> <h2 id="_language_5to6-perlfunc.pod6-__LINE__">__LINE__</h2>
<ul><li><p>__LINE__</p>
</li></ul> <p>Replaced by <span class="code">$?LINE</span>.</p>
<a name="t2.3.69"></a> <h2 id="_language_5to6-perlfunc.pod6-link">link</h2>
<ul><li><p>link OLDFILE, NEWFILE</p>
</li></ul> <p>See <a href="#_routine_link.pod6">link</a></p>
<a name="t2.3.70"></a> <h2 id="_language_5to6-perlfunc.pod6-listen">listen</h2>
<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="t2.3.71"></a> <h2 id="_language_5to6-perlfunc.pod6-local">local</h2>
<ul><li><p>local EXPR</p>
</li></ul> <p>The Perl 6 equivalent is <span class="code">temp</span>. Unlike <span class="code">local</span>, however, the value of the given variable is not immediately unset: it retains its original value until assigned to.</p>
<a name="t2.3.72"></a> <h2 id="_language_5to6-perlfunc.pod6-localtime">localtime</h2>
<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;
my $sec = $d.second; # Potentially includes fractional seconds
my $min = $d.minute;
my $hour = $d.hour;
my $mday = $d.day-of-month; # or $d.day; 1..31
my $mon = $d.month; # 1..12
my $year = $d.year;
my $wday = $d.day-of-week; # 1 =&gt; Monday, 2 =&gt; Tuesday, etc.
my $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 &quot;2015-06-29T12:49:31-04:00&quot;.</p>
<a name="t2.3.73"></a> <h2 id="_language_5to6-perlfunc.pod6-lock">lock</h2>
<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="t2.3.74"></a> <h2 id="_language_5to6-perlfunc.pod6-log">log</h2>
<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="t2.3.75"></a> <h2 id="_language_5to6-perlfunc.pod6-lstat">lstat</h2>
<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="t2.3.76"></a> <h2 id="_language_5to6-perlfunc.pod6-m//">m//</h2>
<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="#_language_regexes.pod6-Adverbs">Adverbs</a></p>
<a name="t2.3.77"></a> <h2 id="_language_5to6-perlfunc.pod6-map">map</h2>
<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="t2.3.78"></a> <h2 id="_language_5to6-perlfunc.pod6-mkdir">mkdir</h2>
<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="t2.3.79"></a> <h2 id="_language_5to6-perlfunc.pod6-msg*">msg*</h2>
<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="t2.3.80"></a> <h2 id="_language_5to6-perlfunc.pod6-my">my</h2>
<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="t2.3.81"></a> <h2 id="_language_5to6-perlfunc.pod6-next">next</h2>
<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="t2.3.82"></a> <h2 id="_language_5to6-perlfunc.pod6-no">no</h2>
<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 or versions.</p>
<a name="t2.3.83"></a> <h2 id="_language_5to6-perlfunc.pod6-oct">oct</h2>
<ul><li><p>oct</p>
</li></ul> <p>Replaced by the adverbial form <span class="code">:8</span>. E. g. <span class="code">:8(&quot;100&quot;)</span> returns 64.</p>
<p>If you want to deal with strings that start in <span class="code">0x</span>, <span class="code">0o</span>, or <span class="code">0b</span>, you can just use the <span class="code">prefix:&lt;+&gt;</span> operator.</p>
<a name="t2.3.84"></a> <h2 id="_language_5to6-perlfunc.pod6-open">open</h2>
<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(&quot;file&quot;, :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 <a href="#_routine_open.pod6">here</a>.</p>
<p>Another important change is that filehandles don't get automatically closed on scope exit. It's necessary to call <a href="#_routine_close.pod6">close</a> explicitly.</p>
<a name="t2.3.85"></a> <h2 id="_language_5to6-perlfunc.pod6-opendir">opendir</h2>
<ul><li><p>opendir DIRHANDLE, EXPR</p>
</li></ul> <p>No replacement. See <a href="#_routine_dir.pod6"><span class="code">&amp;dir</span> / <span class="code">IO::Path.dir</span></a> for alternatives.</p>
<a name="t2.3.86"></a> <h2 id="_language_5to6-perlfunc.pod6-ord">ord</h2>
<ul><li><p>ord EXPR</p>
</li></ul> <p>Same as in Perl 5. May be used as a method: <span class="code">&quot;howdy!&quot;.ord; # 104</span></p>
<a name="t2.3.87"></a> <h2 id="_language_5to6-perlfunc.pod6-our">our</h2>
<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="t2.3.88"></a> <h2 id="_language_5to6-perlfunc.pod6-pack">pack</h2>
<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="#_routine_unpack.pod6">unpack</a>.</p>
<a name="t2.3.89"></a> <h2 id="_language_5to6-perlfunc.pod6-package">package</h2>
<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="t2.3.90"></a> <h2 id="_language_5to6-perlfunc.pod6-__PACKAGE__">__PACKAGE__</h2>
<ul><li><p>__PACKAGE__</p>
</li></ul> <p>Replaced by <span class="code">$?PACKAGE</span>.</p>
<a name="t2.3.91"></a> <h2 id="_language_5to6-perlfunc.pod6-pipe">pipe</h2>
<ul><li><p>pipe READHANDLE, WRITEHANDLE</p>
</li></ul> <p>Depending on your needs, see <a href="#_type_Channel.pod6"><span class="code">Channel</span></a> to shuttle data between threads (and <a href="#_language_concurrency.pod6">Concurrency tutorial</a> for other options), or see <a href="#_type_Proc.pod6"><span class="code">Proc</span></a> type for piping to and from processes.</p>
<a name="t2.3.92"></a> <h2 id="_language_5to6-perlfunc.pod6-pop">pop</h2>
<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="t2.3.93"></a> <h2 id="_language_5to6-perlfunc.pod6-pos">pos</h2>
<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="#_language_regexes.pod6-Continue">Continue</a>.</p>
<a name="t2.3.94"></a> <h2 id="_language_5to6-perlfunc.pod6-print">print</h2>
<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, writing to standard out. To use <span class="code">print</span> as a function with a filehandle <i>instead</i> of standard out, you can use a method call: <span class="code">$fh.print(&quot;howdy!&quot;)</span></p>
<a name="t2.3.95"></a> <h2 id="_language_5to6-perlfunc.pod6-printf">printf</h2>
<ul><li><p>printf FORMAT, LIST</p>
</li></ul> <ul><li><p>printf</p>
</li></ul> <p>Perl 6 version is similar; see <a href="https://docs.perl6.org/type/Str#sub_sprintf">sprintf</a> for details on acceptable format directives. To print to a filehandle other than STDOUT, use the <a href="#_type_printf.pod6"><span class="code">.printf</span></a> method on that filehandle.</p>
<a name="t2.3.96"></a> <h2 id="_language_5to6-perlfunc.pod6-prototype">prototype</h2>
<ul><li><p>prototype FUNCTION</p>
</li></ul> <p>Not available in Perl 6. The closest equivalent is <span class="code">.signature</span>. E. g. <span class="code">say &amp;sprintf.signature</span> results in &quot;(Cool $format, *@args)&quot;.</p>
<a name="t2.3.97"></a> <h2 id="_language_5to6-perlfunc.pod6-push">push</h2>
<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(&quot;foo&quot;);</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.pod6-method_append">append method</a>.</p>
<a name="t2.3.98"></a> <h2 id="_language_5to6-perlfunc.pod6-quoting">quoting</h2>
<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"> q/.../; # is still equivalent to using single quotes.
qq/.../; # is still equivalent to using double quotes.
qw/.../; # is more commonly rendered as C&lt;&lt; &lt;...&gt; &gt;&gt; in Perl 6.
</pre>
<p>There are some added quoting constructs and equivalents, as explained at <a href="#_language_quoting.pod6">quoting</a>.</p>
<ul><li><p>qr/STRING/ <a id="i4" name="qr (Perl 5)"></a><span class="indexed"></span></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&gt; </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)">https://design.perl6.org/S05.html#Extensible_metasyntax_(%3C...%3E)</a></p>
<a name="t2.3.99"></a> <h2 id="_language_5to6-perlfunc.pod6-rand">rand</h2>
<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="#_language_operators.pod6-prefix_%5E">^ operator</a> and <a href="#_routine_pick.pod6">pick</a>.</p>
<a name="t2.3.100"></a> <h2 id="_language_5to6-perlfunc.pod6-read">read</h2>
<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="t2.3.101"></a> <h2 id="_language_5to6-perlfunc.pod6-readdir">readdir</h2>
<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="#_type_IO::Path.pod6-routine_dir">dir routine</a>.</p>
<a name="t2.3.102"></a> <h2 id="_language_5to6-perlfunc.pod6-readline">readline</h2>
<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="#_language_io.pod6">io</a>.</p>
<a name="t2.3.103"></a> <h2 id="_language_5to6-perlfunc.pod6-readlink">readlink</h2>
<ul><li><p>readlink EXPR</p>
</li></ul> <p>Appears to be gone from Perl 6.</p>
<a name="t2.3.104"></a> <h2 id="_language_5to6-perlfunc.pod6-readpipe">readpipe</h2>
<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="t2.3.105"></a> <h2 id="_language_5to6-perlfunc.pod6-recv">recv</h2>
<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="t2.3.106"></a> <h2 id="_language_5to6-perlfunc.pod6-redo">redo</h2>
<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="t2.3.107"></a> <h2 id="_language_5to6-perlfunc.pod6-ref">ref</h2>
<ul><li><p>ref EXPR</p>
</li></ul> <p>Gone. To quote S29, &quot;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>.&quot; Except that <span class="code">Perl5::p5ref</span> does not seem to currently exist...</p>
<a name="t2.3.108"></a> <h2 id="_language_5to6-perlfunc.pod6-rename">rename</h2>
<ul><li><p>rename OLDNAME, NEWNAME</p>
</li></ul> <p>Still available in Perl 6.</p>
<a name="t2.3.109"></a> <h2 id="_language_5to6-perlfunc.pod6-requires">requires</h2>
<ul><li><p>require VERSION</p>
</li></ul> <p>No equivalent.</p>
<a name="t2.3.110"></a> <h2 id="_language_5to6-perlfunc.pod6-reset">reset</h2>
<ul><li><p>reset EXPR</p>
</li></ul> <p>No equivalent.</p>
<a name="t2.3.111"></a> <h2 id="_language_5to6-perlfunc.pod6-return">return</h2>
<ul><li><p>return EXPR</p>
</li></ul> <p>Appears to be available in Perl 6, although not clearly documented.</p>
<a name="t2.3.112"></a> <h2 id="_language_5to6-perlfunc.pod6-reverse">reverse</h2>
<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="t2.3.113"></a> <h2 id="_language_5to6-perlfunc.pod6-rewinddir">rewinddir</h2>
<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="t2.3.114"></a> <h2 id="_language_5to6-perlfunc.pod6-rindex">rindex</h2>
<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 = &quot;babaganush&quot;;say $x.rindex(&quot;a&quot;);say $x.rindex(&quot;a&quot;, 3); # 5, 3</span></p>
<a name="t2.3.115"></a> <h2 id="_language_5to6-perlfunc.pod6-rmdir">rmdir</h2>
<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 &quot;Foo&quot;;</span> and <span class="code">&quot;Foo&quot;.IO.rmdir;</span> are equivalent.</p>
<a name="t2.3.116"></a> <h2 id="_language_5to6-perlfunc.pod6-s///">s///</h2>
<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="#_language_regexes.pod6-Adverbs">Adverbs page</a></p>
<a name="t2.3.117"></a> <h2 id="_language_5to6-perlfunc.pod6-say">say</h2>
<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: &quot;Howdy!&quot;</span>. The use of the colon as an &quot;invocant marker&quot; here is discussed at <a href="https://design.perl6.org/S03.html#line_4019">https://design.perl6.org/S03.html#line_4019</a>. Alternately, you can use a method call: <span class="code">$fh.say(&quot;howdy!&quot;)</span></p>
<a name="t2.3.118"></a> <h2 id="_language_5to6-perlfunc.pod6-scalar">scalar</h2>
<ul><li><p>scalar EXPR</p>
</li></ul> <p>Gone. Apparently &quot;very&quot; gone.</p>
<a name="t2.3.119"></a> <h2 id="_language_5to6-perlfunc.pod6-seek">seek</h2>
<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="t2.3.120"></a> <h2 id="_language_5to6-perlfunc.pod6-seekdir">seekdir</h2>
<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="t2.3.121"></a> <h2 id="_language_5to6-perlfunc.pod6-select">select</h2>
<ul><li><p>select FILEHANDLE</p>
</li></ul> <p>&quot;[S]elect as a global concept is dead.&quot; 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">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="t2.3.122"></a> <h2 id="_language_5to6-perlfunc.pod6-semctl">semctl</h2>
<ul><li><p>semctl ID, SEMNUM, CMD, ARG</p>
</li></ul> <p>No longer in core.</p>
<a name="t2.3.123"></a> <h2 id="_language_5to6-perlfunc.pod6-semget">semget</h2>
<ul><li><p>semget KEY, NSEMS, FLAGS</p>
</li></ul> <p>No longer in core.</p>
<a name="t2.3.124"></a> <h2 id="_language_5to6-perlfunc.pod6-semop">semop</h2>
<ul><li><p>semop KEY, OPSTRING</p>
</li></ul> <p>No longer in core.</p>
<a name="t2.3.125"></a> <h2 id="_language_5to6-perlfunc.pod6-send">send</h2>
<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="t2.3.126"></a> <h2 id="_language_5to6-perlfunc.pod6-setpgrp">setpgrp</h2>
<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="t2.3.127"></a> <h2 id="_language_5to6-perlfunc.pod6-setpriority">setpriority</h2>
<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="t2.3.128"></a> <h2 id="_language_5to6-perlfunc.pod6-setsockopt">setsockopt</h2>
<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="t2.3.129"></a> <h2 id="_language_5to6-perlfunc.pod6-shift">shift</h2>
<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="t2.3.130"></a> <h2 id="_language_5to6-perlfunc.pod6-shm*">shm*</h2>
<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="t2.3.131"></a> <h2 id="_language_5to6-perlfunc.pod6-shutdown">shutdown</h2>
<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="t2.3.132"></a> <h2 id="_language_5to6-perlfunc.pod6-sin">sin</h2>
<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="t2.3.133"></a> <h2 id="_language_5to6-perlfunc.pod6-sleep">sleep</h2>
<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="t2.3.134"></a> <h2 id="_language_5to6-perlfunc.pod6-sockets">sockets</h2>
<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="t2.3.135"></a> <h2 id="_language_5to6-perlfunc.pod6-sort">sort</h2>
<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">5to6-perlvar</a>) and sort routines no longer return positive integers, negative integers, or 0, but rather <span class="code">Order::Less</span>, <span class="code">Order::Same</span>, or <span class="code">Order::More</span> objects. See <a href="#_routine_sort.pod6">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="t2.3.136"></a> <h2 id="_language_5to6-perlfunc.pod6-splice">splice</h2>
<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&gt;); </span> is equivalent to <span class="code">@foo.splice(2, 3, &lt;M N O P&gt;); </span>.</p>
<a name="t2.3.137"></a> <h2 id="_language_5to6-perlfunc.pod6-split">split</h2>
<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(';', &quot;a;b;c&quot;, :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 <a href="#_routine_split.pod6">here</a>. Unsurprisingly, <span class="code">split</span> also now works as a method: <span class="code">&quot;a;b;c&quot;.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="t2.3.138"></a> <h2 id="_language_5to6-perlfunc.pod6-sprintf">sprintf</h2>
<ul><li><p>sprintf FORMAT, LIST</p>
</li></ul> <p>Works as in Perl 5. The formats currently available are:</p>
<table>
<tr><td>%</td> <td>a literal percent sign</td></tr>
<tr><td>c</td> <td>a character with the given codepoint</td></tr>
<tr><td>s</td> <td>a string</td></tr>
<tr><td>d</td> <td>a signed integer, in decimal</td></tr>
<tr><td>u</td> <td>an unsigned integer, in decimal</td></tr>
<tr><td>o</td> <td>an unsigned integer, in octal</td></tr>
<tr><td>x</td> <td>an unsigned integer, in hexadecimal</td></tr>
<tr><td>e</td> <td>a floating-point number, in scientific notation</td></tr>
<tr><td>f</td> <td>a floating-point number, in fixed decimal notation</td></tr>
<tr><td>g</td> <td>a floating-point number, in %e or %f notation</td></tr>
<tr><td>X</td> <td>like x, but using uppercase letters</td></tr>
<tr><td>E</td> <td>like e, but using an uppercase &quot;E&quot;</td></tr>
<tr><td>G</td> <td>like g, but with an uppercase &quot;E&quot; (if applicable)</td></tr>
</table> <p>Compatibility:</p>
<table>
<tr><td>i</td> <td>a synonym for %d</td></tr>
<tr><td>D</td> <td>a synonym for %ld</td></tr>
<tr><td>U</td> <td>a synonym for %lu</td></tr>
<tr><td>O</td> <td>a synonym for %lo</td></tr>
<tr><td>F</td> <td>a synonym for %f</td></tr>
</table> <p>Perl 5 (non-)compatibility:</p>
<table>
<tr><td>n</td> <td>produces a runtime exception</td></tr>
<tr><td>p</td> <td>produces a runtime exception</td></tr>
</table> <p>There are modifiers for integers, but they're mainly no-ops, as the semantics aren't settled:</p>
<table>
<tr><td>h</td> <td>interpret integer as native &quot;short&quot; (typically int16)</td></tr>
<tr><td>l</td> <td>interpret integer as native &quot;long&quot; (typically int32 or int64)</td></tr>
<tr><td>ll</td> <td>interpret integer as native &quot;long long&quot; (typically int64)</td></tr>
<tr><td>L</td> <td>interpret integer as native &quot;long long&quot; (typically uint64)</td></tr>
<tr><td>q</td> <td>interpret integer as native &quot;quads&quot; (typically int64 or larger)</td></tr>
</table> <a name="t2.3.139"></a> <h2 id="_language_5to6-perlfunc.pod6-sqrt">sqrt</h2>
<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="t2.3.140"></a> <h2 id="_language_5to6-perlfunc.pod6-srand">srand</h2>
<ul><li><p>srand EXPR</p>
</li></ul> <p>Available in Perl 6.</p>
<a name="t2.3.141"></a> <h2 id="_language_5to6-perlfunc.pod6-stat">stat</h2>
<ul><li><p>stat EXPR</p>
</li></ul> <ul><li><p>stat DIRHANDLE</p>
</li></ul> <ul><li><p>stat</p>
</li></ul> <p>Unlikely to be implemented as a built in function since it's POSIX specific, but available through the <span class="code">NativeCall</span> interface.</p>
<a name="t2.3.142"></a> <h2 id="_language_5to6-perlfunc.pod6-state">state</h2>
<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, see <a href="#_syntax_state.pod6">state</a>.</p>
<a name="t2.3.143"></a> <h2 id="_language_5to6-perlfunc.pod6-study">study</h2>
<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="t2.3.144"></a> <h2 id="_language_5to6-perlfunc.pod6-sub">sub</h2>
<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="#_language_functions.pod6">functions</a>.</p>
<a name="t2.3.145"></a> <h2 id="_language_5to6-perlfunc.pod6-__SUB__">__SUB__</h2>
<ul><li><p>__SUB__</p>
</li></ul> <p>Replaced by <span class="code">&amp;?ROUTINE</span>.</p>
<a name="t2.3.146"></a> <h2 id="_language_5to6-perlfunc.pod6-substr">substr</h2>
<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(&quot;hola!&quot;, 1, 3)</span> and <span class="code">&quot;hola!&quot;.substr(1, 3)</span> both return &quot;ola&quot;.</p>
<a name="t2.3.147"></a> <h2 id="_language_5to6-perlfunc.pod6-symlink">symlink</h2>
<ul><li><p>symlink OLDFILE, NEWFILE</p>
</li></ul> <p>See <a href="#_routine_symlink.pod6">symlink</a></p>
<a name="t2.3.148"></a> <h2 id="_language_5to6-perlfunc.pod6-syscall">syscall</h2>
<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="t2.3.149"></a> <h2 id="_language_5to6-perlfunc.pod6-sys*">sys*</h2>
<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="t2.3.150"></a> <h2 id="_language_5to6-perlfunc.pod6-system">system</h2>
<ul><li><p>system LIST</p>
</li></ul> <ul><li><p>system PROGRAM LIST</p>
</li></ul> <p>For this, you probably want (<a href="#_routine_run.pod6">run</a>) or (<a href="#_routine_shell.pod6">shell routine</a>).</p>
<a name="t2.3.151"></a> <h2 id="_language_5to6-perlfunc.pod6-syswrite">syswrite</h2>
<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="t2.3.152"></a> <h2 id="_language_5to6-perlfunc.pod6-tell">tell</h2>
<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="t2.3.153"></a> <h2 id="_language_5to6-perlfunc.pod6-telldir">telldir</h2>
<ul><li><p>telldir DIRHANDLE</p>
</li></ul> <p>Possibly in <span class="code">IO::Path</span>, but not yet documented.</p>
<a name="t2.3.154"></a> <h2 id="_language_5to6-perlfunc.pod6-tie">tie</h2>
<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="t2.3.155"></a> <h2 id="_language_5to6-perlfunc.pod6-time">time</h2>
<ul><li><p>time</p>
</li></ul> <p>&quot;Returns an Int representing the current time.&quot; 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="t2.3.156"></a> <h2 id="_language_5to6-perlfunc.pod6-times">times</h2>
<ul><li><p>times</p>
</li></ul> <p>Not available in Perl 6.</p>
<a name="t2.3.157"></a> <h2 id="_language_5to6-perlfunc.pod6-tr///">tr///</h2>
<ul><li><p>tr///</p>
</li></ul> <p>Works similarly to how it does in Perl 5. The one caveat is that ranges are specified differently. Instead of using a range &quot;a-z&quot;, you would use &quot;a..z&quot;, i.e. with Perl's range operator. In Perl 6, <span class="code">tr///</span> has a method version, called <a href="#_routine_trans.pod6">trans</a>, which offers a few additional features.</p>
<p>Perl 5's <span class="code">/r</span> flag is instead implemented as <span class="code">TR///</span> operator. The <span class="code">y///</span> equivalent does not exist.</p>
<a name="t2.3.158"></a> <h2 id="_language_5to6-perlfunc.pod6-truncate">truncate</h2>
<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="t2.3.159"></a> <h2 id="_language_5to6-perlfunc.pod6-uc">uc</h2>
<ul><li><p>uc EXPR</p>
</li></ul> <p>Works as a function and a method. <span class="code">uc(&quot;ha&quot;)</span> and <span class="code">&quot;ha&quot;.uc</span> both return &quot;HA&quot;.</p>
<a name="t2.3.160"></a> <h2 id="_language_5to6-perlfunc.pod6-ucfirst">ucfirst</h2>
<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 <a href="#_routine_tc.pod6"><span class="code">tc</span></a> probably does what you need.</p>
<a name="t2.3.161"></a> <h2 id="_language_5to6-perlfunc.pod6-undef">undef</h2>
<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&gt;;</span></p>
Add a note here about Type-based undefined values.
<a name="t2.3.162"></a> <h2 id="_language_5to6-perlfunc.pod6-unlink">unlink</h2>
<ul><li><p>unlink LIST</p>
</li></ul> <p>Still available. Usable as a method: <span class="code">&quot;filename&quot;.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="t2.3.163"></a> <h2 id="_language_5to6-perlfunc.pod6-unpack">unpack</h2>
<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 <a href="#_routine_unpack.pod6">here</a>.</p>
<a name="t2.3.164"></a> <h2 id="_language_5to6-perlfunc.pod6-unshift">unshift</h2>
<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, &quot;blah&quot;)</span> is equivalent to <span class="code">@a.unshift(&quot;blah&quot;)</span>.</p>
<a name="t2.3.165"></a> <h2 id="_language_5to6-perlfunc.pod6-untie">untie</h2>
<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="t2.3.166"></a> <h2 id="_language_5to6-perlfunc.pod6-use">use</h2>
<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>In Perl 5, this requires a minimum version of the perl executable in order to run. In Perl 6, this requires a version of the specification, (e.g. <span class="code">6.c</span>), which can be implemented by various perl6 executables.</p>
<a name="t2.3.167"></a> <h2 id="_language_5to6-perlfunc.pod6-utime">utime</h2>
<ul><li><p>utime LIST</p>
</li></ul> <p>No equivalent.</p>
<a name="t2.3.168"></a> <h2 id="_language_5to6-perlfunc.pod6-values">values</h2>
<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="t2.3.169"></a> <h2 id="_language_5to6-perlfunc.pod6-vec">vec</h2>
<ul><li><p>vec EXPR, OFFSET, BITS</p>
</li></ul> <p>S29 says &quot;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.&quot; It is unclear, however, that this has actually happened.</p>
<a name="t2.3.170"></a> <h2 id="_language_5to6-perlfunc.pod6-wait">wait</h2>
<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="t2.3.171"></a> <h2 id="_language_5to6-perlfunc.pod6-waitpid">waitpid</h2>
<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="t2.3.172"></a> <h2 id="_language_5to6-perlfunc.pod6-wantarray">wantarray</h2>
<ul><li><p>wantarray</p>
</li></ul> <p>There is no <span class="code">wantarray</span> in Perl 6, because <a href="#_language_faq.pod6-Why_is_wantarray_or_want_gone?_Can_I_return_different_things_in_different_contexts?">reasons</a>.</p>
<p>There are very easy ways to cover many of the use cases which wantarray filled.</p>
<p>First, since Perl 6 does not need special reference syntax to contain a <span class="code">List</span> or <span class="code">Array</span> in a <span class="code">Scalar</span>, simply returning a list may be all that is needed:</p>
<pre class="code">sub listofstuff {
return 1, 2, 3;
}
my $a = listofstuff();
print $a; # prints &quot;123&quot;
print join(&quot;&lt;&quot;, listofstuff()) # prints &quot;1&lt;2&lt;3&quot;</pre>
<p>One of the most common use cases is to provide either an array of lines or elements, or a prettier string than would be produced by simply printing the array. One can mix in a custom <span class="code">.Str</span> method for this purpose:</p>
<pre class="code">sub prettylist(*@origlist) {
@origlist but role {
method Str { self.join(&quot;&lt;&quot;) }
}
}
print prettylist(1, 2, 3); # prints &quot;1&lt;2&lt;3&quot;
print join(&quot;&gt;&quot;, prettylist(3, 2, 1)); # prints &quot;3&gt;2&gt;1&quot;</pre>
<p>In the above example, the returned list may be lazy, and the <span class="code">.Str</span> method is not called until stringification happens, so no extra work is done to generate something which is not asked for.</p>
<p>Another use case is to create methods which are mutators when called in void context but produce copies during assignment. It is generally considered better form in Perl 6 not to do so, since users can quite easily turn any copy-producing method into a mutator using the <span class="code">.=</span> operator:</p>
<pre class="code">my $a = &quot;foo\n&quot;;
$a.ords.say; # says &quot;(102 111 111 10)&quot;
$a .= chomp;
$a.ords.say; # says &quot;(102 111 111)&quot;</pre>
<p>However if you have your heart set on using the same function name for both operations, you can get most of the way there by mixing in a <span class="code">.sink</span> method, which will be called when the result finds itself in void context. There are some caveats however, so again, this is not advised:</p>
<pre class="code">multi sub increment($b is rw) {
($b + 1) does role { method sink { $b++ } }
}
multi sub increment($b) {
$b + 1
}
my $a = 1;
increment($a);
say $a; # says &quot;2&quot;
my $b = increment($a);
say $a, $b; # says &quot;2 3&quot;
# ...users will just have to be aware that they should not accidentally
# sink a stored value later, though this requires some effort to
# actually do:
sub identity($c is rw) { $c };
$a = 1;
$b = increment($a);
identity($b);
$a.say; # says &quot;2&quot;</pre>
<a name="t2.3.173"></a> <h2 id="_language_5to6-perlfunc.pod6-warn">warn</h2>
<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="#_language_exceptions.pod6">Exceptions</a>.</p>
<a name="t2.3.174"></a> <h2 id="_language_5to6-perlfunc.pod6-write">write</h2>
<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="t2.3.175"></a> <h2 id="_language_5to6-perlfunc.pod6-y///">y///</h2>
<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>
</div>
<!-- /language/5to6-perlop.pod6 --><div class="pod-body"><a id="_language_5to6-perlop.pod6"></a><a name="t3"></a><h1 class="title">3 5to6-perlop</h1> <p class="subtitle">Perl 5 to Perl 6 guide - operators</p> <a name="t3.1"></a> <h1 id="_language_5to6-perlop.pod6-DESCRIPTION">DESCRIPTION</h1>
<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="t3.2"></a> <h1 id="_language_5to6-perlop.pod6-NOTE">NOTE</h1>
<p>This document <i>does not</i> explain 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 <a href="#_language_operators.pod6">Perl 6 documentation</a>.</p>
<a name="t3.2.1"></a> <h2 id="_language_5to6-perlop.pod6-Operator_Precedence_and_Associativity">Operator Precedence and Associativity</h2>
<p>The operator precedence table is somewhat different in Perl 6 than it is in Perl 5, so it will not be detail here. If you need to know the precedence and associativity of a given operator in Perl 6, refer to <a href="#_language_operators.pod6-Operator_Precedence">Operator Precedence</a>.</p>
<a name="t3.2.2"></a> <h2 id="_language_5to6-perlop.pod6-Terms_and_List_Operators">Terms and List Operators</h2>
<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="#_language_5to6-perlfunc.pod6">5to6-perlfunc.pod6</a>. Parentheses are still used for grouping.</p>
<a name="t3.2.3"></a> <h2 id="_language_5to6-perlop.pod6-The_Arrow_Operator">The Arrow Operator</h2>
<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-&gt;[7] </span> becomes <span class="code">$arrayref.[7]</span> in Perl 6 and, similarly, <span class="code">$user-&gt;name </span> becomes <span class="code">$user.name</span>. The <span class="code">=&gt; </span> arrow is used for constructing Pairs, see <a href="#_language_terms.pod6-Pair">Pair term documentation</a>.</p>
<a name="t3.2.4"></a> <h2 id="_language_5to6-perlop.pod6-Auto-increment_and_Auto-decrement">Auto-increment and Auto-decrement</h2>
<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="t3.2.5"></a> <h2 id="_language_5to6-perlop.pod6-Exponentiation">Exponentiation</h2>
<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. &quot;-2**4&quot; evaluates as &quot;-(2**4)&quot; rather than &quot;(-2)**4)&quot;) is also true for Perl 6.</p>
<a name="t3.2.6"></a> <h2 id="_language_5to6-perlop.pod6-Symbolic_Unary_Operators">Symbolic Unary Operators</h2>
<p>As in Perl 5, unary <span class="code">!</span> and <span class="code">-</span> do logical and 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 the Numeric type.</p>
<p>Unary <span class="code">\</span> 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: <span class="code">$sref = &amp;foo</span> Anonymous arrays, hashes, and subs return their references during creation <i>right away</i>.</p>
<a name="t3.2.7"></a> <h2 id="_language_5to6-perlop.pod6-Binding_Operators">Binding Operators</h2>
<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="t3.2.8"></a> <h2 id="_language_5to6-perlop.pod6-Multiplicative_Operators">Multiplicative Operators</h2>
<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 &quot;1&quot;s, you would use <span class="code">@ones = 1 xx 80;</span>.</p>
<a name="t3.2.9"></a> <h2 id="_language_5to6-perlop.pod6-Additive_Operators">Additive Operators</h2>
<p>Binary <span class="code">+</span> and <span class="code">-</span> 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="t3.2.10"></a> <h2 id="_language_5to6-perlop.pod6-Shift_Operators">Shift Operators</h2>
<p><span class="code">&lt;&lt; </span> and <span class="code">&gt;&gt; </span> have been replaced by <span class="code">+&lt; </span> and <span class="code">+&gt; </span>.</p>
<a name="t3.2.11"></a> <h2 id="_language_5to6-perlop.pod6-Named_Unary_Operators">Named Unary Operators</h2>
<p>As noted above, you'll find these in <a href="#_language_5to6-perlfunc.pod6">5to6-perlfunc.pod6</a>.</p>
<a name="t3.2.12"></a> <h2 id="_language_5to6-perlop.pod6-Relational_Operators">Relational Operators</h2>
<p>These all work as in Perl 5.</p>
<a name="t3.2.13"></a> <h2 id="_language_5to6-perlop.pod6-Equality_Operators">Equality Operators</h2>
<p><span class="code">==</span> and <span class="code">!=</span> both work as in Perl 5.</p>
<p><span class="code">&lt;=&gt; </span> and <span class="code">cmp</span> have different behavior in Perl 6. <span class="code">&lt;=&gt; </span> does a numeric comparison, but returns <span class="code">Order::Less</span>, <span class="code">Order::Same</span>, or <span class="code">Order::More</span> 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;=&gt; </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">https://design.perl6.org/S03.html#Smart_matching</a>.</p>
<a name="t3.2.14"></a> <h2 id="_language_5to6-perlop.pod6-Smartmatch_Operator">Smartmatch Operator</h2>
<p>See the entry on <span class="code">~~</span> directly above.</p>
<a name="t3.2.15"></a> <h2 id="_language_5to6-perlop.pod6-Bitwise_And">Bitwise And</h2>
<p>Binary <span class="code">&amp;</span> is <span class="code">+&amp;</span> in Perl 6.</p>
<a name="t3.2.16"></a> <h2 id="_language_5to6-perlop.pod6-Bitwise_Or_and_Exclusive_Or">Bitwise Or and Exclusive Or</h2>
<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="t3.2.17"></a> <h2 id="_language_5to6-perlop.pod6-C-style_Logical_And">C-style Logical And</h2>
<p>Unchanged.</p>
<a name="t3.2.18"></a> <h2 id="_language_5to6-perlop.pod6-C-style_Logical_Or">C-style Logical Or</h2>
<p>Unchanged.</p>
<a name="t3.2.19"></a> <h2 id="_language_5to6-perlop.pod6-Logical_Defined-Or">Logical Defined-Or</h2>
<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="t3.2.20"></a> <h2 id="_language_5to6-perlop.pod6-Range_Operators">Range Operators</h2>
<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>
<ul><li><p>infix <span class="code">..^</span> which excludes the endpoint;</p>
</li></ul> <ul><li><p>infix ^.. which excludes the starting point;</p>
</li></ul> <ul><li><p>infix <span class="code">^..^</span> which excludes both the starting and ending points;</p>
</li></ul> <ul><li><p>prefix <span class="code">^</span> which starts from zero excluding the endpoint.</p>
</li></ul> <p>The following example shows the effects of all the above range operators (please note parentheses are used only to allow the method call):</p>
<pre class="code">(1..^5).list; # (1 2 3 4)
(1^..5).list; # (2 3 4 5)
(1^..^5).list; # (2 3 4)
(^5).list; # (0 1 2 3 4)
</pre>
<p>In Perl 5, in scalar context, the operators <span class="code">..</span> and <span class="code">...</span> work as flip-flop operators, even if they are little-known and probably less used. Those operators have been replaced in Perl 6 by <a href="#_routine_ff.pod6">ff</a> and <a href="#_routine_fff.pod6">fff</a> respectively.</p>
<a name="t3.2.21"></a> <h2 id="_language_5to6-perlop.pod6-Conditional_Operator">Conditional Operator</h2>
<p>The conditional operator <span class="code">? :</span> has been replaced by <span class="code">?? !!</span>:</p>
<pre class="code">$x = $ok ? $yes : $no; # Perl 5
</pre>
<pre class="code">$x = $ok ?? $yes !! $no; # Perl 6
</pre>
<a name="t3.2.22"></a> <h2 id="_language_5to6-perlop.pod6-Assignment_Operators">Assignment Operators</h2>
<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="t3.2.23"></a> <h2 id="_language_5to6-perlop.pod6-Comma_Operator">Comma Operator</h2>
<p>The comma operator works mostly as expected, but technically it creates <a href="#_type_List.pod6">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="#_language_operators.pod6-infix_%3A">this page</a>.</p>
<p>The <span class="code">=&gt; </span> operator works similarly to the Perl 5 &quot;fat comma&quot; 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="t3.2.24"></a> <h2 id="_language_5to6-perlop.pod6-List_Operators_(Rightward)">List Operators (Rightward)</h2>
<p>Like the Named Unary Operators, you'll find these discussed in <a href="#_language_5to6-perlfunc.pod6">5to6-perlfunc.pod</a>.</p>
<a name="t3.2.25"></a> <h2 id="_language_5to6-perlop.pod6-Logical_Not">Logical Not</h2>
<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="t3.2.26"></a> <h2 id="_language_5to6-perlop.pod6-Logical_And">Logical And</h2>
<p>Lower precedence version of <span class="code">&amp;&amp;</span> as in Perl 5.</p>
<a name="t3.2.27"></a> <h2 id="_language_5to6-perlop.pod6-Logical_or_and_Exclusive_Or">Logical or and Exclusive Or</h2>
<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="t3.2.28"></a> <h2 id="_language_5to6-perlop.pod6-Quote_and_Quote-like_Operators">Quote and Quote-like Operators</h2>
<p>For all the gory details on quoting constructs, see <a href="#_language_quoting.pod6">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 &quot;This is still a closing curly brace → \&quot;.</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 &quot;This is not a closing curly brace → }, but this is →&quot;. 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&gt;;say qq/@a[] example@example.com/; </span> results in &quot;1 2 3 example@example.com&quot;. Hashes interpolate in a possibly unexpected manner: <span class="code">%a = 1 =&gt; 2, 3 =&gt; 4;say &quot;%a[]&quot;; </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="#_language_quoting.pod6-Interpolation%3A_qq">Interpolation</a>.</p>
<p><span class="code">qw</span> works as in Perl 5, and can also be rendered as <span class="code">&lt;...&gt; </span>. E. g. <span class="code">qw/a b c/</span> is equivalent to <span class="code">&lt;a b c&gt; </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 &quot;42 b c&quot;.</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> works similarly to how it does in Perl 5. The one caveat is that ranges are specified differently. Instead of using a range &quot;a-z&quot;, you would use &quot;a..z&quot;, 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'] =&gt; ['A'..'C'], ['d'..'q'] =&gt; ['D'..'Q'], ['r'..'z'] =&gt; ['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">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 &quot;END&quot;. 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="t3.2.29"></a> <h2 id="_language_5to6-perlop.pod6-I/O_Operators">I/O Operators</h2>
<p>The full details on Input/Output in Perl 6 can be found at <a href="#_language_io.pod6">io</a>.</p>
<p>As <span class="code">&lt;...&gt; </span> is the quote-words construct in Perl 6, <span class="code">&lt;&gt; </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 = &quot;filename&quot;.IO.lines;</span> or <span class="code">my $fh = open &quot;filename&quot;, :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 -&gt; $line {
# Do something with $line
}
</pre>
<p>Note the use of <span class="code">-&gt; </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</p>
<pre class="code">my $x = &quot;filename&quot;.IO.slurp;
# ... or ...
my $fh = open &quot;filename&quot;, :r;
my $x = $fh.slurp;
</pre>
<p>As noted in <a href="#_language_5to6-perlvar.pod6">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="t3.2.30"></a> <h2 id="_language_5to6-perlop.pod6-No-ops">No-ops</h2>
<p>Although it's not specifically documented, <span class="code">1 while foo();</span> appears to work in this sense.</p>
<a name="t3.2.31"></a> <h2 id="_language_5to6-perlop.pod6-Bitwise_String_Operators">Bitwise String Operators</h2>
<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 <span class="code">?|</span>.</p>
<p>Left shift and right shift are <span class="code">+&lt; </span> and <span class="code">+&gt; </span>.</p>
</div>
<!-- /language/5to6-perlsyn.pod6 --><div class="pod-body"><a id="_language_5to6-perlsyn.pod6"></a><a name="t4"></a><h1 class="title">4 5to6-perlsyn</h1> <p class="subtitle">Perl 5 to Perl 6 guide - syntax</p> <p>perlsyn - Perl syntax</p>
<a name="t4.1"></a> <h1 id="_language_5to6-perlsyn.pod6-DESCRIPTION">DESCRIPTION</h1>
<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="t4.2"></a> <h1 id="_language_5to6-perlsyn.pod6-NOTE">NOTE</h1>
<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="t4.3"></a> <h1 id="_language_5to6-perlsyn.pod6-Free_Form">Free Form</h1>
<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)</span> or <span class="code">my($x, $y)</span>). In Perl 6, that space is required, thus <span class="code">while ($x &lt; 5)</span> or <span class="code">my ($x, $y)</span>. In Perl 6, however, you can omit the parentheses altogether: <span class="code">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 &quot;unspace&quot; whitespace, so you can use whitespace where it would otherwise be forbidden.</p>
<p>See <a href="#_language_5to6-nutshell.pod6-Whitespace">Whitespace</a> for details.</p>
<a name="t4.3.1"></a> <h2 id="_language_5to6-perlsyn.pod6-Declarations">Declarations</h2>
<p>As noted in <a href="#_language_5to6-perlfunc.pod6">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 &quot;(Any)&quot;. <span class="code">my Int $y;say $y;</span> will give you &quot;(Int)&quot;.</p>
<a name="t4.3.2"></a> <h2 id="_language_5to6-perlsyn.pod6-Comments">Comments</h2>
<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 &quot;something stupid&quot;;
}
</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="t4.3.3"></a> <h2 id="_language_5to6-perlsyn.pod6-Truth_and_Falsehood">Truth and Falsehood</h2>
<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">&quot;0&quot;</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">&quot;0&quot;</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="t4.3.4"></a> <h2 id="_language_5to6-perlsyn.pod6-Statement_Modifiers">Statement Modifiers</h2>
<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="t4.3.5"></a> <h2 id="_language_5to6-perlsyn.pod6-Compound_Statements">Compound Statements</h2>
<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="#_language_control.pod6-given">this page</a>.</p>
<a name="t4.3.6"></a> <h2 id="_language_5to6-perlsyn.pod6-Loop_Control">Loop Control</h2>
<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 .= ':'
}
</pre>
<pre class="code"># Perl 6
my $str = '';
for 1..5 {
next if $_ % 2 == 1;
$str ~= $_;
NEXT {
$str ~= ':'
}
}
</pre>
<a name="t4.3.7"></a> <h2 id="_language_5to6-perlsyn.pod6-For_Loops">For Loops</h2>
<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="t4.3.8"></a> <h2 id="_language_5to6-perlsyn.pod6-Foreach_Loops">Foreach Loops</h2>
<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="t4.3.9"></a> <h2 id="_language_5to6-perlsyn.pod6-Switch_Statements">Switch Statements</h2>
<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 <a href="#_language_control.pod6-given">here</a>.</p>
<a name="t4.3.10"></a> <h2 id="_language_5to6-perlsyn.pod6-Goto">Goto</h2>
<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="https://design.perl6.org/S04.html#The_goto_statement">https://design.perl6.org/S04.html#The_goto_statement</a>.</p>
<a name="t4.3.11"></a> <h2 id="_language_5to6-perlsyn.pod6-The_Ellipsis_Statement">The Ellipsis Statement</h2>
<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="https://design.perl6.org/S06.html#Stub_declarations">https://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="t4.3.12"></a> <h2 id="_language_5to6-perlsyn.pod6-PODs:_Embedded_Documentation">PODs: Embedded Documentation</h2>
<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 (&quot;|&quot;) is significant in <span class="code">X&lt;&gt; </span> codes, and it's not clear how to get a literal &quot;|&quot; 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="https://design.perl6.org/S26.html">https://design.perl6.org/S26.html</a>.</p>
</div>
<!-- /language/5to6-perlvar.pod6 --><div class="pod-body"><a id="_language_5to6-perlvar.pod6"></a><a name="t5"></a><h1 class="title">5 5to6-perlvar</h1> <p class="subtitle">Perl 5 to Perl 6 guide - special variables</p> <a name="t5.1"></a> <h1 id="_language_5to6-perlvar.pod6-DESCRIPTION">DESCRIPTION</h1>
<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="t5.2"></a> <h1 id="_language_5to6-perlvar.pod6-NOTE">NOTE</h1>
<p>This document is an attempt to guide the reader from the <i>Special Variables</i> in Perl 5 to their equivalents in Perl 6. For full documentation on the Perl 6 <i>Special Variables</i>, please see the Perl 6 documentation for each of them.</p>
<a name="t5.3"></a> <h1 id="_language_5to6-perlvar.pod6-SPECIAL_VARIABLES">SPECIAL VARIABLES</h1>
<p><a id="i5" name="Special Variables (Perl 5)"></a><span class="indexed"></span></p>
<a name="t5.3.1"></a> <h2 id="_language_5to6-perlvar.pod6-General_Variables">General Variables</h2>
<ul><li><p>$ARG</p>
</li></ul> <ul><li><p>$_ <a id="i6" name="$_ (Perl 5)"></a><span class="indexed"></span></p>
</li></ul> <p>Thankfully, <span class="code">$_</span> is the general default variable as in Perl 5. The main difference in Perl 6 is 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>@_ <a id="i7" name="@_ (Perl 5)"></a><span class="indexed"></span></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>$&quot;</p>
</li></ul> <p>Currently, there is no equivalent of the List Separator variable in Perl 6. Design document <a href="https://design.perl6.org/S28.html">S28</a> 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>$$ <a id="i8" name="$$ (Perl 5)"></a><span class="indexed"></span></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 <a id="i9" name="$0 (Perl 5)"></a><span class="indexed"></span></p>
</li></ul> <p>You can access the program name in Perl 6 via <span class="code">$*PROGRAM-NAME</span>.</p>
<p>Note: <span class="code">$0</span> in Perl 6 is the variable holding the first captured value from a regexp match (i. e. capture variables now start from <span class="code">$0</span> rather than <span class="code">$1</span>).</p>
<ul><li><p>$REAL_GROUP_ID</p>
</li></ul> <ul><li><p>$GID</p>
</li></ul> <ul><li><p>$(</p>
</li></ul> <p>In Perl 6 the group information is handled by <span class="code">$*GROUP</span>, which holds an object of type <a href="#_type_IntStr.pod6">IntStr</a> and therefore can be used either within a string or a numeric context. The group id is therefore obtained via <span class="code">$*GROUP.Numeric</span>, while the group name via <span class="code">$*GROUP.Str</span>.</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>In Perl 6 the user information is handled by <span class="code">$*USER</span>, which holds an object of type <a href="#_type_IntStr.pod6">IntStr</a> and therefore can be used either within a string or a numeric context (this is similar to how the group information is handled by the <span class="code">$*GROUP</span> object). The user id is therefore obtained via <span class="code">$*USER.Numeric</span>, while the username via <span class="code">$*USER.Str</span>.</p>
<ul><li><p>$EFFECTIVE_USER_ID</p>
</li></ul> <ul><li><p>$EUID</p>
</li></ul> <ul><li><p>$&gt;</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;
# OUTPUT: «(1 2 3 4 5 6)␤»
sort { $^g cmp $^a }, 1, 5, 6, 4, 2, 3;
# OUTPUT: «(6 5 4 3 2 1)␤»
for 1..9 { say $^c, $^a, $^b; last }
# OUTPUT: «312␤»
</pre>
<p>For more on placeholder variables, see <a href="#_language_variables.pod6-The_^_Twigil">this page</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. For example, <span class="code">OLDPWD</span> 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 running version of Perl 6 is kept by <span class="code">$*PERL</span> special variable, that is an object. The running version is retrieved via <span class="code">$*PERL.version</span>, which returns something like <span class="code">v6.c</span>; the full stringified version of the Perl interpreter is obtained via <span class="code">$*PERL.Str</span>, which returns something like <span class="code">Perl 6 (6.c)</span>.</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 <span class="code">-F</span> command-line switches are not yet implemented in rakudo.</p>
<ul><li><p>@INC <a id="i10" name="@INC (Perl 5)"></a><span class="indexed"></span></p>
</li></ul> <p>No longer exists in Perl 6. Please use &quot;use lib&quot; to manipulate the module repositories to be searched. The closest thing to @INC is really $*REPO. But that works completely differently from @INC mostly because of the precompilation capabilities of Perl 6.</p>
<pre class="code"># Print out a list of compunit repositories
.say for $*REPO.repo-chain;</pre>
<ul><li><p>%INC <a id="i11" name="%INC (Perl 5)"></a><span class="indexed"></span></p>
</li></ul> <p>No longer exists in Perl 6. Because each Repository is responsible for remembering which modules have been loaded already. You can get a list of all loaded modules (compilation units) like so:</p>
<pre class="code">use Test;
use MyModule;
say flat $*REPO.repo-chain.map(*.loaded); #-&gt; (MyModule Test)
</pre>
<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 exist.</p>
<ul><li><p>$^M</p>
</li></ul> <p>S28 suggests $*EMERGENCY_MEMORY, but it does not yet 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 &quot;the name of the operating system&quot; as design document <a href="https://design.perl6.org/S28.html">S28</a> has three different suggestions, all of which give different answers.</p>
<p>There are currently three main objects containing information about the &quot;running environment&quot;:</p>
<ul><li><p><span class="code">$*KERNEL</span> provides information about the running Operating System kernel;</p>
</li></ul> <ul><li><p><span class="code">$*DISTRO</span> provides information about the Operating System distribution;</p>
</li></ul> <ul><li><p><span class="code">$*VM</span> provides information about the running backend machine for Perl 6.</p>
</li></ul> <p>All the above objects have methods in common:</p>
<ul><li><p><span class="code">version</span> provides the version number for that component;</p>
</li></ul> <ul><li><p><span class="code">name</span> provides the mnemonic name for that component;</p>
</li></ul> <ul><li><p><span class="code">auth</span> provides the known author(s) for that component.</p>
</li></ul> <p>As a short example, the following piece of code prints information about all the above components:</p>
<pre class="code">for $*KERNEL, $*DISTRO, $*VM -&gt; $what {
say $what.^name;
say 'version ' ~ $what.version
~ ' named ' ~ $what.name
~ ' by ' ~ $what.auth;
}
# Kernel
# version 4.10.0.42.generic named linux by unknown
# Distro
# version 17.04.Zesty.Zapus named ubuntu by https://www.ubuntu.com/
# VM
# version 2017.11 named moar by The MoarVM Team
</pre>
<p>The <span class="code">Str</span> method on all of the above produces the <i>short</i> version of the information, at the current time the <span class="code">name</span>.</p>
<p>All the objects have other methods that can be useful when trying to identify the exact running instance, for more information use &lt;.^methods&gt; to introspect all the above.</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">$*INIT-INSTANT</span>. Unlike in Perl 5, this is not in seconds since epoch, but an <a href="#_type_Instant.pod6">Instant</a> 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 is no 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>. Note that there is also <span class="code">$*EXECUTABLE</span>, which is an <span class="code">IO</span> object in Perl 6.</p>
<a name="t5.3.2"></a> <h2 id="_language_5to6-perlvar.pod6-Variables_related_to_regular_expressions">Variables related to regular expressions</h2>
<a name="t5.3.2.1"></a> <h3 id="_language_5to6-perlvar.pod6-Performance_issues">Performance issues</h3>
<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>&gt; ($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 <a href="#_type_Match.pod6">match</a> object, so the Perl 5 behavior of <span class="code">$&amp;</span> can be obtained by stringifying it, i. e. <span class="code">~$/</span>.</p>
<p>Please note that while <span class="code">$/.Str</span> should also work, <span class="code">~$/</span> is currently the more common idiom.</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="#_routine_%5b%20%5d.pod6-language_documentation_operators">[ ] routine</a></p>
</li></ul> <ul><li><p><a href="#_type_Whatever.pod6">Whatever</a></p>
</li></ul> <p>...and possibly</p>
<ul><li><p><a href="https://design.perl6.org/S02.html#line_1126">https://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>No equivalent.</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="t5.3.3"></a> <h2 id="_language_5to6-perlvar.pod6-Variables_related_to_filehandles">Variables related to filehandles</h2>
<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>No direct replacement exists.</p>
<p>When iterating using <a href="#_routine_lines.pod6">lines</a> method from <a href="#_type_IO::Path.pod6">IO::Path</a> or <a href="#_type_IO::Handle.pod6">IO::Handle</a> types, you can <a href="#_language_operators.pod6-index-entry-Z_%28zip_meta_operator%29">zip</a> with a <a href="#_type_Range.pod6">Range</a>:</p>
<pre class="code">for 1..* Z &quot;foo&quot;.IO.lines -&gt; ($ln, $text) {
say &quot;$ln: $text&quot;
}
# OUTPUT:
# 1: a
# 2: b
# 3: c
# 4: d
</pre>
<p>For <a href="#_type_IO::CatHandle.pod6">IO::CatHandle</a> types (of which <a href="#_language_variables.pod6-index-entry-%24%2AARGFILES"><span class="code">$*ARGFILES</span></a> is one), you can use <a href="#_type_IO::CatHandle.pod6-method_on-switch"><span class="code">on-switch</span></a> hook to reset line number on handle switch, and increment it manually. See also <a href="https://modules.perl6.org/repo/IO::CatHandle::AutoLines"><span class="code">IO::CatHandle::AutoLines</span></a> and <a href="https://modules.perl6.org/repo/LN"><span class="code">LN</span></a> modules that simplify this operation.</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>No global alternative available. TTY handles are unbuffered by default, for others, set <a href="#_routine_out-buffer.pod6">out-buffer</a> to zero or use <span class="code">:!out-buffer</span> with <a href="#_routine_open.pod6">open</a> on a specific <a href="#_type_IO::Handle.pod6">IO::Handle</a>.</p>
<ul><li><p>${^LAST_FH}</p>
</li></ul> <p>Not implemented in Perl 6.</p>
<a name="t5.3.3.1"></a> <h3 id="_language_5to6-perlvar.pod6-Variables_related_to_formats">Variables related to formats</h3>
<p>There are no built-in formats in Perl 6.</p>
<a name="t5.3.4"></a> <h2 id="_language_5to6-perlvar.pod6-Error_Variables">Error Variables</h2>
<p>Because of how error variables have changed in Perl 6, they will not be detailed here individually.</p>
<p>To quote the Perl 6 <a href="#_routine_syntax_$!.pod6">docs</a>, &quot;$! is the error variable.&quot; That's it. All the error variables appear to have been eaten by $!. As with the rest of Perl 6, it's an object that will return various things depending on the type of error or <a href="#_type_Exception.pod6">exception</a>.</p>
<p>In particular, when dealing with <a href="#_type_Exception.pod6">exceptions</a> the <span class="code">$!</span> provides information about the thrown exception, assuming the program has not halted:</p>
<pre class="code">try {
fail &quot;Boooh&quot;;
CATCH {
# within the catch block
# the exception is placed into $_
say 'within the catch:';
say $_.^name ~ ' : ' ~ $_.message;
$_.resume; # do not abort
}
}
# outside the catch block the exception is placed
# into $!
say 'outside the catch:';
say $!.^name ~ ' : ' ~ $!.message;
</pre>
<p>and the above code produces the following output</p>
<pre class="code">within the catch:
X::AdHoc : Boooh
outside the catch:
X::AdHoc : Boooh
</pre>
<p>therefore, as stated before, the <span class="code">$!</span> variable holds the exception object.</p>
<a name="t5.3.5"></a> <h2 id="_language_5to6-perlvar.pod6-Variables_related_to_the_interpreter_state">Variables related to the interpreter state</h2>
<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 &quot;pending&quot;. 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="t5.3.6"></a> <h2 id="_language_5to6-perlvar.pod6-Deprecated_and_removed_variables">Deprecated and removed variables</h2>
<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>
</div>
<!-- /language/about.pod6 --><div class="pod-body"><a id="_language_about.pod6"></a><a name="t6"></a><h1 class="title">6 About the Docs</h1> <p class="subtitle">Meta-documentation</p> <p>This document collection represents the on-going effort 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://docs.perl6.org">https://docs.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>
<p>This particular document is a quick overview of the process described in more detail in <a href="https://github.com/perl6/doc/blob/master/CONTRIBUTING.md">CONTRIBUTING on GitHub</a>. This document also provides a short introduction to writing Perl 6 Pod files, which can be rendered into HTML and other formats.</p>
<a name="t6.1"></a> <h1 id="_language_about.pod6-Structure">Structure</h1>
<p>All of the documentation is written in Perl 6 Pod and kept in the <span class="code">doc/</span> directory, and the <span class="code">doc/Language/</span> and <span class="code">doc/Type/</span> sub-directories. These files are processed as collections of definitions or &quot;documentables&quot;, which are then post-processed and linked together.</p>
<a name="t6.2"></a> <h1 id="_language_about.pod6-Generating_HTML_from_Pod">Generating HTML from Pod</h1>
<p>To generate HTML from the Pod files, you'll need:</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, Pod::To::BigPage, and URI::Escape (can be installed via <a href="https://github.com/ugexe/zef">zef</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="https://github.com/atom/highlights">Atom Highlights</a> and <a href="https://atom.io/packages/language-perl6">language-perl6</a>, for syntax highlighting</p>
</li></ul> <p>To generate the documentation into the <span class="code">html/</span> folder, run:</p>
<pre class="code">perl6 htmlify.p6
</pre>
<p>To host the documentation from a web server, have Perl 5 and Mojolicious::Lite installed, then run:</p>
<pre class="code">perl app.pl daemon
</pre>
<a name="t6.3"></a> <h1 id="_language_about.pod6-Contributing">Contributing</h1>
<p>The documentation is written in Perl 6 Pod.</p>
<p>For a quick introduction to Perl 6 Pod, see <a href="https://docs.perl6.org/language/pod">Perl 6 Pod</a>.</p>
<p>For full details about the Perl 6 Pod specification, see <a href="https://design.perl6.org/S26.html">Synopsis 26, Documentation</a>.</p>
<a name="t6.3.1"></a> <h2 id="_language_about.pod6-Adding_definitions">Adding definitions</h2>
<p>Documentables can be defined using an <span class="code">=headN</span> Pod directive, where <span class="code">N</span> is greater than zero (e.g., <span class="code">=head1</span>, <span class="code">=head2</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 <var class="replaceable">My Definition</var>
Some paragraphs, followed by some code:
my Code $examples = &quot;amazing&quot;;
Mind === blown.
=head3 Minor details about <var class="replaceable">My Definition</var>
It's fantastic.
=head2 And now, for something completely different
</pre>
<p>The documentable <var class="replaceable">My Definition</var> 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 named, say, Z. First the code in the document source:</p>
<pre class="code">=item X&lt;C&lt;How to use the Z infix&gt; | infix,Z&gt; (This a special case, which
is always considered a definition)
=item C&lt;The Z Infix&gt;
=item B&lt;The C&lt;Z&gt; Infix&gt;
=item C&lt;Infix Z&gt;
=item B&lt;Infix C&lt;Z&gt;&gt;
=item C&lt;trait is cached&gt; (A special case for the L&lt;trait|/language/functions#Traits&gt; documentables)
</pre>
<p>Then the results on the rendered page:</p>
<ul><li><p><a id="i12" name="infix Z"></a><span class="indexed"><span class="code">How to use the Z infix</span></span> (This is a special case, which is always considered a definition)</p>
</li></ul> <ul><li><p><span class="code">The Z Infix</span></p>
</li></ul> <ul><li><p><b>The <span class="code">Z</span> Infix</b></p>
</li></ul> <ul><li><p><span class="code">Infix Z</span></p>
</li></ul> <ul><li><p><b>Infix <span class="code">Z</span></b></p>
</li></ul> <ul><li><p><span class="code">trait is cached</span> (A special case for the <a href="#_language_functions.pod6-Traits">trait</a> documentables)</p>
</li></ul> <p>These items should now be searchable by using the search field in the HTML docs.</p>
<p>You can add emphasis with bold (<b> B&lt;&gt; </b>) or italicized (<b> I&lt;&gt; </b>), with or without code formatting (<b> C&lt;&gt; </b>). Due to current parser limitations, special steps have to be taken to use <b> X&lt;&gt; </b> with other formatting codes; for example:</p>
<pre class="code">=item X&lt;B&lt;foo&gt;|foo&gt; a fancy subroutine
</pre>
<p>renders like this</p>
<ul><li><p><a id="i13" name="foo"></a><span class="indexed"><b>foo</b></span> a fancy subroutine</p>
</li></ul> <p>Notice that text after a pipe ('|') has no formatting. Also note that <b> C&lt;&gt; </b> preserves spaces and treats text as verbatim.</p>
</div>
<!-- /language/classtut.pod6 --><div class="pod-body"><a id="_language_classtut.pod6"></a><a name="t7"></a><h1 class="title">7 Classes and Objects</h1> <p class="subtitle">A tutorial for creating and using classes in Perl 6</p> <p><a id="i14" name="OOP"></a><span class="indexed"></span></p>
More descriptive title?
<p>Perl 6 has a rich built-in syntax for defining and using classes.</p>
<p>A default constructor allows the setting of attributes for the created object:</p>
<pre class="code">class Point {
has Int $.x;
has Int $.y;
}
class Rectangle {
has Point $.lower;
has Point $.upper;
method area() returns Int {
($!upper.x - $!lower.x) * ( $!upper.y - $!lower.y);
}
}
# Create a new Rectangle from two Points
my $r = Rectangle.new(lower =&gt; Point.new(x =&gt; 0, y =&gt; 0), upper =&gt; Point.new(x =&gt; 10, y =&gt; 10));
say $r.area(); # OUTPUT: «100␤»
</pre>
<p>You can also provide your own construction and build implementation. The following, more elaborate example shows how a dependency handler might look in Perl 6. It showcases custom constructors, private and public attributes, methods and various aspects of signatures. It's not very much code, and yet the result is interesting and 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="t7.1"></a> <h1 id="_language_classtut.pod6-Starting_with_class">Starting with class</h1>
<p><a id="i15" name="class"></a><span class="indexed"></span> <a id="i16" name="classes"></a><span class="indexed"></span></p>
<p><a id="i17" name="state"></a><span class="indexed"></span> <a id="i18" name="has"></a><span class="indexed"></span> <a id="i19" name="classes has"></a><span class="indexed"></span> <a id="i20" name="behavior"></a><span class="indexed"></span> <a id="i21" name="classes behavior"></a><span class="indexed"></span></p>
<p>Perl 6, like many other languages, uses the <span class="code">class</span> keyword to define a 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><a id="i22" name="type object"></a><span class="indexed"></span> <a id="i23" name="DEFINITE"></a><span class="indexed"></span> <a id="i24" name=".DEFINITE"></a><span class="indexed"></span></p>
<p>Declaring a class creates a new <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 &quot;empty instance&quot; of the class. 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>You can use <span class="code">.DEFINITE</span> method to find out if what you have is an instance or a type object:</p>
<pre class="code">say Int.DEFINITE; # OUTPUT: «False␤» (type object)
say 426.DEFINITE; # OUTPUT: «True␤» (instance)
class Foo {};
say Foo.DEFINITE; # OUTPUT: «False␤» (type object)
say Foo.new.DEFINITE; # OUTPUT: «True␤» (instance)</pre>
<p>You can also use type smileys to only accept instances or type objects:</p>
<pre class="code">multi foo (Int:U) { &quot;It's a type object!&quot; }
multi foo (Int:D) { &quot;It's an instance!&quot; }
say foo Int; # OUTPUT: «It's a type object!␤»
say foo 42; # OUTPUT: «It's an instance!␤»</pre>
<a name="t7.2"></a> <h1 id="_language_classtut.pod6-State">State</h1>
<p><a id="i25" name="attributes"></a><span class="indexed"></span> <a id="i26" name="classes attributes"></a><span class="indexed"></span></p>
<p><a id="i27" name="encapsulation"></a><span class="indexed"></span> <a id="i28" name="classes encapsulation"></a><span class="indexed"></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). 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><a id="i29" name="sigils &amp;"></a><span class="indexed"></span> <a id="i30" name="twigils"></a><span class="indexed"></span> <a id="i31" name="twigils !"></a><span class="indexed"></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><a id="i32" name="twigils ."></a><span class="indexed"></span> <a id="i33" name="twigils accessors"></a><span class="indexed"></span> <a id="i34" name="accessor methods"></a><span class="indexed"></span> <a id="i35" name="classes accessors"></a><span class="indexed"></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 attribute 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><a id="i36" name="traits is rw"></a><span class="indexed"></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="t7.3"></a> <h1 id="_language_classtut.pod6-Static_fields?">Static fields?</h1>
<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="#_syntax_my.pod6">my</a> or <a href="#_syntax_our.pod6">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="#_syntax_use.pod6">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="t7.4"></a> <h1 id="_language_classtut.pod6-Methods">Methods</h1>
<p><a id="i37" name="methods"></a><span class="indexed"></span> <a id="i38" name="classes methods"></a><span class="indexed"></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><a id="i39" name="invocant"></a><span class="indexed"></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 <span class="code">perform</span> 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><a id="i40" name="operators ."></a><span class="indexed"></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="t7.4.1"></a> <h2 id="_language_classtut.pod6-Private_Methods">Private Methods</h2>
<p>Just like attributes, methods can also be private. Private methods are declared with a prefixed exclamation mark. They are called with <span class="code">self!</span> followed by the method's name. To call a private method of another class the calling class has to be trusted by the called class. A trust relationship is declared with <span class="code">trusts</span> and the class to be trusted must already be declared. Calling a private method of another class requires an instance of that class and the fully qualified name of the method. Trust also allows access to private attributes.</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="t7.5"></a> <h1 id="_language_classtut.pod6-Constructors">Constructors</h1>
<p><a id="i41" name="constructors"></a><span class="indexed"></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">Mu</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><a id="i42" name="objects bless"></a><span class="indexed"></span> <a id="i43" name="bless"></a><span class="indexed"></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 create the object themselves. The easiest way to do this is by calling the <a href="#_routine_bless.pod6">bless</a> method, also inherited from <a href="#_type_Mu.pod6">Mu</a>. The <span class="code">bless</span> method expects a set of named parameters to provide 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><a id="i44" name="BUILD"></a><span class="indexed"></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.pod6-Object_Construction">objects</a> for more information.</p>
<p>The <span class="code">BUILD</span> method is responsible for initializing all attributes and must also handle default values:</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.pod6-Object_Construction">Object Construction</a> for more options to influence object construction and attribute initialization.</p>
<a name="t7.6"></a> <h1 id="_language_classtut.pod6-Consuming_our_class">Consuming our class</h1>
<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 &quot;empty instance&quot; 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 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="t7.7"></a> <h1 id="_language_classtut.pod6-Inheritance">Inheritance</h1>
<p><a id="i45" name="is (inheritance)"></a><span class="indexed"></span></p>
<p>Object Oriented Programming provides the concept of inheritance as one of the mechanisms 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>
<pre class="code">class Employee {
has $.salary;
method pay() {
say &quot;Here is \$$.salary&quot;;
}
}
class Programmer is Employee {
has @.known_languages is rw;
has $.favorite_editor;
method code_to_solve( $problem ) {
say &quot;Solving $problem using $.favorite_editor in &quot;
~ $.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 =&gt; 100_000,
known_languages =&gt; &lt;Perl5 Perl6 Erlang C++&gt;,
favorite_editor =&gt; 'vim'
);
$programmer.code_to_solve('halting problem');
$programmer.pay();
</pre>
<a name="t7.7.1"></a> <h2 id="_language_classtut.pod6-Overriding_inherited_methods">Overriding inherited methods</h2>
<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 &quot;Cooking $food&quot;;
}
method clean_utensils {
say &quot;Cleaning $_&quot; for @.utensils;
}
}
class Baker is Cook {
method cook( $confection ) {
say &quot;Baking a tasty $confection&quot;;
}
}
my $cook = Cook.new(
utensils =&gt; &lt;spoon ladle knife pan&gt;,
cookbooks =&gt; 'The Joy of Cooking',
salary =&gt; 40000);
$cook.cook( 'pizza' ); # OUTPUT: «Cooking pizza␤»
my $baker = Baker.new(
utensils =&gt; 'self cleaning oven',
cookbooks =&gt; &quot;The Baker's Apprentice&quot;,
salary =&gt; 50000);
$baker.cook('brioche'); # OUTPUT: «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>To access methods in the inheritance chain use <a href="#_language_functions.pod6-Re-dispatching">re-dispatch</a> or the <a href="#_type_Metamodel::ClassHOW.pod6-method_can">MOP</a>.</p>
<a name="t7.7.2"></a> <h2 id="_language_classtut.pod6-Multiple_inheritance">Multiple inheritance</h2>
<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 better than depth-first search for handling multiple inheritance.</p>
<pre class="code">class GeekCook is Programmer is Cook {
method new( *%params ) {
push( %params&lt;cookbooks&gt;, &quot;Cooking for Geeks&quot; );
return self.bless(|%params);
}
}
my $geek = GeekCook.new(
books =&gt; 'Learning Perl 6',
utensils =&gt; ('stainless steel pot', 'knife', 'calibrated oven'),
favorite_editor =&gt; 'MacVim',
known_languages =&gt; &lt;Perl6&gt;
);
$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.pod6-Roles">Roles</a>.</p>
<a name="t7.7.3"></a> <h2 id="_language_classtut.pod6-The_also_declarator">The <a name="46"></a><span class="code">also</span> declarator</h2>
<p>Classes to be inherited from can be listed in the class declaration body by prefixing the <span class="code">is</span> trait with <span class="code">also</span>. This also works for the role composition trait <span class="code">does</span>.</p>
<pre class="code">class GeekCook {
also is Programmer;
also is Cook;
# ...
}
role A {};
role B {};
class C { also does A; also does B }
</pre>
<a name="t7.8"></a> <h1 id="_language_classtut.pod6-Introspection">Introspection</h1>
<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 &quot;It's an employee&quot; };
if $o ~~ GeekCook { say &quot;It's a geeky cook&quot; };
say $o.WHAT;
say $o.perl;
say $o.^methods(:local)».name.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 =&gt; [&quot;Perl&quot;, &quot;Python&quot;, &quot;Pascal&quot;],
favorite_editor =&gt; &quot;gvim&quot;, salary =&gt; &quot;too small&quot;)
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, it is very useful for debugging simple objects. <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> <a id="i47" name="^methods"></a><span class="indexed"></span> <span class="code">$o.^methods(:local)</span> produces a list of <a href="#_type_Method.pod6">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">Programmer</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 its <i>meta class</i>, which is a class managing the properties of the <span class="code">Programmer</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>
</div>
<!-- /language/community.pod6 --><div class="pod-body"><a id="_language_community.pod6"></a><a name="t8"></a><h1 class="title">8 Community </h1> <p class="subtitle">Information about the people working on and using Perl 6</p> <a name="t8.1"></a> <h1 id="_language_community.pod6-Overview">Overview</h1>
<p>&quot;Perl 5 was my rewrite of Perl. I want Perl 6 to be the community's rewrite of Perl and of the community.&quot; - Larry Wall</p>
<a name="t8.2"></a> <h1 id="_language_community.pod6-IRC">IRC</h1>
<p>There is a large presence on the <span class="code">#perl6</span> channel on <span class="code">freenode.net</span>, who are happy to provide support and answer questions.</p>
</div>
<!-- /language/concurrency.pod6 --><div class="pod-body"><a id="_language_concurrency.pod6"></a><a name="t9"></a><h1 class="title">9 Concurrency</h1> <p class="subtitle">Concurrency and Asynchronous Programming</p> <p>In common with most modern programming languages, Perl 6 is designed to <a href="https://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 (e.g., <a href="#_type_Thread.pod6">Thread</a> and <a href="#_type_Scheduler.pod6">Scheduler</a>) and use the higher-level interfaces.</p>
<a name="t9.1"></a> <h1 id="_language_concurrency.pod6-High-level_APIs">High-level APIs</h1>
<a name="t9.1.1"></a> <h2 id="_language_concurrency.pod6-Promises">Promises</h2>
<p>A <a href="#_type_Promise.pod6">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. A <span class="code">Promise</span> starts from a <span class="code">Planned</span> status and can result in either a <span class="code">Kept</span> status, meaning the promise has been successfully completed, or a <span class="code">Broken</span> status meaning that the promise has failed. Usually this is 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; # OUTPUT: «Planned␤»
$p1.keep('result');
say $p1.status; # OUTPUT: «Kept␤»
say $p1.result; # OUTPUT: «result␤»
# (since it has been kept, a result is available!)
my $p2 = Promise.new;
$p2.break('oh no');
say $p2.status; # OUTPUT: «Broken␤»
say $p2.result; # dies, because the promise has been broken
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::AdHoc+{X::Promise::Broken}: oh no␤»
</pre>
<p>Promises gain much of their power by being composable, for example by chaining, usually by the <a href="#_type_Promise.pod6-method_then">then</a> method:</p>
<pre class="code">my $promise1 = Promise.new();
my $promise2 = $promise1.then(
-&gt; $v { say $v.result; &quot;Second Result&quot; }
);
$promise1.keep(&quot;First Result&quot;);
say $promise2.result; # OUTPUT: «First Result␤Second Result␤»</pre>
<p>Here the <a href="#_type_Promise.pod6-method_then">then</a> method schedules code to be executed when the first <a href="#_type_Promise.pod6">Promise</a> is kept or broken, itself returning a new <a href="#_type_Promise.pod6">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(-&gt; $v { say &quot;Handled but : &quot;; say $v.result});
$promise1.break(&quot;First Result&quot;);
try $promise2.result;
say $promise2.cause; # OUTPUT: «Handled but : ␤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="#_type_Exception.pod6">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="#_type_X::Promise::CauseOnlyValidOnBroken.pod6">X::Promise::CauseOnlyValidOnBroken</a> exception.</p>
<p>A <a href="#_type_Promise.pod6">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(-&gt; $v { say $v.status; 'Second Result' });
say $promise2.result;</pre>
<p>The <a href="#_type_Promise.pod6-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="#_type_Promise.pod6">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.pod6-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; # OUTPUT: «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="#_type_Exception.pod6">Exception</a> object that was thrown:</p>
<pre class="code">my $promise = Promise.start({ die &quot;Broken Promise&quot; });
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; # OUTPUT: «[55 -55]␤»</pre>
<p>In addition to <span class="code">await</span>, two class methods combine several <a href="#_type_Promise.pod6">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:</p>
<pre class="code">my $promise = Promise.allof(
Promise.in(2),
Promise.in(3)
);
await $promise;
say &quot;All done&quot;; # 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:</p>
<pre class="code">my $promise = Promise.anyof(
Promise.in(3),
Promise.in(8600)
);
await $promise;
say &quot;All done&quot;; # 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. You may, for example, want to create a dependent Promise that will examine each of the original promises:</p>
<pre class="code">my @promises;
for 1..5 -&gt; $t {
push @promises, start {
sleep $t;
Bool.pick;
};
}
say await Promise.allof(@promises).then({ so all(@promises&gt;&gt;.result) });</pre>
<p>Which will give True if all of the promises were kept with True, False otherwise.</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.pod6-method_vow">method vow</a>, which returns a <a href="#_type_Vow.pod6">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="#_type_X::Promise::Vowed.pod6">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
# &quot;Access denied to keep/break this Promise; already vowed&quot;
$promise.keep;
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Promise::Vowed: Access denied to keep/break this Promise; already vowed␤»</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"></a> <h2 id="_language_concurrency.pod6-Supplies">Supplies</h2>
<p>A <a href="#_type_Supply.pod6">Supply</a> is an asynchronous data streaming mechanism that can be consumed by one or more consumers simultaneously in a manner similar to &quot;events&quot; in other programming languages and can be seen as enabling &quot;Event Driven&quot; or reactive designs.</p>
<p>At its simplest, a <a href="#_type_Supply.pod6">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="#_type_Supply.pod6">Supply</a> can either be <span class="code">live</span> or <span class="code">on-demand</span>. A <span class="code">live</span> supply is like a TV broadcast: those who tune in don't get previously emitted values. An <span class="code">on-demand</span> broadcast is like Netflix: everyone who starts streaming a movie (taps a supply), always starts it from the beginning (gets all the values), regardless of how many people are watching it right now. Note that no history is kept for <span class="code">on-demand</span> supplies, instead, the <span class="code">supply</span> block is run for each tap of the supply.</p>
<p>A <span class="code">live</span> <a href="#_type_Supply.pod6">Supply</a> is created by the <a href="#_type_Supplier.pod6">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( -&gt; $v { say $v });
for 1 .. 10 {
$supplier.emit($_);
}</pre>
<p>Note that the <span class="code">tap</span> is called on a <a href="#_type_Supply.pod6">Supply</a> object created by the <a href="#_type_Supplier.pod6">Supplier</a> and new values are emitted on the <a href="#_type_Supplier.pod6">Supplier</a>.</p>
<p><a id="i48" name="supply (on-demand)"></a><span class="indexed"></span> An <span class="code">on-demand</span> <a href="#_type_Supply.pod6">Supply</a> is created by the <span class="code">supply</span> keyword:</p>
<pre class="code">my $supply = supply {
for 1 .. 10 {
emit($_);
}
}
$supply.tap( -&gt; $v { say $v });</pre>
<p>In this case the code in the supply block is executed every time the <a href="#_type_Supply.pod6">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( -&gt; $v { say &quot;First : $v&quot; });
$supply.tap( -&gt; $v { say &quot;Second : $v&quot; });</pre>
<p>The <span class="code">tap</span> method returns a <a href="#_type_Tap.pod6">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( -&gt; $v { say $v });
$supplier.emit(&quot;OK&quot;);
$tap.close;
$supplier.emit(&quot;Won't trigger the tap&quot;);</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(-&gt; $v { say $v });
sleep 10;</pre>
<p><a id="i49" name="react"></a><span class="indexed"></span> This could also be written using the <span class="code">react</span> keyword:</p>
<pre class="code">react {
whenever Supply.interval(2) -&gt; $v {
say $v;
done() if $v == 4;
}
}</pre>
<p>Here the <a id="i50" name=""></a><span class="indexed"><span class="code">whenever</span></span> keyword uses <a href="#_type_Supply.pod6-method_act"><span class="code">.act</span></a> to create a tap on the <a href="#_type_Supply.pod6">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(-&gt; $v { say &quot;First $v&quot; });
sleep 6;
$supply.tap(-&gt; $v { say &quot;Second $v&quot;});
sleep 10;</pre>
<p>An <span class="code">on-demand</span> <a href="#_type_Supply.pod6">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) -&gt; $v {
say $v;
}
}</pre>
<p>A live <span class="code">Supply</span> that keeps values until first tapped can be created with <a href="#_type_Supplier::Preserving.pod6">Supplier::Preserving</a>.</p>
<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(-&gt; $v { say &quot;Original : $v&quot; });
my $odd_supply = $supply.grep({ $_ % 2 });
$odd_supply.tap(-&gt; $v { say &quot;Odd : $v&quot; });
my $even_supply = $supply.grep({ not $_ % 2 });
$even_supply.tap(-&gt; $v { say &quot;Even : $v&quot; });
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(-&gt; $v { say &quot;Original : $v&quot; });
my $half_supply = $supply.map({ $_ / 2 });
$half_supply.tap(-&gt; $v { say &quot;Half : $v&quot; });
for 0 .. 10 {
$supplier.emit($_);
}</pre>
<p>If you need to have an action that runs when the supply finishes, you can do so by setting the <span class="code">done</span> and <span class="code">quit</span> options in the call to <span class="code">tap</span>:</p>
<pre class="code">$supply.tap: { ... },
done =&gt; { say 'Job is done.' },
quit =&gt; {
when X::MyApp::Error { say &quot;App Error: &quot;, $_.message }
};
</pre>
<p>The <span class="code">quit</span> block works very similar to a <span class="code">CATCH</span>. If the exception is marked as seen by a <span class="code">when</span> or <span class="code">default</span> block, the exception is caught and handled. Otherwise, the exception continues to up the call tree (i.e., the same behavior as when <span class="code">quit</span> is not set).</p>
<p><a id="i51" name="whenever"></a><span class="indexed"></span> If you are using the <span class="code">react</span> or <span class="code">supply</span> block syntax with <span class="code">whenever</span>, you can add phasers within your <span class="code">whenever</span> blocks to handle the <span class="code">done</span> and <span class="code">quit</span> messages from the tapped supply:</p>
<pre class="code">react {
whenever $supply {
...; # your usual supply tap code here
LAST { say 'Job is done.' }
QUIT { when X::MyApp::Error { say &quot;App Error: &quot;, $_.message } }
}
}
</pre>
<p>The behavior here is the same as setting <span class="code">done</span> and <span class="code">quit</span> on <span class="code">tap</span>.</p>
<a name="t9.1.3"></a> <h2 id="_language_concurrency.pod6-Channels">Channels</h2>
<p>A <a href="#_type_Channel.pod6">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 &quot;fifo&quot; 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="#_type_Channel.pod6">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="#_type_Supply.pod6">Supply</a>.</p>
<p>An item is queued onto the <a href="#_type_Channel.pod6">Channel</a> with the <a href="#_type_Channel.pod6-method_send">method send</a>, and the <a href="#_type_Channel.pod6-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; # OUTPUT: «Channel One␤»</pre>
<p>If the channel has been closed with the <a href="#_type_Channel.pod6-method_close">method close</a> then any <span class="code">send</span> will cause the exception <a href="#_type_X::Channel::SendOnClosed.pod6">X::Channel::SendOnClosed</a> to be thrown, and a <span class="code">receive</span> will throw a <a href="#_type_X::Channel::ReceiveOnClosed.pod6">X::Channel::ReceiveOnClosed</a> if there are no more items on the queue.</p>
<p>The <a href="#_type_Channel.pod6-method_list">method list</a> returns all the items on the <a href="#_type_Channel.pod6">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: -&gt; $r {
start {
sleep $r;
$channel.send($r);
}
}
$channel.close;
for $channel.list -&gt; $r {
say $r;
}</pre>
<p>There is also the non-blocking <a href="#_type_Channel.pod6-method_poll">method poll</a> that returns an available item from the channel or <a href="#_type_Nil.pod6">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 three Promises that sleep for 1..3 seconds, and then
# send a value to our Channel
^3 .map: -&gt; $v {
start {
sleep 3 - $v;
$c.send: &quot;$v from thread {$*THREAD.id}&quot;;
}
}
# Wait 3 seconds before closing the channel
Promise.in(3).then: { $c.close }
# Continuously loop and poll the channel, until it's closed
my $is-closed = $c.closed;
loop {
if $c.poll -&gt; $item {
say &quot;$item received after {now - INIT now} seconds&quot;;
}
elsif $is-closed {
last;
}
say 'Doing some unrelated things...';
sleep .6;
}
# Doing some unrelated things...
# Doing some unrelated things...
# 2 from thread 5 received after 1.2063182 seconds
# Doing some unrelated things...
# Doing some unrelated things...
# 1 from thread 4 received after 2.41117376 seconds
# Doing some unrelated things...
# 0 from thread 3 received after 3.01364461 seconds
# Doing some unrelated things...</pre>
<p>The <a href="#_type_Channel.pod6-method_closed">method closed</a> returns a <a href="#_type_Promise.pod6">Promise</a> that will be kept (and consequently will evaluate to True in a boolean context) when the channel is closed.</p>
<p>The <span class="code">.poll</span> method can be used in combination with <span class="code">.receive</span> method, as a caching mechanism where lack of value returned by `.poll` is a signal that more values need to be fetched and loaded into the channel:</p>
<pre class="code">sub get-value {
return $c.poll // do { start replenish-cache; $c.receive };
}
sub replenish-cache {
for ^20 {
$c.send: $_ for slowly-fetch-a-thing();
}
}
</pre>
<p>Channels can be used in place of the <a href="#_type_Supply.pod6">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: -&gt; $r {
start {
sleep $r;
$channel.send($r);
}
}
$channel.close;
await $p;
</pre>
<p>It is also possible to obtain a <a href="#_type_Channel.pod6">Channel</a> from a <a href="#_type_Supply.pod6">Supply</a> using the <a href="#_type_Supply.pod6-method_Channel">Channel method</a> which returns a <a href="#_type_Channel.pod6">Channel</a> which is fed by a <span class="code">tap</span> on the <a href="#_type_Supply.pod6">Supply</a>:</p>
<pre class="code">my $supplier = Supplier.new;
my $supply = $supplier.Supply;
my $channel = $supply.Channel;
my $p = start {
react {
whenever $channel -&gt; $item {
say &quot;via Channel: $item&quot;;
}
}
}
await (^10).map: -&gt; $r {
start {
sleep $r;
$supplier.emit($r);
}
}
$supplier.done;
await $p;</pre>
<p><span class="code">Channel</span> will return a different <a href="#_type_Channel.pod6">Channel</a> fed with the same data each time it is called. This could be used, for instance, to fan-out a <a href="#_type_Supply.pod6">Supply</a> to one or more <a href="#_type_Channel.pod6">Channel</a>s to provide for different interfaces in a program.</p>
<a name="t9.1.4"></a> <h2 id="_language_concurrency.pod6-Proc::Async">Proc::Async</h2>
<p><a href="#_type_Proc::Async.pod6">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(-&gt; $v { print &quot;Output: $v&quot; });
$proc.stderr.tap(-&gt; $v { print &quot;Error: $v&quot; });
say &quot;Starting...&quot;;
my $promise = $proc.start;
await $promise;
say &quot;Done.&quot;;
# 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.pod6-method_start">start</a> is called, which will return a <a href="#_type_Promise.pod6">Promise</a> that will be kept when the program exits. The standard output and standard error of the program are available as <a href="#_type_Supply.pod6">Supply</a> objects from the methods <a href="#_type_Proc::Async.pod6-method_stdout">stdout</a> and <a href="#_type_Proc::Async.pod6-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.pod6-method_write">write</a>, <a href="#_type_Proc::Async.pod6-method_print">print</a> or <a href="#_type_Proc::Async.pod6-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(-&gt; $v { print &quot;Output: $v&quot; });
say &quot;Starting...&quot;;
my $promise = $proc.start;
$proc.say(&quot;this line has foo&quot;);
$proc.say(&quot;this one doesn't&quot;);
$proc.close-stdin;
await $promise;
say &quot;Done.&quot;;
# 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.pod6-method_close-stdin">close-stdin</a> can be called when you are finished writing to allow the <a href="#_type_Promise.pod6">Promise</a> returned by <span class="code">start</span> to be kept.</p>
<a name="t9.2"></a> <h1 id="_language_concurrency.pod6-Low-level_APIs">Low-level APIs</h1>
<a name="t9.2.1"></a> <h2 id="_language_concurrency.pod6-Threads">Threads</h2>
<p>The lowest level interface for concurrency is provided by <a href="#_type_Thread.pod6">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 =&gt; { for 1 .. 10 -&gt; $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 -&gt; $v { say $v }});</pre>
<p>In both cases the completion of the code encapsulated by the <a href="#_type_Thread.pod6">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 emphasized that threads are unlikely to be useful directly in user code.</p>
<a name="t9.2.2"></a> <h2 id="_language_concurrency.pod6-Schedulers">Schedulers</h2>
<p>The next level of the concurrency API is supplied by classes that implement the interface defined by the role <a href="#_type_Scheduler.pod6">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="#_type_Proc::Async.pod6">Proc::Async</a>, <a href="#_type_Promise.pod6">Promise</a> and <a href="#_type_Supply.pod6">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="#_type_Scheduler.pod6">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="#_type_Callable.pod6">Callable</a> in <span class="code">&amp;code</span> to be executed in the manner determined by the adverbs (as documented in <a href="#_type_Scheduler.pod6">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 =&gt; 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="#_type_Cancellation.pod6">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 =&gt; 2 );
sleep 10;
$cancellation.cancel;
sleep 10;</pre>
<p>should only output 0 to 5,</p>
<p>Despite the apparent advantage the <a href="#_type_Scheduler.pod6">Scheduler</a> interface provides over that of <a href="#_type_Thread.pod6">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"></a> <h3 id="_language_concurrency.pod6-ThreadPoolScheduler">ThreadPoolScheduler</h3>
<p>The <a href="#_type_ThreadPoolScheduler.pod6">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"></a> <h3 id="_language_concurrency.pod6-CurrentThreadScheduler">CurrentThreadScheduler</h3>
<p>The <a href="#_type_CurrentThreadScheduler.pod6">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"></a> <h2 id="_language_concurrency.pod6-Locks">Locks</h2>
<p>The class <a href="#_type_Lock.pod6">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 &quot;Mutex&quot; in other programming languages. Because the higher level classes (<a href="#_type_Promise.pod6">Promise</a>, <a href="#_type_Supply.pod6">Supply</a> and <a href="#_type_Channel.pod6">Channel</a>) use a <a href="#_type_Lock.pod6">Lock</a> where required it is unlikely that user code will need to use a <a href="#_type_Lock.pod6">Lock</a> directly.</p>
<p>The primary interface to <a href="#_type_Lock.pod6">Lock</a> is the method <a href="#_type_Lock.pod6-method_protect">protect</a> which ensures that a block of code (commonly called a &quot;critical section&quot;) 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; # OUTPUT: «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"></a> <h1 id="_language_concurrency.pod6-Safety_Concerns">Safety Concerns</h1>
<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="#_type_Array.pod6">Array</a> or a <a href="#_type_Hash.pod6">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 <a href="#_type_Lock.pod6">Lock</a> to protect the critical section. A possibly better fix would be to refactor the code so that sharing a container is not necessary.</p>
</div>
<!-- /language/containers.pod6 --><div class="pod-body"><a id="_language_containers.pod6"></a><a name="t10"></a><h1 class="title">10 Containers</h1> <p class="subtitle">A low-level explanation of Perl 6 containers</p> <p>This article started as a conversation 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"></a> <h1 id="_language_containers.pod6-What_is_a_variable?">What is a variable?</h1>
<p>Some people like to say &quot;everything is an object&quot;, 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"></a> <h1 id="_language_containers.pod6-Scalar_containers">Scalar containers</h1>
<p>Although objects of type <a href="#_type_Scalar.pod6"><span class="code">Scalar</span></a> are everywhere in Perl 6, you rarely 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 &quot;replace the previously stored value with the new one&quot;.</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; # OUTPUT: «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; # OUTPUT: «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; # OUTPUT: «Int␤»
say $x.VAR.^name; # OUTPUT: «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;
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Parameter::RW: Parameter '$x' expected a writable container, but got Int value␤»</pre>
<a name="t10.3"></a> <h1 id="_language_containers.pod6-Callable_containers">Callable containers</h1>
<p>Callable containers provide a bridge between the syntax of a <a href="#_type_Routine.pod6">Routine</a> call and the actual call of the method <a href="#_type_Callable.pod6-method_CALL-ME">CALL-ME</a> of the object that is stored in the container. The sigil <span class="code">&amp;</span> is required when declaring the container and has to be omitted when executing the <span class="code">Callable</span>. The default type constraint is <a href="#_type_Callable.pod6">Callable</a>.</p>
<pre class="code">my &amp;c = -&gt; Int $a { say &quot;$a is whole&quot; }
c;
c();</pre>
<p>The sigil has to be provided when referring to the value stored in the container. This in turn allows <span class="code">Routine</span>s to be uses as <a href="#_type_Signature.pod6-Constraining_signatures_of_Callables">arguments</a> to calls.</p>
<pre class="code">sub f() {}
my &amp;g = sub {}
sub caller(&amp;c1, &amp;c2){ c1, c2 }
caller(&amp;f, &amp;g);</pre>
<a name="t10.4"></a> <h1 id="_language_containers.pod6-Binding">Binding</h1>
<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">my $x := 42;
$x = 23;
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::AdHoc: Cannot assign to an immutable value␤»</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; # OUTPUT: «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><a id="i52" name="\ (container binding)"></a><span class="indexed"></span> Sigilless variables 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; # OUTPUT: «43␤»
sub f($c is raw) { $c++ }
f($a);
say $a; # OUTPUT: «44␤»</pre>
<a name="t10.5"></a> <h1 id="_language_containers.pod6-Scalar_containers_and_listy_things">Scalar containers and listy things</h1>
<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.pod6">List</a> It is created by the comma operator.</p>
<pre class="code">say (1, 2, 3).^name; # OUTPUT: «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; # OUTPUT: «23␤»
($x, 1, 2)[1] = 23; # Cannot modify an immutable value
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Assignment::RO: Cannot modify an immutable Int␤»</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; # OUTPUT: «[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>
<a name="t10.6"></a> <h1 id="_language_containers.pod6-Assigning_and_binding_to_array_variables">Assigning and binding to array variables</h1>
<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; # OUTPUT: «Int␤»
my @a = 42; say @a.^name; # OUTPUT: «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.^name; # OUTPUT: «List␤»</pre>
<a name="t10.7"></a> <h1 id="_language_containers.pod6-Binding_to_array_elements">Binding to array elements</h1>
<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; # OUTPUT: «[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; # runtime error: X::Bind::Slice
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Bind::Slice: Cannot bind to Array slice␤»</pre>
<p>Operations that mix Lists and Arrays generally protect against such a thing happening accidentally.</p>
<a name="t10.8"></a> <h1 id="_language_containers.pod6-Flattening,_items_and_containers">Flattening, items and containers</h1>
<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><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; # OUTPUT: «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; # OUTPUT: «5␤»
sub f(*@x) { @x.elems };
say f @a, 4, 5; # OUTPUT: «5␤»</pre>
<p>As hinted above, scalar containers prevent that flattening:</p>
<pre class="code">sub f(*@x) { @x.elems };
my @a = 1, 2, 3;
say f $@a, 4, 5; # OUTPUT: «3␤»</pre>
<p>The <span class="code">@</span> character can also be used as a prefix to coerce the argument to a list, thus removing a scalar container:</p>
<pre class="code">my $x = (1, 2, 3);
.say for @$x; # 3 iterations</pre>
<p>However, the <span class="code">&lt;&gt;</span> is more appropriate to decontainerize items that aren't lists:</p>
<pre class="code">my $x = ^Inf .grep: *.is-prime;
say &quot;$_ is prime&quot; for @$x; # WRONG! List keeps values, thus leaking memory
say &quot;$_ is prime&quot; for $x&lt;&gt;; # RIGHT. Simply decontainerize the Seq
my $y := ^Inf .grep: *.is-prime; # Even better; no Scalars involved at all</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.9"></a> <h1 id="_language_containers.pod6-Self-Referential_Data">Self-Referential Data</h1>
<p>Containers types, including <span class="code">Array</span> and <span class="code">Hash</span>, allow you to create self-referential structures.</p>
<pre class="code">my @a;
@a[0] = @a;
put @a.perl;
# OUTPUT: «((my @Array_75093712) = [@Array_75093712,])␤»</pre>
<p>Perl 6 does not prevent you from creating and using self-referential data; You may end up in a loop trying to dump the data; as a last resort, you can use Promises to <a href="#_type_Promise.pod6-method_in">handle</a> timeouts.</p>
<a name="t10.10"></a> <h1 id="_language_containers.pod6-Type_Constraints">Type Constraints</h1>
<p>Any container can have a type constraint in the form of a <a href="#_language_typesystem.pod6-Type_objects">type object</a> or a <a href="#_language_typesystem.pod6-subset">subset</a>. Both can be placed between a declarator and the variable name or after the trait <a href="#_type_Variable.pod6-trait_is_dynamic">of</a>. The constraint is a property of the container, not the variable. Any (re-)binding may change the type constraint or remove the constraint altogether if bound to a value instead of a container. Introspection of type constraints on containers is provided by <span class="code">.VAR.of</span>.</p>
<pre class="code">EVAL ‚my Int $i = 42; $i := &quot;forty plus two&quot;;‘;
CATCH { default { say .^name, ' ', .Str } }
# OUTPUT: «Type check failed in binding; expected Int but got Str (&quot;forty plus two&quot;)␤…»</pre>
<p>The default type constraint of a <span class="code">Scalar</span> container is Any. For &amp;-sigiled containers it's <span class="code">Callable</span> and @-sigiled containers are of type <span class="code">Array</span>. Please note that binding can change the type constraint.</p>
<a name="t10.11"></a> <h1 id="_language_containers.pod6-Custom_containers">Custom containers</h1>
<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 as 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 =&gt; method () { $c-value },
STORE =&gt; method (T $new-value) {
X::OutOfRange.new(what =&gt; 'number', got =&gt; '13', range =&gt; '-∞..12, 14..∞').throw
if $new-value == 13;
$c-value = $new-value;
}
);
}
my Int $a := lucky(Int);
say $a = 12; # OUTPUT: «12␤»
say $a = 'FOO'; # X::TypeCheck::Binding
say $a = 13; # X::OutOfRange
CATCH { default { say .^name, ': ', .Str } };</pre>
</div>
<!-- /language/contributors.pod6 --><div class="pod-body"><a id="_language_contributors.pod6"></a><a name="t11"></a><h1 class="title">11 Contributors</h1> <p class="subtitle">List of contributors to Perl 6 over the years</p> <p>The following people contributed to the development of Perl 6, as could be determined from the logs of all the various projects that make up Perl 6. If you think you are missing from this list, or for any reason would not like to appear on this list, or need a correction, please submit a <a href="#_language_glossary.pod6-Pull_Request">Pull Request</a> with the required change(s).</p>
<a name="t11.1"></a> <h1 id="_language_contributors.pod6-A">A</h1>
<pre class="code"> Gisle Aas
abcxyzp
Chuck Adams
Colin Paul Adams
Rod Adams
C.J. Adams-Collier
David H. Adler
Chirag Agrawal
Amir E. Aharoni
Bilal Akhtar
Julian Albo
Alekssasho
alexghacker
Paco Alguacil
Brandon S Allbery
Geir Amdal
Markus Amsler
Paul C. Anagnostopoulos
Nikolay Ananiev
anatolyv
andras
Saleem Ansari
Joji Antony
Tomoki Aonuma
Syed Uzair Aqeel
arathorn
Arcterus
Kodi Arfer
Daniel Arbelo Arrocha
ash
Ted Ashton
Arnaud Assad
atroxaper
Ori Avtalion אורי אבטליון
Auzon
Alex Chen 陈梓立
</pre>
<a name="t11.2"></a> <h1 id="_language_contributors.pod6-B">B</h1>
<pre class="code"> Greg Bacon
Ivan Baidakou
Alex Balhatchet
Szabó
Balázs
Amir Livine Bar-On עמיר ליבנה בר-און
Luca Barbato
Mattia Barbon
Ann Barcomb
Christian Bartolomäus
Alex &quot;Skud&quot; Bayley
bcmb
Jody Belka
Shachaf Ben-Kiki
Andrei Benea
benedikth
Zev Benjamin
benmorrow
Kevan Benson
Martin Berends
Anton Berezin
Arthur Bergman
Anders Nor Berle
bestian
Peter Bevan
Mark Biggar
Carlin Bingham
Ævar Arnfjörð Bjarmason
J. David Blackstone
Ronald Blaschke
Ingo Blechschmidt
bloonix
blwood
Kristof Bogaerts
Dan Bolser
Конрад Боровски
Christopher Bottoms
Gonéri Le Bouder
Jos Boumans
Brad Bowman
Matt Boyle
bpetering
H.Merijn Brand
Terrence Brannon
Gwern Branwen
Stig Brautaset
Herbert &quot;lichtkind&quot; Breunung
bri
brian_d_foy
Fernando Brito
Geoffrey Broadwell
Leon Brocard
Benjamin Brodfuehrer
Samuel Bronson
Dan Brook
Nathan C. Brown
Roger Browne
Philippe Bruhat (BooK)
David Brunton
Corwin Brust
Klaus Brüssel
Lucas Buchala
buchetc
Christoph Buchetmann
Norbert Buchmuller
Buddha Buck
Alexandre Buisse
Tim Bunce
Bryan Burgers
Sean M. Burke
Matthew Byng-Maddick
András Bártházi
Jürgen Bömmels
</pre>
<a name="t11.3"></a> <h1 id="_language_contributors.pod6-C">C</h1>
<pre class="code"> Caelum
Aldo Calpini
Edward Cant
David Cantrell
Carlin
Michael Cartmell
Hezekiah Carty
Nuno 'smash' Carvalho
Marcelo Serra Castilhos
Piers Cawley
cdavaz
cdpruden
Gianni Ceccarelli
cfourier
Marc Chantreux
Mitchell N Charity
Oliver Charles
Vasily Chekalkin
Yuan-Chen Cheng 鄭原真
Daniel Chetlin
Hsin-Chan Chien 簡信昌
N. Hao Ching
Joshua Choi
Elizabeth Cholet
David Christensen
chuck
cjeris
Nicholas Clark
Steve Clark
Jeff Clites
cmarcelo
cmeyer
Paul Cochrane
Daniel Colascione
Jason Cole
Will &quot;Coke&quot; Coleda
Sylvain Colinet
cono
Tim Conrow
Géraud Continsouzas
Damian Conway
Neil Conway
Stuart Cook
David Corbin
Deven T. Corzine
cosmicnet
Timothy Covell
Beau E. Cox
Simon Cozens
Philip Crow
cspenser
Franck Cuny
Tyler Curtis
David Czech
</pre>
<a name="t11.4"></a> <h1 id="_language_contributors.pod6-D">D</h1>
<pre class="code"> Daenyth
Dagur
Ritz Daniel
darkwolf
Chris Davaz
David Warring
Justin DeVuyst
Daniel Dehennin
Akim Demaille
Detonite
Lars &quot;daxim&quot; Dieckow 迪拉斯
Matt Diephouse
Bob Diertens
Wendy &quot;woolfy&quot; van Dijk
Jeffrey Dik
John M. Dlugosz
dimid
diotalevi
Hans van Dok
Chris Dolan
Mark Dominus
Bryan Donlan
Andy Dougherty
Dave Doyle
drKreso
dr_df0
dudley
Jonathan Scott Duff
dug
Lee Duhem
Darren Duncan
</pre>
<a name="t11.5"></a> <h1 id="_language_contributors.pod6-E">E</h1>
<pre class="code"> Andrew Egeler
Havard Eidnes
Nelson Elhage
Ran Eliam
Fitz Elliott
Alex Elsayed
Jay Emerson
Aankhola Encorporated
ennio
Enveigler
Jon Ericson
Shae Matijs Erisson
Eryq
Mike Eve
Pat Eyler
</pre>
<a name="t11.6"></a> <h1 id="_language_contributors.pod6-F">F</h1>
<pre class="code"> Aaron Faanes
Kevin Falcone
David Farrell
Angel Faus
Jason Felds
Paul Fenwick
Jose Rodrigo Fernandez
Nelson Ferraz
Adriano Ferreira
João Fernando Ferreira
Chris Fields
Caio Marcelo de Oliveira Filho
Steve Fink
Shlomi &quot;rindolf&quot; Fish שלומי פיש
Mark Leighton Fisher
Scott Fitzenrider
Dudley Flanders
Richard Foley
Vincent Foley
Julian Fondren
Ruben Fonseca
David Formosa
Karl Forner
Solomon Foster
Chaddaï Fouché
Lloyd Fournier
Michael Fowler
Matt Fowles
franck
Austin Frank
Carl Franks
Kent Fredric
Chaim Frenkel
Piotr Fusik
</pre>
<a name="t11.7"></a> <h1 id="_language_contributors.pod6-G">G</h1>
<pre class="code"> gabriele
John Gabriele
Christoph Gärtner
Martin von Gagern
Felix Gallo
Salvador Ortiz Garcia
Rafaël Garcia-Suarez
Joshua Gatcomb
Jerry Gay
gcomnz
Jonathan Gentle
iVAN Georgiev
Brian Gernhardt
Bram Geron
Alessandro Ghedini
Imran Ghory
Peter Gibbs
Tanton Gibbs
Brad Gilbert (b2gills)
Karl Glazebrook
Nick Glencross
Mark Glines
Flávio S. Glock
Jason Gloudon
Simon Glover
gnuvince
Garrett Goebel
Jeffrey Goff
Mikhael Goikhman
Benjamin Goldberg
Arcady Goldmints-Orlov
Dimitry Golubovsky
Gerard Goossen
Goplat
Alex Gough
Léo Grange
Chad &quot;Exodist&quot; Granum
Kenneth A Graves
Bruce Gray
Nathan Gray
Mark Grimes
Lucien Grondin
Rolf Grossmann
David Grove
Marcel Grünauer
Daniel Grunblatt
Uri Guttman
gwern
</pre>
<a name="t11.8"></a> <h1 id="_language_contributors.pod6-H">H</h1>
<pre class="code"> Swaroop C H
Richard Hainsworth
Roger Hale
John &quot;ab5tract&quot; Haltiwanger
Nigel Hamilton
Eric Hanchrow
Sterling Hanenkamp
Ask Bjørn Hansen
Christian &quot;chansen&quot; Hansen
Eirik Berg Hanssen
Samuel Harrington
Trey Harris
John Harrison
Carsten Hartenfels
Richard Hartmann
Kyle Hasselbacher
Austin Hastings
Carl Hayter
Florian Helmberger
Gordon Henriksen
Felix Herrmann
Peter Heslin
Fred Heutte
Jarkko Hietaniemi
Michael H. Hind
Joshua Hoblitt
Zack Hobson
Eric Hodges
Rob Hoelz
Masahiro Honma
Lyle Hopkins
JD Horelick
Jeff Horwitz
Chris Hostetter
Laurens Van Houtven
Jeremy Howard
Yiyi Hu 鹄驿懿
Benedikt Huber
Brad Hughes
Sterling Hughes
Tom Hughes
Tristan Hume
Donald Hunter
Douglas Hunter
Juan Francisco Cantero Hurtado
Kay-Uwe 'kiwi' Hüll
</pre>
<a name="t11.9"></a> <h1 id="_language_contributors.pod6-I">I</h1>
<pre class="code"> Alin Iacob
Ibotty
ibrown
ihrd
Roland Illing
Jan Ingvoldstad
Joshua Isom
isop
Ivan_A_Frey
ivanoff
</pre>
<a name="t11.10"></a> <h1 id="_language_contributors.pod6-J">J</h1>
<pre class="code"> Akash Manohar J
jafelds
Robert G. Jakabosky
jamesrom
S. A. Janet
jani
Heiko Jansen
Stuart Jansen
Jarrod
Jedai
Chris Jepeway
Chris Jeris
Dagur Valberg Johannsson
Erik Johansen
Paul Johnson
johnspurr
Isaac Jones
Norman Nunley Jr
Yoshikuni Jujo
Brian S. Julin
Josh Juran
Michal Jurosz
</pre>
<a name="t11.11"></a> <h1 id="_language_contributors.pod6-K">K</h1>
<pre class="code"> David Koenig
Prakash Kailasa
Shoichi Kaji
Daniel Kang
Isis Kang
Chia-Liang Kao 高嘉良
Dmitry Karasik
Luben Karavelov
Amir Karger
Offer Kaye
Bruce Keeler
James E Keenan
Cole Keirsey
Adam Kennedy
Matt Kennedy
Shane Kerr
khairul
Mikhail Khorkov
Krzysztof Kielak
Andres Kievsky
Daehyub Kim
Rob Kinyon
Oleg Kiselyov
Oolley kj
Martin Kjeldsen
Thomas &quot;domm&quot; Klausner
Zohar &quot;lumi&quot; Kelrich זהר קלריך/卡卓哈
Damian Miles Knopp
Dan Kogai 小飼弾
Yuval &quot;nothingmuch&quot; Kogman יובל קוג'מן
Tomasz Konojacki
Vadim Konovalov
Nick Kostirya
Matt Kraai
Thomas Kratz
Adrian Kreher
John van Krieken
Matthias Krull
Bradley M. Kuhn
Bob Kuo
Colin Kuskie
Kamil Kułaga
</pre>
<a name="t11.12"></a> <h1 id="_language_contributors.pod6-L">L</h1>
<pre class="code"> Sage LaTorra
Brent Laabs
laben
Johannes Laire
Markus Laire
Fayland Lam 林道
Mike Lambert
lanny
Leo Lapworth
last.of.the.careless.men
Bart Lateur
Jia-Hong Lee
Lola Lee
Jonathan Leffler
Tobias Leich
lembark
Mark Lentczner
Moritz A Lenz
Jean-Louis Leroy
Andy Lester
Jonathan &quot;Duke&quot; Leto
Vladimir Lettiev
Mike Li 李曉光
Stefan Lidman
Yung-Chung Lin 林永忠
Glenn Linderman
Vladimir Lipsky
Zach Lipton
Stevan Little
Kang-Min Liu 劉康民
Skip Livingston
David M. Lloyd
Daniel Lo
Peter Lobsinger
Andres Löh
Nick Logan
Eric Lubow
Nolan Lum
Peter Lunicks
LylePerl
Ian Lynagh
lysdexsik
</pre>
<a name="t11.13"></a> <h1 id="_language_contributors.pod6-M">M</h1>
<pre class="code"> Kiran Kumar M.
Jerry MacClure
Noel Maddy
Christopher J. Madsen
Abhijit A. Mahabal
Max Maischein
Peter Makholm
Ujwal Reddy Malipeddi
malon
Christopher Malon
Dagfinn Ilmari Mannsåker
Michael Maraist
Roie Marianer רועי מריאנר
markmont
Simon Marlow
martin
Paolo Martini
Ilya Martynov
Jaume Martí
James Mastros
Michael J. Mathews
Vyacheslav Matjukhin
Tokuhiro Matsuno
mattc
Mike Mattie
Elizabeth &quot;lizmat&quot; Mattijsen
Вячеслав Матюхин
Markus Mayr
Josh McAdams
Martin McCarthy
Mark McConnell
Steven McDougall
John McNamara
Scott McWhirter
mdinger
Olivier &quot;dolmen&quot; Mengué
Kevin Metcalf
Patrick R. Michaud
mimir
mjreed
Tom Moertel
Michael Mol
Paolo Molaro
Shawn M Moore
Brandon Michael Moore
Alexander Moquin
Ion Alexandru Morega
Dino Morelli
Kolia Morev
Zach Morgan
mr_ank
Alex Munroe
muraiki
Paweł Murias
mvuets
Steve Mynott
mzedeler
Carl Mäsak
</pre>
<a name="t11.14"></a> <h1 id="_language_contributors.pod6-N">N</h1>
<pre class="code"> naesten
Tim Nelson
Ailin Nemui
Ingy döt Net 應吉大聶
David Nicol
Faye Niemeyer
Nigelsandever
Karl Rune Nilsen
Salve J. Nilsen
Per Christian Nodtvedt
Ben Noordhuis
Paweł Nowak
Norman Nunley
</pre>
<a name="t11.15"></a> <h1 id="_language_contributors.pod6-O">O</h1>
<pre class="code"> Tony O'Dell
יהושע &quot;שי&quot; אוחיון
Clayton O'Neill
Stefan O'Rear
Sean O'Rourke
Matt Oates
Tony Olekshy
Martin Olsen
Dmitriy Olshevskiy
Dave Olszewski
Nelo Onyiah
William Orr
Jon Orwant
Andrei Osipov
Christoph Otto
</pre>
<a name="t11.16"></a> <h1 id="_language_contributors.pod6-P">P</h1>
<pre class="code"> Pawel Pabian
Walter Pallestrong
Luke Palmer
Bartłomiej Palmowski
Pancake
Paolo
Marton Papp
Andrew Parker
Roman M. Parparov
Anthony Parsons
Mike Pastore
Nova Patch
Timo Paulssen
Tony Payne
Stéphane &quot;cognominal&quot; Payrard
Slava Pechenin
Gael Pegliasco
Stéphane Peiry
Felipe Pena
Nayden Pendov
Wenzel P. P. Peppmeyer
François Perrad
Markus Peter
Ben Petering
Steve Peters
Tim Peterson
Ronny Pfannschmidt
Clinton A. Pierce
Jerrad Pierce
Thilo Planz
plunix
pmakholm
Curtis 'Ovid' Poe
Gerd Pokorra
Peter Polacik
Flavio Poletti
Kevin Polulak
John Porter
Ryan W. Porter
Stephen P. Potter
Philip Potter
Adam Preble
premshree
Klāvs Priedītis
Adam Prime
Richard Proctor
Christopher Pruden
Kevin Puetz
Gregor N. Purdy
purl
</pre>
<a name="t11.17"></a> <h1 id="_language_contributors.pod6-Q">Q</h1>
<pre class="code"> Hongwen Qiu
Jerome Quelin
quester
</pre>
<a name="t11.18"></a> <h1 id="_language_contributors.pod6-R">R</h1>
<pre class="code"> Gerhard R.
Peter Rabbitson
Florian Ragwitz
raiph
Matt Rajca
Marcus Ramberg
Claudio Ramirez
Prog Rammer
Allison Randal
David Ranvig
Lars Balker Rasmussen
Curtis Rawls
raydiak
Robin Redeker
Ted Reed
Jens Rehsack
Charles Reiss
Gabriele Renzi
Kenneth C. Rich
Jason Richmond
Ryan Richter
Sebastian Riedel
Dennis Rieks
Jens Rieks
Lanny Ripple
John Rizzo
rkhill
Andrew Robbins
Amos Robinson
Jonathan Rockway
Stefano Rodighiero
Andrew Rodland
Lindolfo Rodrigues
Bob Rogers
Dave Rolsky
David Romano
ron
Eric J. Roode
Garret Rooney
Garrett Rooney
David Ross
Andreas Rottmann
Brent Royal-Gordon
Shmarya Rubenstein
Sam Ruby
Simon Ruderich
Daniel Ruoso
Jake Russo
ruz
Joseph Ryan
Gilbert Röhrbein
</pre>
<a name="t11.19"></a> <h1 id="_language_contributors.pod6-S">S</h1>
<pre class="code"> Sam S
s1n
sahadev
Patrick Abi Salloum
salty_horse
Chip Salzenberg
Shrivatsan Sampathkumar
Igor Rafael Sanchez-Puls
Hugo van der Sanden
Thomas Sandlaß
Yun SangHo
sanug
Siddhant Saraf
Sasho
Andrew Savige
John Saylor
Matt Schallert
Bernhard Schmalhofer
Arthur Axel Schmidt
Ronald Schmidt
Michael Schroeder
Steven Schubiger
Steve &quot;thundergnat&quot; Schulze
Andreas Schwab
Randal L. Schwartz
Pepe Schwarz
Frederik Schwarzer
Calvin Schwenzfeier
Michael G. Schwern
Steffen Schwigon
Tom Scola
Ariel Scolnicov
Michael Scott
Peter Scott
Rick Scott
Stefan Seifert
Austin Seipp
Mark Senn
Filip Sergot
Seth Gold (Sgeo)
William Shallum
Kris Shannon
shenyute
Aaron Sherman
Mark Shoulson
Ryan Siemens
Ricardo Signes
Hinrik Örn Sigurðsson
Jonathan Sillito
Miroslav Silovic
Steve Simmons
Alberto Manuel Brandao Simoes
John Siracusa
Arne Skjærholt
Barrie Slaymaker
Radek Slupik
Mike Small
Benjamin Smith
Melvin Smith
Tim Smith
Adrian White aka
snarkyboojum
Richard Soderberg
SolidState
Vishal Soni
Syloke Soong
Shawn Sorichetti
Tadeusz Sośnierz
sue spence
Cory Spencer
Robert Spier
Michael Stapelberg
Edwin Steiner
stephenpollei
Michael Stevens
Don Stewart
Radu Stoica
Klaas-Jan Stol
Alek Storm
David Storrs
Mark Stosberg
Jonathan Stowe
Cosimo Streppone
Jonathan Strickland
Pascal Stumpf
Su-Shee
Sue
Laye Suen
Dan Sugalski
Mark Summerfield
Simon Sun
Cheng-Lung Sung 宋政隆
Sunnavy
Samuel Sutch
svatsan
svn
Andrew Sweger
sygi
Sebastian Sylvan
Gábor Szabó
Bálint Szilakszi
Marek Šuppa
</pre>
<a name="t11.20"></a> <h1 id="_language_contributors.pod6-T">T</h1>
<pre class="code"> TOGoS
Arvindh Rajesh Tamilmani
Audrey Tang 唐鳳
Bestian Tang 唐宗浩
Adrian Taylor
Jesse Taylor
Philip Taylor
Kevin Tew
the_dormant
Marcus Thiesen
Adam Thomason
Richard Tibbetts
Carey Tilden
Marcel Timmerman
Leon Timmermans
tkob
John Tobey
Frank Tobin
Bennett Todd
Graham Todd
Leopold Tötsch
Daniel Toma
Nathan Torkington
Timothy Totten
Itsuki Toyota
John J. Trammell
Matt S. Trout
Nat Tuck
Adam Turoff
Ben Tyler
</pre>
<a name="t11.21"></a> <h1 id="_language_contributors.pod6-U">U</h1>
<pre class="code"> ujwal
Bernd Ulmann
Reini Urban
parrot user
uzair
</pre>
<a name="t11.22"></a> <h1 id="_language_contributors.pod6-V">V</h1>
<pre class="code"> VZ
Ilmari Vacklin
vamped
Wim Vanderbauwhede
vendethiel
David Vergin
Ted Vessenes
Sam Vilain
Cédric Vincent
Jesse Vincent
Jos Visser
John van Vlaanderen
vmax
Jeremy Voorhis
Martin Vorländer
Johan Vromans
Maxim Vuets
</pre>
<a name="t11.23"></a> <h1 id="_language_contributors.pod6-W">W</h1>
<pre class="code"> Juerd Waalboer
Mariano Wahlmann
Kevin Walker
Gloria Wall
Larry Wall
Lewis Wall
Michal J Wallace
John Paul Wallington
walter
Matthew Walton
Ting Wang
Xinyuan Wang
Andy Wardley
Bryan C. Warnock
wayland
Stephen Weeks
Zhen-Bang Wei
Nick Wellnhofer
Shu-Chun Weng
Danny Werner
Brian Wheeler
David E. Wheeler
Dave Whipp
Adrian White
Andrew Whitworth
Bart Wiegmans
Nathan Wiger
Brock Wilcox
Edwin Wiles
Bob Wilkinson
Chris 'BinGOs' Williams
Greg Williams
Josh Wilmes
Matthew Wilson
Ashley Winters
Brian Wisti
Dave Woldrich
Helmut Wollmersdorfer
Kevin J. Woolley
Jonathan Worthington
Kuang-Che Wu 吳光哲
</pre>
<a name="t11.24"></a> <h1 id="_language_contributors.pod6-X">X</h1>
<pre class="code"> xenu
Liang-Qi Xie 謝良奇
Xtreak
</pre>
<a name="t11.25"></a> <h1 id="_language_contributors.pod6-Y">Y</h1>
<pre class="code"> Gaal Yahas גל יחס
Thomas Yandell
Alvis Yardley
Thomas Yeh 葉志宏
Natan Yellin
yiyihu
Matt Youell
Tony Young
Shen Yu-Teh
</pre>
<a name="t11.26"></a> <h1 id="_language_contributors.pod6-Z">Z</h1>
<pre class="code"> Ilya Zakharevich
Ruslan Zakirov
Ahmad M. Zawawi
Michael A. D. Zedeler
zengargoyle
zeriod
Agent Zhang 章亦春
Jimmy Zhuo
Ziggy6
Rob Zinkov
Zoffix Znet
</pre>
</div>
<!-- /language/control.pod6 --><div class="pod-body"><a id="_language_control.pod6"></a><a name="t12"></a><h1 class="title">12 Control Flow</h1> <p class="subtitle">Statements used to control the flow of execution</p> <a name="t12.1"></a> <h1 id="_language_control.pod6-statements"><a name="53"></a>statements</h1>
<p>Perl 6 programs consists of one or more statements. Simple statements are separated by semicolons. The following program will say &quot;Hello&quot; and then say &quot;World&quot; on the next line.</p>
<pre class="code">say &quot;Hello&quot;;
say &quot;World&quot;;</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
&quot;Hello&quot;; say &quot;World&quot;;</pre>
<a name="t12.2"></a> <h1 id="_language_control.pod6-blocks"><a name="54"></a>blocks</h1>
<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 &quot;Hello&quot;; say &quot;World&quot; }</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; # OUTPUT: «1␤»
{ say 2; say 3 }; # OUTPUT: «2␤3␤»
say 4; # OUTPUT: «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.pod6-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 &quot;We get here&quot;; { say &quot;then here.&quot; }; { say &quot;not here&quot;; 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 } # OUTPUT: «42␤»
{ 43.say } # OUTPUT: «43␤»
{ 42.say }; { 43.say } # OUTPUT: «42␤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">{ &quot;Without semicolons line-wrapping can be a bit treacherous.&quot;.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="t12.3"></a> <h1 id="_language_control.pod6-do"><a name="55"></a>do</h1>
<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 &quot;Heads I win, tails I die.&quot;; Bool.pick } or die; say &quot;I win.&quot;;
</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 &quot;(..1 ..2 ..3)&quot; not &quot;(..1 ...2 ....3)&quot;
my $f = &quot;.&quot;; say do { $f ~= &quot;.&quot; } 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 } ; # OUTPUT: «(3, 2)␤»
3, (if 1 { 2 }) ; # OUTPUT: «(3, 2)␤»
</pre>
<pre class="code">3, if 1 { 2 } ; # Syntax error
</pre>
<p>...which brings us to <span class="code">if</span>.</p>
<a name="t12.4"></a> <h1 id="_language_control.pod6-if"><a name="56"></a>if</h1>
<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 { &quot;1 is true&quot;.say } ; # says &quot;1 is true&quot;
</pre>
<pre class="code">if 1 &quot;1 is true&quot;.say ; # syntax error, missing block
</pre>
<pre class="code">if 0 { &quot;0 is true&quot;.say } ; # does not say anything, because 0 is false
</pre>
<pre class="code">if 42.say and 0 { 43.say }; # says &quot;42&quot; but does not say &quot;43&quot;
</pre>
<p>There is also a form of <span class="code">if</span> called a &quot;statement modifier&quot; 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 &quot;42&quot; but does not say &quot;43&quot;
43.say if 42.say and 1; # says &quot;42&quot; and then says &quot;43&quot;
say &quot;It is easier to read code when 'if's are kept on left of screen&quot;
if True; # says the above, because it is true
{ 43.say } if True; # says &quot;43&quot; 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.pod6">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 &quot;(1 3 0)&quot;
my $c = 0; say (1, (if 1 { $c += 42; 2; }), 3, $c); # says &quot;(1 2 3 42)&quot;
say (1, (if 1 { 2, 2 }), 3); # does not slip, says &quot;(1 (2 2) 3)&quot;</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 &quot;(1 42 2)&quot;
say (1, (42 if False), 2); # says &quot;(1 2)&quot;
say (1, 42 if False , 2); # says &quot;(1 42)&quot; because &quot;if False, 2&quot; 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 &quot;1&quot;
$_ = 1; if 42 -&gt; $_ { $_.say } ; # says &quot;42&quot;
$_ = 1; if 42 -&gt; $a { $_.say; $a.say } ; # says &quot;1&quot; then says &quot;42&quot;
$_ = 1; if 42 { $_.say; $^a.say } ; # says &quot;1&quot; then says &quot;42&quot;</pre>
<a name="t12.4.1"></a> <h2 id="_language_control.pod6-else/elsif"><a name="57"></a>else/elsif</h2>
<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 &quot;no&quot; } else { say &quot;yes&quot; } ; # says &quot;yes&quot;
if 0 { say &quot;no&quot; } else{ say &quot;yes&quot; } ; # says &quot;yes&quot;, space is not 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 &quot;no&quot; }; else { say &quot;yes&quot; } ; # syntax error
</pre>
<pre class="code">if 0 { say &quot;no&quot; }
else { say &quot;yes&quot; } ; # says &quot;yes&quot;
</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 &quot;no&quot; } elsif False { say &quot;NO&quot; } else { say &quot;yes&quot; } # says &quot;yes&quot;
if 0 { say &quot;no&quot; } elsif True { say &quot;YES&quot; } else { say &quot;yes&quot; } # says &quot;YES&quot;
if 0 { say &quot;no&quot; } elsif False { say &quot;NO&quot; } # does not say anything
sub right { &quot;Right!&quot;.say; True }
sub wrong { &quot;Wrong!&quot;.say; False }
if wrong() { say &quot;no&quot; } elsif right() { say &quot;yes&quot; } else { say &quot;maybe&quot; }
# The above says &quot;Wrong!&quot; then says &quot;Right!&quot; then says &quot;yes&quot;</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 &quot;how?&quot; } ; # syntax error
if 0 { say 0 } elsif 1 { say 1 }; else { say &quot;how?&quot; } ; # syntax error
if 0 { say 0 } elsif 1 { say 1 } else { say &quot;how?&quot; } ; # says &quot;1&quot;
</pre>
<pre class="code">if 0 { say 0 } elsif 1 { say 1 }
else { say &quot;how?&quot; } ; # says &quot;1&quot;
if 0 { say 0 }
elsif 1 { say 1 } else { say &quot;how?&quot; } ; # says &quot;1&quot;
if 0 { say &quot;no&quot; }
elsif False { say &quot;NO&quot; }
else { say &quot;yes&quot; } ; # says &quot;yes&quot;</pre>
<p>The whole thing either <a href="#_type_Slip.pod6">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; &quot;two&quot;; } elsif False { $d += 43; 2; }),
3, $d); # says &quot;(1 3 0)&quot;
my $c = 0; say (1,
(if 0 { $c += 42; &quot;two&quot;; } else { $c += 43; 2; }),
3, $c); # says &quot;(1 2 3 43)&quot;</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 -&gt; $a { &quot;$_ $a&quot;.say } ; # says &quot;1 0&quot;
$_ = 1; if False { } else -&gt; $a { &quot;$_ $a&quot;.say } ; # says &quot;1 False&quot;
if False { } elsif 0 { } else -&gt; $a { $a.say } ; # says &quot;0&quot;</pre>
<a name="t12.4.2"></a> <h2 id="_language_control.pod6-unless"><a name="58"></a>unless</h2>
<p>When you get sick of typing &quot;if not (X)&quot; 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="#11-if">#if</a>:</p>
<pre class="code">unless 1 { &quot;1 is false&quot;.say } ; # does not say anything, since 1 is true
</pre>
<pre class="code">unless 1 &quot;1 is false&quot;.say ; # syntax error, missing block
</pre>
<pre class="code">unless 0 { &quot;0 is false&quot;.say } ; # says &quot;0 is false&quot;
</pre>
<pre class="code">unless 42.say and 1 { 43.say } ; # says &quot;42&quot; but does not say &quot;43&quot;
43.say unless 42.say and 0; # says &quot;42&quot; and then says &quot;43&quot;
43.say unless 42.say and 1; # says &quot;42&quot; but does not say &quot;43&quot;
$_ = 1; unless 0 { $_.say } ; # says &quot;1&quot;
$_ = 1; unless 0 -&gt; $_ { $_.say } ; # says &quot;0&quot;
$_ = 1; unless False -&gt; $a { $a.say } ; # says &quot;False&quot;
my $c = 0; say (1, (unless 0 { $c += 42; 2; }), 3, $c); # says &quot;(1 2 3 42)&quot;
my $d = 0; say (1, (unless 1 { $d += 42; 2; }), 3, $d); # says &quot;(1 3 0)&quot;</pre>
<a name="t12.4.3"></a> <h2 id="_language_control.pod6-with,_orwith,_without"><a name="59"></a>with, orwith, without</h2>
<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 &quot;abc&quot;.index(&quot;a&quot;) { .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 &quot;Found a at 0&quot;
my $s = &quot;abc&quot;;
with $s.index(&quot;a&quot;) { say &quot;Found a at $_&quot; }
orwith $s.index(&quot;b&quot;) { say &quot;Found b at $_&quot; }
orwith $s.index(&quot;c&quot;) { say &quot;Found c at $_&quot; }
else { say &quot;Didn't find a, b or c&quot; }</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 &quot;Yes&quot;
if 0 { say &quot;No&quot; } orwith Nil { say &quot;No&quot; } orwith 0 { say &quot;Yes&quot; };</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">my $answer = Any;
without $answer { warn &quot;Got: $_&quot; }</pre>
<p>There are also <span class="code">with</span> and <span class="code">without</span> statement modifiers:</p>
<pre class="code">my $answer = (Any, True).roll;
say 42 with $answer;
warn &quot;undefined answer&quot; without $answer;</pre>
<a name="t12.5"></a> <h1 id="_language_control.pod6-when"><a name="60"></a>when</h1>
<p>The <span class="code">when</span> block is similar to an <span class="code">if</span> block and either or both can be used in an outer block, they also both have a &quot;statement modifier&quot; form. But there is a difference in how following code in the same, outer block is handled: When the <span class="code">when</span> block is executed, control is passed to the enclosing block and following statements are ignored; but when the <span class="code">if</span> block is executed, following statements are executed. (Note there are other ways to modify the default behavior of each which are discussed in other sections.) The following examples should illustrate the <span class="code">if</span> or <span class="code">when</span> block's default behavior assuming no special exit or other side effect statements are included in the <span class="code">if</span> or <span class="code">when</span> blocks:</p>
<pre class="code">{
if X {...} # if X is true in boolean context, block is executed
# following statements are executed regardless
}
{
when X {...} # if X is true in boolean context, block is executed
# and control passes to the outer block
# following statements are NOT executed
}
</pre>
<p>Should the <span class="code">if</span> and <span class="code">when</span> blocks above appear at file scope, following statements would be executed in each case.</p>
<p>There is one other feature a <span class="code">when</span> has that <span class="code">if</span> doesn't: the <span class="code">when</span>'s boolean context test defaults to <span class="code">$_ ~~</span> while the <span class="code">if</span>'s does not. That has an effect on how one uses the X in the <span class="code">when</span> block without a value for <span class="code">$_</span> (it's <span class="code">Any</span> in that case and <span class="code">Any</span> smart matches on <span class="code">True</span>: <span class="code">Any ~~ True</span> yields <span class="code">True</span>). Consider the following:</p>
<pre class="code">{
my $a = 1;
my $b = True;
when $a { say 'a' }; # no output
when so $a { say 'a' } # a (in &quot;so $a&quot; 'so' coerces $a to Boolean context True
# which matches with Any)
when $b { say 'b' }; # no output (this statement won't be run)
}
</pre>
<p>Finally, <span class="code">when</span>'s statement modifier form does not effect execution of following statements either inside or outside of another block:</p>
<pre class="code">say &quot;foo&quot; when X; # if X is true statement is executed
# following statements are not affected
</pre>
<a name="t12.6"></a> <h1 id="_language_control.pod6-for"><a name="61"></a>for</h1>
<p>The <span class="code">for</span> loop iterates over a list, running the statements inside a <a href="#_type_Block.pod6">block</a> once on each iteration. If the block takes parameters, the elements of the list are provided as arguments.</p>
<pre class="code">my @foo = 1..3;
for @foo { $_.print } # prints each value contained in @foo
for @foo { .print } # same thing, because .print implies a $_ argument
for @foo { 42.print } # prints 42 as many times as @foo has elements</pre>
<p>Pointy block syntax or a <a href="#_language_variables.pod6-The_^_Twigil">placeholder</a> may be used to name the parameter, of course.</p>
<pre class="code">my @foo = 1..3;
for @foo -&gt; $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">my @foo = 1..3;
for @foo.kv -&gt; $idx, $val { say &quot;$idx: $val&quot; }
my %hash = &lt;a b c&gt; Z=&gt; 1,2,3;
for %hash.kv -&gt; $key, $val { say &quot;$key =&gt; $val&quot; }
for 1, 1.1, 2, 2.1 { say &quot;$^x &lt; $^y&quot; } # says &quot;1 &lt; 1.1&quot; then says &quot;2 &lt; 2.1&quot;</pre>
<p>Parameters of a pointy block can have default values, allowing to handle lists with missing elements.</p>
<pre class="code">my @list = 1,2,3,4;
for @list -&gt; $a, $b = 'N/A', $c = 'N/A' {
say &quot;$a $b $c&quot;
}
# OUTPUT: «1 2 3␤4 N/A N/A␤»</pre>
<p>If the postfix form of <span class="code">for</span> is used a block is not required and the topic is set for the statement list.</p>
<pre class="code">say „I $_ butterflies!“ for &lt;♥ ♥ ♥&gt;;
# OUTPUT«I ♥ butterflies!␤I ♥ butterflies!␤I ♥ butterflies!␤»</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 -&gt; $line { .say }
</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;-&gt;</span> instead of <span class="code">-&gt;</span>. If you need to make <span class="code">$_</span> read-write in a for loop, do so explicitly.</p>
<pre class="code">my @foo = 1..3;
for @foo &lt;-&gt; $_ { $_++ }</pre>
<p>A for loop can produce 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 &quot;(2 4 6)&quot;
my @a = do for 1, 2, 3 { $_ * 2 }; @a.say; # says &quot;[2 4 6]&quot;
my @b = (for 1, 2, 3 { $_ * 2 }); @a.say; # same thing</pre>
<a name="t12.7"></a> <h1 id="_language_control.pod6-gather/take"><a name="62"></a>gather/take</h1>
<p><a id="i63" name="lazy list gather"></a><span class="indexed"></span><a id="i64" name="lazy list take"></a><span class="indexed"></span></p>
<p><span class="code">gather</span> is a statement or block prefix that returns a <a href="#_type_Seq.pod6">sequence</a> of values. The values come from calls to <a href="#_type_Mu.pod6-routine_take">take</a> 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; # OUTPUT: «1, 5, 42␤»</pre>
<p><span class="code">gather/take</span> can generate values lazily, depending on context. If you want to force lazy evaluation use the <a href="#_type_Iterable.pod6-method_lazy">lazy</a> subroutine or method. Binding to a scalar or sigilless container will also force laziness.</p>
<p>For example</p>
<pre class="code">my @vals = lazy gather {
take 1;
say &quot;Produced a value&quot;;
take 2;
}
say @vals[0];
say 'between consumption of two values';
say @vals[1];
# OUTPUT:
# 1
# between consumption of two values
# Produced a value
# 2</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 =&gt; sub { take $_ for @elems },
backward =&gt; sub { take $_ for @elems.reverse },
random =&gt; sub { take $_ for @elems.pick(*) },
);
return gather %direction{$direction}();
}
say weird(&lt;a b c&gt;, :direction&lt;backward&gt; ); # OUTPUT: «(c b a)␤»</pre>
<p>If values need to be mutable on the caller side, use <a href="#_type_Mu.pod6-routine_take-rw">take-rw</a>.</p>
<a name="t12.8"></a> <h1 id="_language_control.pod6-given"><a name="65"></a>given <a name="66"></a></h1>
<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">my $var = (Any, 21, any &lt;answer lie&gt;).pick;
given $var {
when 21 { say $_ * 2 }
when 'lie' { .say }
default { say 'default' }
}</pre>
<p>The <span class="code">given</span> statement is often used alone:</p>
<pre class="code">given 42 { .say; .Numeric; }</pre>
<p>This is a lot more understandable than:</p>
<pre class="code">{ .say; .Numeric; }(42)</pre>
<a name="t12.8.1"></a> <h2 id="_language_control.pod6-default_and_when"><a name="67"></a>default and when</h2>
<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 {
&quot;This says&quot;.say;
$_ == 42 and ( default { &quot;This says, too&quot;.say; 43; } );
&quot;This never says&quot;.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, &quot;foo&quot;, 44, &quot;bar&quot; {
when Int { .say }
when /:i ^Bar/ { .say }
default { say &quot;Not an Int or a Bar&quot; }
}
# OUTPUT: «42␤43␤Not an Int or a Bar␤44␤Bar␤»</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">&quot;Int&quot;</span> not <span class="code">42</span>.</p>
<pre class="code">given 42 {
when Int { say &quot;Int&quot; }
when 42 { say 42 }
default { say &quot;huh?&quot; }
}
# OUTPUT: «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 &quot;switch&quot; just so long as you do not open a new block:</p>
<pre class="code">given 42 {
when Int {
when 42 { say 42 }
say &quot;Int&quot;
}
default { say &quot;huh?&quot; }
}
# OUTPUT: «42»</pre>
<p><span class="code">when</span> statements can smart match against <a href="#_language_syntax.pod6-Signature_literals">Signatures</a>.</p>
<a name="t12.8.2"></a> <h2 id="_language_control.pod6-proceed"><a name="68"></a>proceed</h2>
<a name="t12.8.3"></a> <h2 id="_language_control.pod6-succeed"><a name="69"></a>succeed</h2>
<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">given * {
default {
proceed;
&quot;This never says&quot;.say
}
}
&quot;This says&quot;.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 &quot;Int&quot;; proceed }
when 42 { say 42 }
when 40..* { say &quot;greater than 40&quot; }
default { say &quot;huh?&quot; }
}
# OUTPUT: «Int␤»
# OUTPUT: «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 <span class="code">proceed</span> 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 { &quot;Int&quot;.say; proceed }
when 43 { 43.say }
when 42 { 42.say }
default { &quot;got change for an existential answer?&quot;.say }
}
# OUTPUT: «Int␤»
# OUTPUT: «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 short-circuits 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 &quot;Int&quot;;
succeed &quot;Found&quot;;
say &quot;never this!&quot;;
}
when 42 { say 42 }
default { say &quot;dunno?&quot; }
}
# OUTPUT: «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 &quot;This says&quot; } when Int;
&quot;This says too&quot;.say;
when * &gt; 41 {
{ &quot;And this says&quot;.say; proceed } when * &gt; 41;
&quot;This never says&quot;.say;
}
&quot;This also says&quot;.say;
}</pre>
<a name="t12.8.4"></a> <h2 id="_language_control.pod6-given_as_a_statement"><a name="70"></a>given as a statement</h2>
<p><span class="code">given</span> can follow a statement to set the topic in the statement it follows.</p>
<pre class="code">.say given &quot;foo&quot;;
# OUTPUT: «foo␤»
printf &quot;%s %02i.%02i.%i&quot;,
&lt;Mo Tu We Th Fr Sa Su&gt;[.day-of-week - 1],
.day,
.month,
.year
given DateTime.now;
# OUTPUT: «Sa 03.06.2016»</pre>
<a name="t12.9"></a> <h1 id="_language_control.pod6-loop"><a name="71"></a>loop</h1>
<p>The <span class="code">loop</span> statement takes three statements in parentheses separated by <span class="code">;</span> that take the role of initializer, conditional and incrementer. The initializer is executed once and any variable declaration will spill into the surrounding block. The conditional is executed once per iteration and coerced to <span class="code">Bool</span>, if <span class="code">False</span> the loop is stopped. The incrementer is executed once per iteration.</p>
<pre class="code">loop (my $i = 0; $i &lt; 10; $i++) {
say $i;
}</pre>
<p>The infinite loop does not require parentheses.</p>
<pre class="code">loop { say 'forever' }
</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; # OUTPUT: «(2 4 6)␤»
my @a = (loop ( my $j = 0; $j++ &lt; 3;) { $j * 2 }); @a.say; # OUTPUT: «[2 4 6]␤»
my @b = do loop ( my $k = 0; $k++ &lt; 3;) { $k * 2 }; @b.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;) { &quot;heads&quot;.say })
}</pre>
<a name="t12.10"></a> <h1 id="_language_control.pod6-while,_until"><a name="72"></a>while, until</h1>
<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 &quot;\n&quot;;
# OUTPUT: «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 &gt; 3 {
print $x++;
}
print &quot;\n&quot;;
# OUTPUT: «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">my $x = 42;
$x-- while $x &gt; 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="t12.11"></a> <h1 id="_language_control.pod6-repeat/while,_repeat/until"><a name="73"></a>repeat/while, repeat/until</h1>
<p>Executes the block <i>at least once</i> and, if the condition allows, repeats that execution. This differs from <span class="code">while</span>/<span class="code">until</span> in that the condition is evaluated at the end of the loop, even if it appears at the front.</p>
<pre class="code">my $x = -42;
repeat {
$x++;
} while $x &lt; 5;
$x.say; # OUTPUT: «5␤»
repeat {
$x++;
} while $x &lt; 5;
$x.say; # OUTPUT: «6␤»
repeat while $x &lt; 10 {
$x++;
}
$x.say; # OUTPUT: «10␤»
repeat while $x &lt; 10 {
$x++;
}
$x.say; # OUTPUT: «11␤»
repeat {
$x++;
} until $x &gt;= 15;
$x.say; # OUTPUT: «15␤»
repeat {
$x++;
} until $x &gt;= 15;
$x.say; # OUTPUT: «16␤»
repeat until $x &gt;= 20 {
$x++;
}
$x.say; # OUTPUT: «20␤»
repeat until $x &gt;= 20 {
$x++;
}
$x.say; # OUTPUT: «21␤»</pre>
<p>All these forms may produce a return value the same way <span class="code">loop</span> does.</p>
<a name="t12.12"></a> <h1 id="_language_control.pod6-return"><a name="74"></a>return</h1>
<p>The sub <span class="code">return</span> will stop execution of a subroutine or method, run all relevant <a href="#_language_phasers.pod6-Block_Phasers">phasers</a> and provide the given return value to the caller. The default return value is <span class="code">Nil</span>. If a return <a href="#_type_Signature.pod6-Constraining_Return_Types">type constraint</a> is provided it will be checked unless the return value is <span class="code">Nil</span>. If the type check fails the exception <a href="#_type_X::TypeCheck::Return.pod6">X::TypeCheck::Return</a> is thrown. If it passes a control exception is raised and can be caught with <a href="#_language_phasers.pod6-CONTROL">CONTROL</a>.</p>
<p>Any <span class="code">return</span> in a block is tied to the first <span class="code">Routine</span> in the outer lexical scope of that block, no matter how deeply nested. Please note that a <span class="code">return</span> in the root of a package will fail at runtime. A <span class="code">return</span> in a block that is evaluated lazily (e.g. inside <span class="code">map</span>) may find the outer lexical routine gone by the time the block is executed. In almost any case <span class="code">last</span> is the better alternative.</p>
TODO add link to section in /language/function that shows how return values are produces/handled
<a name="t12.13"></a> <h1 id="_language_control.pod6-return-rw"><a name="75"></a>return-rw</h1>
<p>The sub <span class="code">return</span> will return values, not containers. Those are immutable and will lead to runtime errors when attempted to be mutated.</p>
<pre class="code">sub s(){ my $a = 41; return $a };
say ++s();
CATCH { default { say .^name, ': ', .Str } };
# OUTPUT: «X::Multi::NoMatch.new(dispatcher …</pre>
<p>To return a mutable container, use <span class="code">return-rw</span>.</p>
<pre class="code">sub s(){ my $a = 41; return-rw $a };
say ++s();
# OUTPUT: «42␤»</pre>
<p>The same rules as for <span class="code">return</span> regarding phasers and control exceptions apply.</p>
<a name="t12.14"></a> <h1 id="_language_control.pod6-fail"><a name="76"></a>fail</h1>
<p>Leaves the current routine and returns the provided <a href="#_type_Exception.pod6">Exception</a> or <span class="code">Str</span> wrapped inside a <a href="#_type_Failure.pod6">Failure</a>, after all relevant <a href="#_language_phasers.pod6-Block_Phasers">phasers</a> are executed. If the caller activated fatal exceptions via the pragma <span class="code">use fatal;</span>, the exception is thrown instead of being returned as a <span class="code">Failure</span>.</p>
<pre class="code">sub f { fail &quot;WELP!&quot; };
say f;
CATCH { default { say .^name, ': ', .Str } }
# OUTPUT: «X::AdHoc: WELP!␤»</pre>
<a name="t12.15"></a> <h1 id="_language_control.pod6-once"><a name="77"></a>once</h1>
<p>A block prefix with <span class="code">once</span> will be executed exactly once, even if placed inside a loop or a recursive routine.</p>
<pre class="code">my $guard = 3;
loop {
last if $guard-- &lt;= 0;
once { put 'once' };
print 'many'
} # OUTPUT: «once␤manymanymany»</pre>
<p>This works per &quot;clone&quot; of the containing code object, so:</p>
<pre class="code">({ once 42.say } xx 3).map: {$_(), $_()}; # says 42 thrice</pre>
<p>Note that this is <b>not</b> a thread-safe construct when the same clone of the same block is run by multiple threads. Also remember that methods only have one clone per class, not per object.</p>
<a name="t12.16"></a> <h1 id="_language_control.pod6-quietly"><a name="78"></a>quietly</h1>
<p>A <span class="code">quietly</span> block will suppress warnings.</p>
<pre class="code">quietly { warn 'kaput!' };
warn 'still kaput!';
# OUTPUT: «still kaput! [...]␤»</pre>
<a name="t12.17"></a> <h1 id="_language_control.pod6-LABELs">LABELs</h1>
<p><span class="code">while</span>, <span class="code">until</span>, <span class="code">loop</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>. Nested loops are supported, for instance:</p>
<pre class="code">OUTAHERE: while True {
for 1,2,3 -&gt; $n {
last OUTAHERE if $n == 2;
}
}</pre>
<p>Labels can be used also within nested loops to name each loop, for instance:</p>
<pre class="code">OUTAHERE:
loop ( my $i = 1; True; $i++ ) {
OUTFOR:
for 1,2,3 -&gt; $n {
# exits the for loop before its natural end
last OUTFOR if $n == 2;
}
# exits the infinite loop
last OUTAHERE if $i &gt;= 2;
}
</pre>
<a name="t12.18"></a> <h1 id="_language_control.pod6-next"><a name="79"></a>next</h1>
<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 -&gt; $x {
next if $x == 3;
print $x;
}
</pre>
<p>prints &quot;1245&quot;.</p>
<a name="t12.19"></a> <h1 id="_language_control.pod6-last"><a name="80"></a>last</h1>
<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 -&gt; $x {
last if $x == 3;
print $x;
}
</pre>
<p>prints &quot;12&quot;.</p>
<a name="t12.20"></a> <h1 id="_language_control.pod6-redo"><a name="81"></a>redo</h1>
<p>The <span class="code">redo</span> command restarts the loop block without evaluating the conditional again.</p>
<pre class="code">loop {
my $x = prompt(&quot;Enter a number&quot;);
redo unless $x ~~ /\d+/;
last;
}
</pre>
</div>
<!-- /language/enumeration.pod6 --><div class="pod-body"><a id="_language_enumeration.pod6"></a><a name="t13"></a><h1 class="title">13 Enumeration</h1> <p class="subtitle">Using the enum type</p> <a name="t13.1"></a> <h1 id="_language_enumeration.pod6-An_example_using_the_enum_type">An example using the enum type</h1>
<p>In Perl 6 the <span class="code">enum</span> type is much more complex than in some other languages, and the details are found in its type description here: <a href="#_language_typesystem.pod6-enum">enum</a>.</p>
<p>This short document will give a simple example of its use similar to use in C-like languages.</p>
<p>Say we have a program that needs to write to various directories so we want a function that, given a directory name, tests it for (1) its existence and (2) whether it can be written to by the user of the program. The results of the test will determine what actions the program takes next.</p>
<pre class="code"># the directory will have one of these three statuses from the user's perspective:
enum DirStat &lt;CanWrite NoDir NoWrite&gt;;
sub check-dir-status($dir --&gt; DirStat) {
if $dir.IO.d {
# dir exists, can the program user write to it?
my $f = &quot;$dir/.tmp&quot;;
spurt $f, &quot;some text&quot;;
CATCH {
# unable to write for some reason
return NoWrite;
}
# if we get here we must have successfully written to the dir
unlink $f;
return CanWrite;
}
# if we get here the dir must not exist
return NoDir;
}
# test each of three directories by a non-root user
my $dirs =
'/tmp', # normally writable by any user
'/', # writable only by root
'~/tmp'; # a non-existent dir in the user's home dir
for $dirs -&gt; $dir {
my $stat = check-dir-status $dir;
say &quot;status of dir '$dir': $stat&quot;;
if $stat ~~ CanWrite {
say &quot; user can write to dir: $dir&quot;;
}
}
# output
# status of dir '/tmp': CanWrite
# user can write to dir: /tmp
# status of dir '/': NoWrite
# status of dir '~/tmp': NoDir
</pre>
</div>
<!-- /language/exceptions.pod6 --><div class="pod-body"><a id="_language_exceptions.pod6"></a><a name="t14"></a><h1 class="title">14 Exceptions</h1> <p class="subtitle">Using exceptions in Perl 6</p> <p>Exceptions in Perl 6 are objects that hold information about errors. An error can be, for example, the unexpected receiving of data or a network connection no longer available, or a missing file. The information that an exception objects store is, for instance, a human-readable message about the error condition, the backtrace of the raising of the error, and so on.</p>
<p>All built-in exceptions inherit from <a href="#_type_Exception.pod6">Exception</a>, which provides some basic behavior, including the storage of a backtrace and an interface for the backtrace printer.</p>
<a name="t14.1"></a> <h1 id="_language_exceptions.pod6-Ad_hoc_exceptions">Ad hoc exceptions</h1>
<p>Ad hoc exceptions can be used by calling <a href="#_routine_die.pod6">die</a> with a description of the error:</p>
<pre class="code">die &quot;oops, something went wrong&quot;;
# RESULT: «oops, something went wrong in block &lt;unit&gt; at my-script.p6:1␤»</pre>
<p>It is worth noting that <span class="code">die</span> prints the error message to the standard error <span class="code">$*ERR</span>.</p>
<a name="t14.2"></a> <h1 id="_language_exceptions.pod6-Typed_exceptions">Typed exceptions</h1>
<p>Typed exceptions provide more information about the error stored within an exception object.</p>
<p>For example, if while executing <span class="code">.zombie copy</span> on an object, a needed path <span class="code">foo/bar</span> becomes unavailable, then an <a href="#_type_X::IO::DoesNotExist.pod6">X::IO::DoesNotExist</a> exception can be raised:</p>
<pre class="code">die X::IO::DoesNotExist.new(:path(&quot;foo/bar&quot;), :trying(&quot;zombie copy&quot;))
# RESULT: «Failed to find 'foo/bar' while trying to do '.zombie copy'
# in block &lt;unit&gt; at my-script.p6:1»</pre>
<p>Note how the object has provided the backtrace with information about what went wrong. A user of the code can now more easily find and correct the problem.</p>
<a name="t14.3"></a> <h1 id="_language_exceptions.pod6-Catching_exceptions">Catching exceptions</h1>
<p>It's possible to handle exceptional circumstances by supplying a <span class="code">CATCH</span> block:</p>
<pre class="code">die X::IO::DoesNotExist.new(:path(&quot;foo/bar&quot;), :trying(&quot;zombie copy&quot;));
CATCH {
when X::IO { $*ERR.say: &quot;some kind of IO exception was caught!&quot; }
}
# RESULT: «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 sent to <i>stderr</i> and displayed.</p>
<p>A <a id="i82" name="CATCH"></a><span class="indexed"><span class="code">CATCH</span></span> block uses smart matching similar to how <span class="code">given/when</span> smart matches on options, thus it's possible to catch and handle various categories of exceptions 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 .^name, do given .backtrace[0] { .file, .line, .subname }
}
}</pre>
<p>Note that the match target is a role. To allow user defined exceptions to match in the same manner, they must implement the given role. Just existing in the same namespace will look alike but won't match in a <span class="code">CATCH</span> block.</p>
<a name="t14.3.1"></a> <h2 id="_language_exceptions.pod6-Exception_handlers_and_enclosing_blocks.">Exception handlers and enclosing blocks.</h2>
<p>After a CATCH has handled the exception, the block enclosing the CATCH is exited.</p>
<p>In other words, even when the exception is handled successfully, the <i>rest of the code</i> in the enclosing block will never be executed.</p>
<pre class="code">die &quot;something went wrong ...&quot;;
CATCH {
# will definitely catch all the exception
default { .Str.say; }
}
say &quot;This won't be said.&quot;; # but this line will be never reached since
# the enclosing block will be exited immediately
# OUTPUT: «something went wrong ...␤»</pre>
<p>Compare with this:</p>
<pre class="code">CATCH {
CATCH {
default { .Str.say; }
}
die &quot;something went wrong ...&quot;;
}
say &quot;Hi! I am at the outer block!&quot;; # OUTPUT: «Hi! I am at the outer block!␤»</pre>
<p>See &quot;Resuming of Exceptions&quot;, for how to return control back to where the exception originated.</p>
<a name="t14.4"></a> <h1 id="_language_exceptions.pod6-try"><a name="83"></a><span class="code">try</span></h1>
<p>To contain an exception, use a <span class="code">try</span> block. Any exception that is thrown in such a block will be caught by the implicit <span class="code">CATCH</span> block or a <span class="code">CATCH</span> block provided by the user. In the latter case, any unhandled exception will be rethrown.</p>
<pre class="code">class E is Exception { method message() { &quot;Just stop already!&quot; } }
try {
E.throw.new; # this will be local
say &quot;This won't be said.&quot;;
}
say &quot;I'm alive!&quot;;
try {
CATCH {
when X::AdHoc { .Str.say; .resume }
}
die &quot;No, I expect you to DIE Mr. Bond!&quot;;
say &quot;I'm immortal.&quot;;
E.new.throw;
say &quot;No, you don't!&quot;;
}</pre>
<p>Output:</p>
<pre class="code">I'm alive!
No, I expect you to DIE Mr. Bond!
I'm immortal.
Just stop already!
in block &lt;unit&gt; at exception.p6 line 21
</pre>
<p>A <span class="code">try</span>-block is a normal block and as such treats its last statement as the return value of itself. We can therefore use it as a RHS.</p>
<pre class="code">say try { +&quot;99999&quot; } // &quot;oh no&quot;;
say try { +&quot;hello&quot; } // &quot;oh no&quot;;
# OUTPUT: «99999␤oh no␤»
</pre>
<p>Try blocks support <span class="code">else</span> blocks indirectly by returning the return value of the expression or <a href="#_type_Nil.pod6">Nil</a> if an exception was thrown.</p>
<pre class="code">with try +&quot;♥&quot; {
say &quot;this is my number: $_&quot;
} else {
say &quot;not my number!&quot;
}
# OUTPUT: «not my number!␤»</pre>
<p><span class="code">try</span> can also be used with a statement instead of a block:</p>
<pre class="code">say try &quot;some-filename.txt&quot;.IO.slurp // &quot;sane default&quot;;
# OUTPUT: «sane default␤»
</pre>
<a name="t14.5"></a> <h1 id="_language_exceptions.pod6-Throwing_exceptions">Throwing exceptions</h1>
<p>Exceptions can be thrown explicitly with the <span class="code">.throw</span> method of 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&gt;).throw;
&quot;OHAI&quot;.say;
CATCH {
when X::AdHoc { .resume }
}
}
&quot;OBAI&quot;.say;
# OUTPUT: «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&gt;).throw;
&quot;OHAI&quot;.say;
CATCH { }
}
&quot;OBAI&quot;.say;
# RESULT: «foo
# in block &lt;unit&gt; at my-script.p6:1»</pre>
<p>This next example doesn't resume from the point of the exception. Instead, it continues after the enclosing block, since the exception is caught, and then control continues after the <span class="code">CATCH</span> block.</p>
<pre class="code">{
X::AdHoc.new(:payload&lt;foo&gt;).throw;
&quot;OHAI&quot;.say;
CATCH {
when X::AdHoc { }
}
}
&quot;OBAI&quot;.say;
# OUTPUT: «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="t14.6"></a> <h1 id="_language_exceptions.pod6-Resuming_of_Exceptions">Resuming of Exceptions</h1>
<p>Exceptions interrupt control flow and divert it away from the statement following the statement that threw it. Any exception handled by the user can be resumed and control flow will continue with the statement following the statement that threw the exception. To do so, call the method <span class="code">.resume</span> on the exception object.</p>
<pre class="code">CATCH { when X::AdHoc { .resume } } # this is step 2
die &quot;We leave control after this.&quot;; # this is step 1
say &quot;We have continued with control flow.&quot;; # this is step 3</pre>
<a name="t14.7"></a> <h1 id="_language_exceptions.pod6-Uncaught_Exceptions">Uncaught Exceptions</h1>
<p>If an exception is thrown and not caught, it causes the program to exit with a non-zero status code, and typically prints a message to the standard error stream of the program. This message is obtained by calling the <span class="code">gist</span> method on the exception object. You can use this to suppress the default behavior of printing a backtrace along with the message:</p>
<pre class="code">class X::WithoutLineNumber is X::AdHoc {
multi method gist(X::WithoutLineNumber:D:) {
$.payload
}
}
die X::WithoutLineNumber.new(payload =&gt; &quot;message&quot;)
# prints &quot;message\n&quot; to $*ERR and exits, no backtrace</pre>
<a name="t14.8"></a> <h1 id="_language_exceptions.pod6-Control_Exceptions">Control Exceptions</h1>
<p>Control exceptions are thrown by certain <a href="#_language_phasers.pod6-CONTROL">keywords</a> and are handled either automatically or by the appropriate <a href="#_language_phasers.pod6-Loop_Phasers">phaser</a>. Any unhandled control exception is converted to a normal exception.</p>
<pre class="code">{ return; CATCH { default { say .^name, ': ',.Str } } }
# OUTPUT: «X::ControlFlow::Return: Attempt to return outside of any Routine␤»
# was CX::Return</pre>
</div>
<!-- /language/experimental.pod6 --><div class="pod-body"><a id="_language_experimental.pod6"></a><a name="t15"></a><h1 class="title">15 Experimental Features</h1> <p class="subtitle">New features for brave users</p> <p>During Perl 6 development, new features are often made available for users to experimental with before their design is completed. Eventually these features may be made part of the Perl 6 specification. To use these features, one uses the <span class="code">experimental</span> pragma in program source code, for example, like this:</p>
<pre class="code">use experimental :macros;</pre>
<p>Following is a list of current experimental features and a short description of each feature's purpose or a link to more details about its use. (Note: Features marked &quot;[TBD]&quot; are to be defined later.)</p>
The following should be a table but formatting in tables is
not yet rendered properly.
<ul><li><p><a id="i84" name="cache"></a><span class="indexed"><b>cache</b></span> [TBD]</p>
</li></ul> <ul><li><p><a id="i85" name="macros"></a><span class="indexed"><b>macros</b></span> [TBD]</p>
</li></ul> <ul><li><p><a id="i86" name="pack"></a><span class="indexed"><b>pack</b></span> [TBD]</p>
</li></ul> <a name="t15.1"></a> <h1 id="_language_experimental.pod6-Collation">Collation</h1>
<p>Is available in release 2017.02. To use:</p>
<pre class="code">use experimental :collation;</pre>
<p>Allows the use of the <a id="i87" name="unicmp Routine"></a><span class="indexed"><b>unicmp</b></span> and <a id="i88" name="coll method"></a><span class="indexed"><b>coll</b></span> operators. Also allows the use of the <a id="i89" name="collate"></a><span class="indexed"><b>collate</b></span> method. unicmp and coll are like cmp, except it implements the Unicode Collation Algorithm.</p>
<p><b>coll</b> and the <b>collate</b> method are affected by the <a id="i90" name="$*COLLATION"></a><span class="indexed"><b>$*COLLATION</b></span> variable, while <b>unicmp</b> is not. Unlike the cmp operator which sorts according to codepoint, <b>unicmp</b> and <b>coll</b> sort according to how most users would expect.</p>
<pre class="code">use experimental :collation;
say 'a' unicmp 'Z'; # Less
say 'a' cmp 'Z'; # More</pre>
<p><b>coll</b> and the <b>collate</b> method are both configurable by setting the <b>$*COLLATION</b> variable.</p>
<a name="t15.1.1"></a> <h2 id="_language_experimental.pod6-collate_(method)">collate (method)</h2>
<p>You can use the collate method similar to how one would use the <b>sort</b> method.</p>
<pre class="code">use experimental :collation;
say ('a', 'Z').sort; # (Z a)
say ('a', 'Z').collate; # (a Z)
say &lt;ä a o ö&gt;.collate; # (a ä o ö)
my %hash = 'aa' =&gt; 'value', 'Za' =&gt; 'second';
say %hash.collate; # (aa =&gt; value Za =&gt; second);</pre>
<a name="t15.1.2"></a> <h2 id="_language_experimental.pod6-Collation_Levels">Collation Levels</h2>
<p>There are four collation levels which are all configurable.</p>
<p>While the Primary, Secondary and Tertiary mean different things for different scripts, for the Latin script used in English they mostly correspond with Primary being Alphabetic, Secondary being Diacritics and Tertiary being Case.</p>
<p>In the below example you can see how when we disable tertiary collation which in Latin script generally is for case, and also disable quaternary which breaks any ties by checking the codepoint values of the strings, we get <b>Same</b> back for <b>A</b> and <b>a</b>:</p>
<pre class="code">use experimental :collation;
$*COLLATION.set(:quaternary(False), :tertiary(False));
say 'a' coll 'A'; # Same</pre>
<p><b>Note the collation features, especially the $*COLLATION API could change at any time</b></p>
</div>
<!-- /language/faq.pod6 --><div class="pod-body"><a id="_language_faq.pod6"></a><a name="t16"></a><h1 class="title">16 FAQ</h1> <p class="subtitle">Frequently Asked Questions about Perl 6</p> <a name="t16.1"></a> <h1 id="_language_faq.pod6-General">General</h1>
<a name="t16.1.1"></a> <h2 id="_language_faq.pod6-What's_the_difference_between_Rakudo_and_Perl 6?">What's the difference between Rakudo and Perl 6?</h2>
<p>Properly speaking, <a href="http://rakudo.org/">Rakudo</a> is an implementation of Perl 6. It's currently the most developed, but there have been other implementations in the past and there will likely be others in the future. Perl 6 is the definition of the language. Often, Rakudo and Perl 6 will be used interchangeably.</p>
<a name="t16.1.2"></a> <h2 id="_language_faq.pod6-Has_Perl 6_been_released?">Has Perl 6 been released?</h2>
<p>Yes with the Rakudo 2015.12 implementation version on December 25th 2015.</p>
<a name="t16.1.3"></a> <h2 id="_language_faq.pod6-Is_there_a_Perl 6_version_6.0.0?">Is there a Perl 6 version 6.0.0?</h2>
<p>No. The first stable language specification version is v6.c (&quot;Christmas&quot;). Future versions of the spec may have point releases (e.g. v6.c.2) or major releases (e.g., v6.d).</p>
<p>Running <span class="code">perl6 -v</span> will display the language version your compiler implements:</p>
<pre class="code">$ perl6 -v
This is Rakudo version 2017.07 built on MoarVM version 2017.07
implementing Perl 6.c.
</pre>
<a name="t16.1.4"></a> <h2 id="_language_faq.pod6-When_is_v6.d_going_to_be_released?">When is v6.d going to be released?</h2>
<p>Hopefully within a few months. Details at <a href="https://github.com/perl6/6.d-prep">https://github.com/perl6/6.d-prep</a></p>
<p>You can already use some of the new features by using <span class="code">use v6.d.PREVIEW</span> <a href="https://docs.perl6.org/language/pragmas">pragma</a>. Also, many of the 6.d features were already implemented in 6.c compiler, due to the lack (at the time) of the infrastructure to support separate language versions. Thus, when 6.d is released, you may find you were already using many of the new features.</p>
<a name="t16.1.5"></a> <h2 id="_language_faq.pod6-As_a_Perl 6_user,_what_should_I_install?">As a Perl 6 user, what should I install? <a name="91"></a></h2>
<p>Mac users can use the latest Rakudo Star DMG binary installer at <a href="http://rakudo.org/downloads/star">http://rakudo.org/downloads/star</a></p>
<p>Windows users can use the Rakudo Star MSI binary installer. You will need Windows Git and Strawberry Perl 5 to use zef to install library modules.</p>
<p>Linux users probably want to download Rakudo Star and follow the compilation instructions at <a href="http://www.perl6.org/downloads/">http://www.perl6.org/downloads/</a>.</p>
<p>There should be Linux and Mac binaries available from vendors and third parties, although vendor versions may be outdated. Versions before Rakudo release of 2015.12 should be avoided.</p>
<p>There's an official Rakudo Star docker image at <a href="https://hub.docker.com/_/rakudo-star/">https://hub.docker.com/_/rakudo-star/</a></p>
<a name="t16.1.6"></a> <h2 id="_language_faq.pod6-As_an_advanced_user_I_want_to_track_Rakudo_development.">As an advanced user I want to track Rakudo development. <a name="92"></a></h2>
<p>An option is to clone <a href="https://github.com/rakudo/rakudo">the repository</a> and <a href="https://github.com/zoffixznet/r#table-of-contents">build from source</a>.</p>
<p>This will install work in progress which isn't necessarily fully functional. To install the last official monthly release check out the tag visible at <a href="https://raw.githubusercontent.com/rakudo/rakudo/master/VERSION">https://raw.githubusercontent.com/rakudo/rakudo/master/VERSION</a></p>
<p>Some users choose to use <a href="https://github.com/tadzik/rakudobrew">rakudobrew</a>, which allows installation of multiple versions of rakudo. Be sure to <a href="https://github.com/tadzik/rakudobrew#making-new-scripts-available">read its documentation</a></p>
<p>In either case you will probably need to also install zef and p6doc from the ecosystem.</p>
<a name="t16.1.7"></a> <h2 id="_language_faq.pod6-Where_can_I_find_good_documentation_on_Perl 6?">Where can I find good documentation on Perl 6?</h2>
<p>See <a href="https://docs.perl6.org/">the official documentation website</a> (especially its <a href="https://docs.perl6.org/language.html">&quot;Language&quot; section</a>) as well as the <a href="https://perl6.org/resources/">Resources page</a>.</p>
<p>There is a cheat sheet at <a href="https://github.com/perl6/mu/raw/master/docs/Perl6/Cheatsheet/cheatsheet.txt">https://github.com/perl6/mu/raw/master/docs/Perl6/Cheatsheet/cheatsheet.txt</a></p>
<p>Be mindful of publication dates when reading third-party articles. Anything published before December, 2015 likely describes pre-release version of Perl 6.</p>
<p>You can always <a href="https://webchat.freenode.net/?channels=#perl6">get help from a live human in our help chat</a> or <a href="https://www.google.com/search?q=site:irclog.perlgeek.de+inurl:perl6">search the chat logs</a>.</p>
<a name="t16.1.8"></a> <h2 id="_language_faq.pod6-What_is_the_Perl 6_specification?">What is the Perl 6 specification?</h2>
<p>The specification refers to the official test suite for Perl 6. It's called <a href="https://github.com/perl6/roast">roast</a> and is hosted on github. Any compiler that passes the tests is deemed to implement that version of the Perl 6 specification.</p>
<p>Roast's &quot;master&quot; branch corresponds to the latest development that isn't necessarily part of any specification yet. Other branches correspond to specific versions; for example, &quot;6.c-errata&quot;.</p>
<p>So 6.c-errata is a released language version we don't change other than to fix errors in tests (the &quot;errata&quot;) whereas master is the unreleased work-in-progress that may become the next language version. Its current state is not necessarily prescriptive of the next language version's behavior since new additions will be reviewed for inclusion into the release.</p>
<a name="t16.1.9"></a> <h2 id="_language_faq.pod6-Is_there_a_glossary_of_Perl 6_related_terms?">Is there a glossary of Perl 6 related terms?</h2>
<p>Yes, see <a href="#_language_glossary.pod6">glossary</a>.</p>
<a name="t16.1.10"></a> <h2 id="_language_faq.pod6-I'm_a_Perl 5_programmer._Where_is_a_list_of_differences_between_Perl 5_and_Perl 6?">I'm a Perl 5 programmer. Where is a list of differences between Perl 5 and Perl 6?</h2>
<p>There are several <b>5to6-</b> guides in the <a href="https://docs.perl6.org/language.html">Language section of the documentation</a>, most notable of which is the <a href="https://docs.perl6.org/language/5to6-nutshell">5to6-nutshell</a> guide.</p>
<a name="t16.1.11"></a> <h2 id="_language_faq.pod6-I'm_a_Ruby_programmer_looking_for_quickstart_type_docs?">I'm a Ruby programmer looking for quickstart type docs? <a name="93"></a></h2>
<p>See the <a href="https://docs.perl6.org/language/rb-nutshell">rb-nutshell</a> guide.</p>
<a name="t16.2"></a> <h1 id="_language_faq.pod6-Modules">Modules</h1>
<a name="t16.2.1"></a> <h2 id="_language_faq.pod6-Is_there_a_CPAN_(repository_of_third_party_library_modules)_for_Perl 6?">Is there a CPAN (repository of third party library modules) for Perl 6? <a name="94"></a><a name="95"></a></h2>
<p>Yes, it's the same <a href="http://cpan.org/">CPAN</a> as for Perl 5! The only difference is when using <a href="http://pause.perl.org/">PAUSE</a> to upload the module, you'd select <span class="code">Perl 6</span> as the target directory. The <a href="https://modules.perl6.org/l/App::Mi6"><span class="code">App::Mi6</span> tool</a> can simplify the uploading process. Latest versions of <a href="https://modules.perl6.org/l/zef"><span class="code">zef</span> module installer</a> automatically check for latest versions of a module on CPAN as well as our <a href="https://github.com/perl6/ecosystem/">GitHub-based ecosystem</a>.</p>
<p>Viewing of modules available CPAN will be implemented soon on <a href="https://modules.perl6.org/">modules.perl6.org website</a> (temporarily, it's available as a <a href="https://github.com/ugexe/Perl6-ecosystems/blob/master/cpan.json">raw JSON file</a></p>
<a name="t16.2.2"></a> <h2 id="_language_faq.pod6-Is_there_a_perldoc_(command_line_documentation_viewer)_for_Perl 6?">Is there a perldoc (command line documentation viewer) for Perl 6? <a name="96"></a></h2>
<p>Yes, it's called p6doc and is present in the ecosystem under that name. It's present in Rakudo Star but you will need to install it using the monthly release.</p>
<a name="t16.2.3"></a> <h2 id="_language_faq.pod6-Can_I_use_Perl 5_modules_from_Perl 6?">Can I use Perl 5 modules from Perl 6? <a name="97"></a></h2>
<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="t16.2.4"></a> <h2 id="_language_faq.pod6-Can_I_use_C_and_C++_from_Perl 6?">Can I use C and C++ from Perl 6? <a name="98"></a></h2>
<p><a href="https://docs.perl6.org/language/nativecall">Nativecall</a> makes this particularly easy.</p>
<a name="t16.2.5"></a> <h2 id="_language_faq.pod6-Nativecall_can't_find_libfoo.so_and_I_only_have_libfoo.so.1.2!">Nativecall can't find libfoo.so and I only have libfoo.so.1.2!</h2>
<p>This is commonly seen on Debian-like systems. You need to install <span class="code">libfoo-dev</span> package, to set a sym link for the missing file.</p>
<a name="t16.2.6"></a> <h2 id="_language_faq.pod6-Where_have_all_the_traditional_UNIX_library_functions_gone?">Where have all the traditional UNIX library functions gone? <a name="99"></a> <a name="100"></a></h2>
<p>It's very easy to use Nativecall to access them.</p>
<p>An ecosystem module <a href="https://github.com/cspencer/perl6-posix">POSIX</a> is also available.</p>
<a name="t16.2.7"></a> <h2 id="_language_faq.pod6-Does_Rakudo_have_a_core_standard_library?">Does Rakudo have a core standard library?</h2>
<p><a href="https://rakudo.perl6.org/downloads/star/">Rakudo Star distribution</a> does come with <a href="https://github.com/rakudo/star/tree/master/modules">many useful modules</a>.</p>
<p>Rakudo compiler-only release includes <a href="https://docs.perl6.org/language/modules-core">only a couple of the most basic modules</a>.</p>
<p>Many more modules can be found in the <a href="http://modules.perl6.org/">ecosystem</a>.</p>
<a name="t16.2.8"></a> <h2 id="_language_faq.pod6-Is_there_something_like_B::Deparse/How_can_I_get_hold_of_the_AST?">Is there something like <span class="code">B::Deparse</span>/How can I get hold of the AST?</h2>
<p>Use <span class="code">--target=optimize</span> command line option to view the AST of your program, e.g., <span class="code">perl6 --target=optimize -e 'say &quot;hi&quot;'</span></p>
<p>The target <span class="code">optimize</span> gives the AST after the static optimizer did its job, while target <span class="code">ast</span> gives the AST before that step. To get the full list of available targets, run <span class="code">perl6 --stagestats -e &quot;&quot;</span></p>
<a name="t16.2.9"></a> <h2 id="_language_faq.pod6-What_is_Precompilation?">What is Precompilation? <a name="101"></a></h2>
<p>When you load a module for the first time, Rakudo compiles it into bytecode, and both stores it on disk, and uses the compiled bytecode. On subsequent loads, Rakudo prefers to load the bytecode, because that tends to be significantly faster.</p>
<a name="t16.3"></a> <h1 id="_language_faq.pod6-Language_Features">Language Features</h1>
<a name="t16.3.1"></a> <h2 id="_language_faq.pod6-How_can_I_dump_Perl 6_data_structures_(like_Perl 5_Data::Dumper_and_similar)?">How can I dump Perl 6 data structures (like Perl 5 Data::Dumper and similar)? <a name="102"></a></h2>
<p>Typical options are to use <a href="#_routine_say.pod6">say</a> routine that uses <a href="#_routine_gist.pod6">gist</a> method that gives the &quot;gist&quot; of the object being dumped. More detailed output can be obtained by calling <a href="#_routine_perl.pod6">perl</a> method that typically returns representation in <a href="#_routine_EVAL.pod6">EVAL</a>-able code.</p>
<p>If you're using the <a href="http://rakudo.org">rakudo</a> implementation, you can use the <a href="#_programs_01-debugging.pod6-Dumper_function_dd">rakudo-specific <span class="code">dd</span> routine</a> for dumping, whose output is similar to <a href=".perl">.perl</a>, but with more information.</p>
<p>Examples:</p>
<pre class="code"> my $foo = %( foo =&gt; 'bar' );
say $foo.perl; # OUTPUT: «${:foo(&quot;bar&quot;)}␤»
say $foo; # OUTPUT: «{foo =&gt; bar}␤»
# non-standard routine available in rakudo implementation:
dd $foo; # OUTPUT: «Hash $foo = ${:foo(&quot;bar&quot;)}␤»
</pre>
<p>There are also <a href="https://modules.perl6.org/s/dump">several ecosystem modules</a> that provide more control over how data structures are dumped, including support for colored output in.</p>
<a name="t16.3.2"></a> <h2 id="_language_faq.pod6-How_can_I_get_command_line_history_in_the_Perl 6_prompt_(REPL)?">How can I get command line history in the Perl 6 prompt (REPL)?</h2>
<p>Install <a href="https://github.com/hoelzro/p6-linenoise/">Linenoise</a> from the ecosystem.</p>
<p>An alternative for UNIX-like systems is to install <span class="code">rlwrap</span>. This can be done on Debian-ish systems by running:</p>
<pre class="code">sudo apt-get install rlwrap
</pre>
<a name="t16.3.3"></a> <h2 id="_language_faq.pod6-Why_is_the_Rakudo_compiler_so_apologetic?">Why is the Rakudo compiler so apologetic?</h2>
<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="t16.3.4"></a> <h2 id="_language_faq.pod6-What_is_(Any)?">What is <span class="code">(Any)</span>?</h2>
<p><a href="#_type_Any.pod6"><span class="code">Any</span></a> is a top level class most objects inherit from. The <span class="code">Any</span> type object is <a href="#_type_Attribute.html.pod6-Trait_is_default">the default value</a> on variables and parameters without an explicit type constraint, which means you'll likely see <span class="code">(Any)</span> printed when you output a <a href="#_routine_gist.pod6">gist</a> of a variable without any value, such as using <a href="#_routine_say.pod6"><span class="code">say</span> routine</a>:</p>
<pre class="code">my $foo;
say $foo; # OUTPUT: «(Any)␤»
my Int $baz;
say $baz; # OUTPUT: «(Int)␤»
my $bar = 70;
say $bar; # OUTPUT: «70␤»
</pre>
<p>To test whether a variable has any defined values, see <a href="#_classtut.pod6-index-entry-DEFINITE">DEFINITE</a> and <a href="#_routine_defined.pod6">defined</a> routines. Several other constructs exist that test for definiteness, such as <a href="#_syntax_with%20orwith%20without.pod6"><span class="code">with</span> , <span class="code">orwith</span> , and <span class="code">without</span></a> statements, <a href="#_routine_$SOLIDUS$SOLIDUS.pod6"><span class="code">//</span></a>, <a href="#_routine_andthen.pod6">andthen</a>, <a href="#_routine_notandthen.pod6">notandthen</a>, and <a href="#_routine_orelse.pod6">orelse</a> operators, as well as <a href="#_type_Signature.pod6-Constraining_Defined_and_Undefined_Values">type constraint smileys</a>.</p>
<a name="t16.3.5"></a> <h2 id="_language_faq.pod6-What_is_so?">What is <span class="code">so</span>?</h2>
<p><span class="code">so</span> is a loose precedence operator that coerces to <a href="#_type_Bool.pod6">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; # OUTPUT: «True␤»</pre>
<p>In this example, the result of the comparison (which is a <a href="#_type_Junction.pod6">Junction</a>), is converted to Bool before being printed.</p>
<a name="t16.3.6"></a> <h2 id="_language_faq.pod6-What_are_those_:D_and_:U_things_in_signatures?">What are those <span class="code">:D</span> and <span class="code">:U</span> things in signatures?</h2>
<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 &quot;definite&quot;:</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="t16.3.7"></a> <h2 id="_language_faq.pod6-What_is_the_--&gt;_thing_in_the_signature?">What is the <span class="code">--&gt;</span> thing in the signature?</h2>
<p><a href="#_type_Signature.pod6-Constraining_Return_Types">--&gt;</a> 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 --&gt; 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( --&gt; 42 ) { rand }
say discard-random-number;
# OUTPUT: «42␤»</pre>
<p>In this case, the final value is thrown away because the return value is already specified.</p>
<a name="t16.3.8"></a> <h2 id="_language_faq.pod6-How_can_I_extract_the_values_from_a_Junction?">How can I extract the values from a Junction? <a name="103"></a></h2>
<p>If you want to extract the values (eigenstates) from a <a href="#_type_Junction.pod6">Junction</a>, you are probably doing something wrong and should be using a <a href="#_type_Set.pod6">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;
-&gt; Any $s { @states.push: $s }.($j);
@states;
}
say eigenstates(1|2|3).join(', ');
# prints 1, 2, 3 or a permutation thereof</pre>
<a name="t16.3.9"></a> <h2 id="_language_faq.pod6-If_Str_is_immutable,_how_does_s///_work?_If_Int_is_immutable,_how_does_$i++_work?">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>
<p>In Perl 6, values of 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>Knowing this, you would not try to change a literal string (e.g. like <span class="code">'hello' ~~ s/h/H/;</span>), but you might accidentally do something equivalent using <span class="code">map</span> as follows.</p>
<pre class="code">my @foo = &lt;hello world&gt;.map: { s/h/H/ };
# dies with
# Cannot modify an immutable Str (hello)
my @bar = &lt;hello world&gt;».subst-mutate: 'h', 'H';
# dies with
# Cannot resolve caller subst-mutate(Str: Str, Str);
# the following candidates match the type but require
# mutable arguments: ...</pre>
<p>Instead of modifying the original value in place, use a routine or operator that returns a new value:</p>
<pre class="code">my @foo = &lt;hello world&gt;.map: { S/h/H/ }; # ['Hello','world']
my @bar = &lt;hello world&gt;».subst: 'h', 'H'; # ['Hello','world']</pre>
<p>See the documentation on <a href="#_language_containers.pod6">containers</a> for more information.</p>
<a name="t16.3.10"></a> <h2 id="_language_faq.pod6-What's_up_with_array_references_and_automatic_dereferencing?_Do_I_need_the_@_sigil?">What's up with array references and automatic dereferencing? Do I need the <span class="code">@</span> sigil?</h2>
<p>In Perl 6, nearly everything is a reference, so talking about taking references doesn't make much sense. Scalar variables can also contain arrays directly:</p>
<pre class="code">my @a = 1, 2, 3;
say @a; # OUTPUT: «[1 2 3]␤»
say @a.^name; # OUTPUT: «Array␤»
my $scalar = @a;
say $scalar; # OUTPUT: «[1 2 3]␤»
say $scalar.^name; # OUTPUT: «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; # OUTPUT: «6␤»
my @nested = flat $s, $s;
say @nested.elems; # OUTPUT: «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="t16.3.11"></a> <h2 id="_language_faq.pod6-Why_sigils?_Couldn't_you_do_without_them?">Why sigils? Couldn't you do without them? <a name="104"></a></h2>
<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="t16.3.12"></a> <h2 id="_language_faq.pod6-&quot;Type_Str_does_not_support_associative_indexing.&quot;">&quot;Type Str does not support associative indexing.&quot;</h2>
<p>You likely tried to mix string interpolation and key characters, like HTML tags:</p>
<pre class="code">my $foo = &quot;abc&quot;;
say &quot;$foo&lt;html-tag&gt;&quot;;</pre>
<p>Perl 6 thinks <span class="code">$foo</span> to be a Hash and <span class="code">&lt;html-tag&gt;</span> to be a string literal hash key. Use a closure to help it to understand you.</p>
<pre class="code">my $foo = &quot;abc&quot;;
say &quot;{$foo}&lt;html-tag&gt;&quot;;</pre>
<a name="t16.3.13"></a> <h2 id="_language_faq.pod6-Does_Perl 6_have_coroutines?_What_about_yield?">Does Perl 6 have coroutines? What about <span class="code">yield</span>? <a name="105"></a></h2>
<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(-&gt; \x { x² });
</pre>
<a name="t16.3.14"></a> <h2 id="_language_faq.pod6-Why_can't_I_initialize_private_attributes_from_the_new_method,_and_how_can_I_fix_this?">Why can't I initialize private attributes from the new method, and how can I fix this?</h2>
<p>Code like</p>
<pre class="code">class A {
has $!x;
method show-x {
say $!x;
}
}
A.new(x =&gt; 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;
}
}
B.new(x =&gt; 5).show-x;</pre>
<p><span class="code">BUILD</span> is called by the default constructor (indirectly, see <a href="#_language_objects.pod6-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="t16.3.15"></a> <h2 id="_language_faq.pod6-How_and_why_do_say,_put_and_print_differ?">How and why do <span class="code">say</span>, <span class="code">put</span> and <span class="code">print</span> differ?</h2>
<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's 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 &quot;undefined values&quot;, 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; # OUTPUT: «(Date)␤»</pre>
<p>So, <span class="code">say</span> is optimized for debugging; display is optimized for people; and <span class="code">print</span> and <span class="code">put</span> are most 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="t16.3.16"></a> <h2 id="_language_faq.pod6-What's_the_difference_between_token_and_rule_?">What's the difference between <span class="code">token</span> and <span class="code">rule</span> ?</h2>
<p><span class="code">regex</span>, <span class="code">token</span> and <span class="code">rule</span> 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&gt;</span> calls (i.e., 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="t16.3.17"></a> <h2 id="_language_faq.pod6-What's_the_difference_between_die_and_fail?">What's the difference between <span class="code">die</span> and <span class="code">fail</span>?</h2>
<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 &quot;unthrown&quot; or &quot;lazy&quot; exception. It's 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="t16.3.18"></a> <h2 id="_language_faq.pod6-Why_is_wantarray_or_want_gone?_Can_I_return_different_things_in_different_contexts?">Why is <span class="code">wantarray</span> or <span class="code">want</span> gone? Can I return different things in different contexts?</h2>
<p>Perl 5 has the <a href="#_language_5to6-perlfunc.pod6-wantarray"><span class="code">wantarray</span></a> function that tells you whether it's 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's 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's no way to determine if the caller of sub <span class="code">f</span> wants a string or an integer, because it's 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>One way to achieve context sensitivity in Perl 6 is to return an object that knows how to respond to method calls that are typical for a context. In Perl 6, this is actually a <a href="#_language_5to6-perlfunc.pod6-wantarray">lot easier</a> than it may sound, and other features of the language either mitigate the need to do so in the first place or make it possible to cover most of the use cases of wantarray.</p>
<p>For example, regex matches return <a href="#_type_Match.pod6">Match objects that know how to respond to list indexing, hash indexing, and that can turn into the matched string</a>.</p>
<a name="t16.3.19"></a> <h2 id="_language_faq.pod6-What's_the_difference_between_Pointer_and_OpaquePointer?">What's the difference between <span class="code">Pointer</span> and <span class="code">OpaquePointer</span>?</h2>
<p><span class="code">OpaquePointer</span> is deprecated and has been replaced with <span class="code">Pointer</span>.</p>
<a name="t16.4"></a> <h1 id="_language_faq.pod6-Perl 6_Implementation">Perl 6 Implementation <a name="106"></a></h1>
<a name="t16.4.1"></a> <h2 id="_language_faq.pod6-What_Perl 6_Implementations_are_available?">What Perl 6 Implementations are available?</h2>
<p>Currently the best developed is Rakudo (using multiple Virtual Machine backends). Historic implementations include Niecza (.NET) and Pugs (Haskell). Others are listed at <a href="https://www.perl6.org/compilers/">Perl 6 Compilers</a></p>
<a name="t16.4.2"></a> <h2 id="_language_faq.pod6-What_language_is_Rakudo_written_in?">What language is Rakudo written in?</h2>
<p>A short answer is that Rakudo is written almost entirely in Perl 6. A more detailed answer is that Rakudo is written in a mixture of Perl 6 and NQP (&quot;Not Quite Perl&quot;). NQP is a lightweight Perl 6-like environment for virtual machines; it's designed to be a high-level way to create compilers and libraries for virtual machines (such as MoarVM and JVM) using Perl 6 syntax.</p>
<a name="t16.4.3"></a> <h2 id="_language_faq.pod6-What_language_is_NQP_written_in?">What language is NQP written in? <a name="107"></a></h2>
<p>NQP is a mixture of (1) NQP code, (2) whatever language the underlying virtual machine is using, (3) some third-party C and Java libraries, and (4) some bootstrapping files created by earlier runs of the build process.</p>
<a name="t16.4.4"></a> <h2 id="_language_faq.pod6-Is_Perl 6_Lisp?">Is Perl 6 Lisp?</h2>
<pre class="code">(not (not Nil))</pre>
<a name="t16.5"></a> <h1 id="_language_faq.pod6-Meta_Questions_and_Advocacy">Meta Questions and Advocacy</h1>
<a name="t16.5.1"></a> <h2 id="_language_faq.pod6-Why_is_Perl 6_called_Perl?">Why is Perl 6 called Perl?</h2>
<p>… As opposed to some other name that didn't imply all the things that the higher number might indicate on other languages.</p>
<p>The short answer is that it was Larry's choice under <a href="http://perldoc.perl.org/5.12.4/perlhack.html#DESCRIPTION">Rule 1</a>.</p>
<p>The community considers Perl 5 and Perl 6 sister languages - they have a lot in common, address many of the same problem spaces, but Perl 6 is not intended to replace Perl 5. In fact, both languages interoperate with each other.</p>
<a name="t16.5.2"></a> <h2 id="_language_faq.pod6-When_will_Perl 6_be_ready?_Is_it_ready_now?">When will Perl 6 be ready? Is it ready now?</h2>
<p>Readiness of programming languages and their compilers is not a binary decision. As the language and the implementations evolve, they grow steadily more usable. Depending on your needs, Perl 6 and its compilers may or may not be ready for you.</p>
<p>That said, version 6.c (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="t16.5.3"></a> <h2 id="_language_faq.pod6-Why_should_I_learn_Perl 6?_What's_so_great_about_it?">Why should I learn Perl 6? What's so great about it?</h2>
<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>Clean, more readable regular expressions; taken to the next level of usability, with a lot more functionality. Named regular expressions improve ease of use.</p>
</li></ul> <ul><li><p>Junctions allowing easy checking of multiple possibilities; e.g., $a == 1|3|42 ( 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”; e.g., 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 for 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 &gt;&gt;. 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 and 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>Simple numeric computation 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 collection 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 mottos 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="t16.5.4"></a> <h2 id="_language_faq.pod6-Is_Perl 6_fast_enough_for_me?">Is Perl 6 fast enough for me?</h2>
<p>That depends on what you are doing. Rakudo has been developed with the philosophy of &quot;make it work right then make it work fast&quot;. It's fast for some things already but needs work for others. 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.</p>
<p>The following crude benchmarks, with all the usual caveats about such things, show that Perl 6 can be faster than Perl 5 for similar tasks if the big weaponry is included; at the same time, Perl 5 can be faster if only the bare bones are included. Similar situation can be observed when comparing Perl 6 to other languages.</p>
<p>Try it on your system. You may be pleasantly surprised!</p>
<p>Examples:</p>
<pre class="code"># Perl 6 version
use v6.c;
class Foo { has $.i is rw };
for 1..1_000_000 -&gt; $i {
my $obj = Foo.new;
$obj.i = $i;
}
</pre>
<pre class="code"># Perl 5 version
package Foo;
use Moose;
has i =&gt; (is =&gt; 'rw');
__PACKAGE__-&gt;meta-&gt;make_immutable;
for my $i (1..1_000_000) {
my $obj = Foo-&gt;new;
$obj-&gt;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-&gt;new;
$obj-&gt;i($i);
}
1;
</pre>
<pre class="code"># 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>
</div>
<!-- /language/functions.pod6 --><div class="pod-body"><a id="_language_functions.pod6"></a><a name="t17"></a><h1 class="title">17 Functions</h1> <p class="subtitle">Functions and Functional Programming in Perl 6</p> <p>Routines are the smallest means of code reuse in Perl 6. They come in several forms, most notably <a href="#_type_Method.pod6">methods</a>, which belong in classes and roles and are associated with an object; and functions (also called <i>subroutines</i> or <a href="#_type_Sub.pod6">sub</a>s, for short), which can be called 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.pod6">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 the return value.</p>
<p>Introspection on subroutines is provided via <a href="#_type_Routine.pod6"><span class="code">Routine</span></a>.</p>
<a name="t17.1"></a> <h1 id="_language_functions.pod6-Defining/Creating/Using_Functions">Defining/Creating/Using Functions</h1>
<a name="t17.1.1"></a> <h2 id="_language_functions.pod6-Subroutines"><a name="108"></a>Subroutines</h2>
<p>To basic way to create a subroutine is to use the <span class="code">sub</span> declarator followed by an optional <a href="#_language_syntax.pod6-Identifiers">identifier</a>:</p>
<pre class="code">sub my-func { say &quot;Look ma, no args!&quot; }
my-func;</pre>
<p>The sub declarator returns a value of type <a href="#_type_Sub.pod6">Sub</a> that can be stored in any container:</p>
<pre class="code">my &amp;c = sub { say &quot;Look ma, no name!&quot; }
c;
my Any:D $f = sub { say '$f' }
$f;
my Code \a = sub { say ‚raw containers don't implement postcircumfix:&lt;( )&gt;‘ };
a.();</pre>
<p>The declarator <span class="code">sub</span> will declare a new name in the current scope at compile time. As such any indirection has to be resolved at compile time:</p>
<pre class="code">constant aname = 'foo';
sub ::(aname) { say 'oi‽' };
foo;</pre>
<p>This will become more useful once macros are added to Perl 6.</p>
<p>To have the subroutine take arguments, a <a href="#_type_Signature.pod6">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> &quot;!!!!&quot;
}
exclaim &quot;Howdy, World&quot;;
</pre>
<p>By default, subroutines are <a href="#_syntax_my.pod6">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) {
# Puts a slash before non-alphanumeric characters
S:g[&lt;-alpha -digit&gt;] = &quot;\\$/&quot; given $str
}
say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
{
sub escape($str) {
# Writes each non-alphanumeric character in its hexadecimal escape
S:g[&lt;-alpha -digit&gt;] = &quot;\\x[{ $/.ord.base(16) }]&quot; given $str
}
say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤»
}
# Back to original escape function
say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?␤»
</pre>
<p>Subroutines don't have to be named. If unnamed, they're called anonymous subroutines.</p>
<pre class="code">say sub ($a, $b) { $a ** 2 + $b ** 2 }(3, 4) # OUTPUT: «25␤»</pre>
<p>But in this case, it's often desirable to use the more succinct <a href="#_type_Block.pod6">block</a> syntax. Subroutines and blocks can be called in place, as in the example above.</p>
<a name="t17.1.2"></a> <h2 id="_language_functions.pod6-Blocks_and_Lambdas"><a name="109"></a>Blocks and Lambdas</h2>
<p>Whenever you see something like <span class="code">{ $_ + 42 }</span>, <span class="code">-&gt; $a, $b { $a ** $b }</span>, or <span class="code">{ $^text.indent($:spaces) }</span>, that's <a href="#_type_Block.pod6">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 -&gt; $a, $b {
say $a ~ $b;
}
# OUTPUT: «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) # OUTPUT: «25␤»</pre>
<p>For block syntax details, see the documentation for the <a href="#_type_Block.pod6">Block</a> type.</p>
<a name="t17.1.3"></a> <h2 id="_language_functions.pod6-Signatures">Signatures</h2>
<p>The parameters that a function accepts are described in its <i>signature</i>.</p>
<pre class="code">sub format <b>(Str $s)</b> { ... }
-&gt; <b>$a, $b</b> { ... }
</pre>
<p>Details about the syntax and use of signatures can be found in the <a href="#_type_Signature.pod6">documentation on the <span class="code">Signature</span> class</a>.</p>
<a name="t17.1.3.1"></a> <h3 id="_language_functions.pod6-Automatic_Signatures">Automatic Signatures</h3>
<p><a id="i110" name="@_"></a><span class="indexed"></span><a id="i111" name="%_"></a><span class="indexed"></span> If no signature is provided but either of the two automatic variables <span class="code">@_</span> or <span class="code">%_</span> are used in the function body, a signature with <span class="code">*@_</span> or <span class="code">*%_</span> will be generated. Both automatic variables can be used at the same time.</p>
<pre class="code">sub s { say @_, %_ };
say &amp;s.signature # OUTPUT: «(*@_, *%_)␤»</pre>
<a name="t17.1.4"></a> <h2 id="_language_functions.pod6-Arguments">Arguments <a name="112"></a></h2>
<p>Arguments are supplied as a comma separated list. To disambiguate nested calls, use parentheses:</p>
<pre class="code">sub f(&amp;c){ c() * 2 }; # call the function reference c with empty parameter list
sub g($p){ $p - 2 };
say(g(42), 45); # pass only 42 to g()</pre>
<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's 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">sub f(|c){};
f :named(35); # A named argument (in &quot;adverb&quot; form)
f named =&gt; 35; # Also a named argument
f :35named; # A named argument using abbreviated adverb form
f 'named' =&gt; 35; # Not a named argument, a Pair in a positional argument
my \c = &lt;a b c&gt;.Capture;
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="#_type_Capture.pod6">documentation on the <span class="code">Capture</span> class</a>.</p>
<p>When using named arguments, note that normal List &quot;pair-chaining&quot; allows one to skip commas between named arguments.</p>
<pre class="code">sub f(|c){};
f :dest&lt;/tmp/foo&gt; :src&lt;/tmp/bar&gt; :lines(512);
f :32x :50y :110z; # This flavor of &quot;adverb&quot; works, too
f :a:b:c; # The spaces are also optional.</pre>
<a name="t17.1.5"></a> <h2 id="_language_functions.pod6-Return_values">Return values</h2>
<p>Any <span class="code">Block</span> or <span class="code">Routine</span> will provide its last expression as a return value to the caller. If <a href="#_language_control.pod6-return">return</a> or <a href="#_language_control.pod6-return-rw">return-rw</a> are called their parameter, if any, will become the return value. The default return value is <a href="#_type_Nil.pod6">Nil</a>.</p>
<pre class="code">sub a { 42 };
sub b { say a };
b;
# OUTPUT: «42␤»</pre>
<p>Multiple return values are returned as a list or by creating a <a href="#_type_Capture.pod6">Capture</a>. Destructuring can be used to untangle multiple return values.</p>
<pre class="code">sub a { 42, 'answer' };
put a.perl;
# OUTPUT: «(42, &quot;answer&quot;)␤»
my ($n, $s) = a;
put [$s, $n];
# OUTPUT: «answer 42␤»
sub b { &lt;a b c&gt;.Capture };
put b.perl;
# OUTPUT: «\(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)␤»</pre>
<a name="t17.1.6"></a> <h2 id="_language_functions.pod6-Return_Type_Constraints">Return Type Constraints</h2>
<p>Perl 6 has many ways to specify a function's return type:</p>
<pre class="code">sub foo(--&gt; Int) {}; say &amp;foo.returns; # OUTPUT: «(Int)␤»
</pre>
<pre class="code">sub foo() returns Int {}; say &amp;foo.returns; # OUTPUT: «(Int)␤»
</pre>
<pre class="code">sub foo() of Int {}; say &amp;foo.returns; # OUTPUT: «(Int)␤»
</pre>
<pre class="code">my Int sub foo() {}; say &amp;foo.returns; # OUTPUT: «(Int)␤»
</pre>
<p>Attempting to return values of another type will cause a compilation error.</p>
<pre class="code">sub foo() returns Int { &quot;a&quot;; }; foo; # Type check fails
</pre>
<p>Note that <span class="code">Nil</span> and <span class="code">Failure</span> are exempt from return type constraints and can be returned from any routine, regardless of its constraint:</p>
<pre class="code">sub foo() returns Int { fail }; foo; # Failure returned
sub bar() returns Int { return }; bar; # Nil returned
</pre>
<a name="t17.1.7"></a> <h2 id="_language_functions.pod6-Multi-dispatch"><a name="113"></a>Multi-dispatch</h2>
<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 determines the proper <i>candidate</i> and calls it.</p>
<p>You declare each candidate with the <span class="code">multi</span> declarator:</p>
<pre class="code">multi congratulate($name) {
say &quot;Happy birthday, $name&quot;;
}
multi congratulate($name, $age) {
say &quot;Happy {$age}th birthday, $name&quot;;
}
congratulate 'Larry'; # OUTPUT: «Happy birthday, Larry␤»
congratulate 'Bob', 45; # OUTPUT: «Happy 45th birthday, Bob␤»</pre>
<p>Dispatch can happen on the number of arguments (the <a href="#_type_Routine.pod6-(Code)_method_arity">arity</a>), the type of arguments but also on additional assertions which can be placed on them. For more information about type constraints see the documentation for the <a href="#_type_Signature.pod6-Type_Constraints">Signature</a> class.</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]); # OUTPUT: «[true, 42]␤»</pre>
<p>Named parameters participate in the dispatch even if they are not provided in the call. Therefore a multi candidate with named parameters will be given precedence.</p>
<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 &quot;Hooray for your $reason, $name&quot;;
}
}
role BirthdayCongrats {
multi method congratulate('birthday', $name) {
say &quot;Happy birthday, $name&quot;;
}
multi method congratulate('birthday', $name, $age) {
say &quot;Happy {$age}th birthday, $name&quot;;
}
}
my $congrats = Congrats.new does BirthdayCongrats;
$congrats.congratulate('promotion','Cindy'); # OUTPUT: «Hooray for your promotion, Cindy␤»
$congrats.congratulate('birthday','Bob'); # OUTPUT: «Happy birthday, Bob␤»</pre>
<p>Unlike <span class="code">sub</span>, if you use named parameters with multi methods, the parameters must be required parameters to behave as expected.</p>
<p>Please note that a non-multi sub or operator will hide multi candidates of the same name in any parent scope or child scope. The same is true for imported non-multi candidates.</p>
<a name="t17.1.7.1"></a> <h3 id="_language_functions.pod6-proto"><a name="114"></a>proto</h3>
<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 &quot;Hooray for your $reason, $name&quot;;
}
multi congratulate($reason, $name, Int $rank) {
say &quot;Hooray for your $reason, $name -- got rank $rank!&quot;;
}
congratulate('being a cool number', 'Fred'); # OK
congratulate('being a cool number', 'Fred', 42); # OK</pre>
<pre class="code"> congratulate('being a cool number', 42); # Proto match error
</pre>
<p>The proto insists that all <span class="code">multi congratulate</span> 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, and allows a <span class="code">multi</span> to take additional arguments. The first two calls succeed, but the third fails (at compile time) because <span class="code">42</span> doesn't match <span class="code">Str</span>.</p>
<pre class="code">say &amp;congratulate.signature # OUTPUT: «(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 -- False if unsuccessful
proto notify(Str $user,Str $msg) {
my \hour = DateTime.now.hour;
if hour &gt; 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 passed on.</p>
<pre class="code">proto mistake-proto(Str() $str, Int $number = 42) {*}
multi mistake-proto($str, $number) { say $str.^name }
mistake-proto(7, 42); # OUTPUT: «Int␤» -- not passed on
</pre>
<pre class="code">mistake-proto('test'); # fails -- not passed on
</pre>
only
<a name="t17.2"></a> <h1 id="_language_functions.pod6-Conventions_and_Idioms">Conventions and Idioms</h1>
<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.</p>
<a name="t17.2.1"></a> <h2 id="_language_functions.pod6-Slurpy_Conventions">Slurpy Conventions</h2>
<p>Perhaps the most important one of these conventions is the way slurpy list arguments are handled. Most of the time, functions will not automatically flatten slurpy lists. The rare exceptions are those functions that don't have a reasonable behavior on lists of lists (e.g., <a href="#_routine_chrs.pod6">chrs</a>) or where there is a conflict with an established idiom (e.g., <a href="#_routine_pop.pod6">pop</a> being the inverse of <a href="#_routine_push.pod6">push</a>).</p>
<p>If you wish to match this look and feel, any <a href="#_type_Iterable.pod6">Iterable</a> argument must be broken out element-by-element using a <span class="code">**@</span> slurpy, with two nuances:</p>
<ul><li><p>An <a href="#_type_Iterable.pod6">Iterable</a> inside a <a href="#_language_containers.pod6-Scalar_containers">Scalar container</a> doesn't count.</p>
</li></ul> <ul><li><p><a href="#_type_List.pod6">List</a>s created with a <a href="#_routine_,.pod6"><span class="code">,</span></a> at the top level only count as one <a href="#_type_Iterable.pod6">Iterable</a>.</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) { &quot;grab $_&quot;.say for @a }</pre>
<p>which is shorthand for something very close to:</p>
<pre class="code">multi sub grab(**@a) { &quot;grab $_&quot;.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 <i>&quot;single argument rule&quot;</i> and is important to understand when invoking slurpy functions:</p>
<pre class="code">grab(1, 2); # OUTPUT: «grab 1␤grab 2␤»
grab((1, 2)); # OUTPUT: «grab 1␤grab 2␤»
grab($(1, 2)); # OUTPUT: «grab 1 2␤»
grab((1, 2), 3); # OUTPUT: «grab 1 2␤grab 3␤»
</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)); # OUTPUT: «grab 1␤grab 2␤grab 3␤grab 4␤»
grab(flat $(1, 2), $(3, 4)); # OUTPUT: «grab 1 2␤grab 3 4␤»
grab(flat (1, 2)); # OUTPUT: «grab 1␤grab 2␤»
grab(flat $(1, 2)); # OUTPUT: «grab 1␤grab 2␤»
</pre>
<p>It's worth noting that mixing binding and sigilless variables in these cases requires a bit of finesse, because there is no <a href="#_type_Scalar.pod6">Scalar</a> intermediary used during binding.</p>
<pre class="code">my $a = (1, 2); # Normal assignment, equivalent to $(1, 2)
grab($a); # OUTPUT: «grab 1 2␤»
my $b := (1, 2); # Binding, $b links directly to a bare (1, 2)
grab($b); # OUTPUT: «grab 1␤grab 2␤»
my \c = (1, 2); # Sigilless variables always bind, even with '='
grab(c); # OUTPUT: «grab 1␤grab 2␤»
</pre>
<a name="t17.3"></a> <h1 id="_language_functions.pod6-Functions_are_First-Class_Objects">Functions are First-Class Objects</h1>
<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); # OUTPUT: «36␤»</pre>
<p><a id="i115" name="prefix &amp;"></a><span class="indexed"></span> Or you can reference an existing named function by using the <span class="code">&amp;</span>-sigil 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.pod6-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; # OUTPUT: «1, 4, 9, 16, 25␤»</pre>
<a name="t17.3.1"></a> <h2 id="_language_functions.pod6-Infix_Form"><!-- -->Infix Form</h2>
<p>To call a subroutine with 2 arguments like an infix operator, use a subroutine reference surrounded by <span class="code">[</span> and <span class="code">]</span>.</p>
<pre class="code">sub plus { $^a + $^b };
say 21 [&amp;plus] 21;
# OUTPUT: «42␤»</pre>
<a name="t17.3.2"></a> <h2 id="_language_functions.pod6-Closures">Closures</h2>
<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(); # OUTPUT: «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>Another closure example is the use of <a href="#_type_List.pod6-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; # OUTPUT: «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="t17.3.3"></a> <h2 id="_language_functions.pod6-Routines">Routines</h2>
<p>Routines are code objects that conform to <a href="#_type_Routine.pod6">type Routine</a>, most notably <a href="#_type_Sub.pod6">Sub</a>, <a href="#_type_Method.pod6">Method</a>, <a href="#_type_Regex.pod6">Regex</a> and <a href="#_type_Submethod.pod6">Submethod</a>.</p>
<p>They carry additional functionality in addition to what <a href="#_type_Block.pod6">Block</a> supplies: they can come as <a href="#16-Multi-dispatch">multis</a>, you can <a href="#_type_Routine.pod6-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&gt;;
sub has-keyword(*@words) {
for @words -&gt; $word {
return True if $word (elem) $keywords;
}
False;
}
say has-keyword 'not', 'one', 'here'; # OUTPUT: «False␤»
say has-keyword 'but', 'here', 'for'; # OUTPUT: «True␤»</pre>
<p>Here, <span class="code">return</span> doesn't 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>
<p><a id="i116" name="use soft (pragma)"></a><span class="indexed"></span> Routines can be inlined and as such provide an obstacle for wrapping. Use the pragma <span class="code">use soft;</span> to prevent inlining to allow wrapping at runtime.</p>
<pre class="code">sub testee(Int $i, Str $s){
rand.Rat * $i ~ $s;
}
sub wrap-to-debug(&amp;c){
say &quot;wrapping {&amp;c.name} with arguments {&amp;c.signature.perl}&quot;;
&amp;c.wrap: sub (|args){
note &quot;calling {&amp;c.name} with {args.gist}&quot;;
my \ret-val := callwith(|args);
note &quot;returned from {&amp;c.name} with return value {ret-val.perl}&quot;;
ret-val
}
}
my $testee-handler = wrap-to-debug(&amp;testee);
# OUTPUT: «wrapping testee with arguments :(Int $i, Str $s)»
say testee(10, &quot;ten&quot;);
# OUTPUT: «calling testee with \(10, &quot;ten&quot;)␤returned from testee with return value &quot;6.151190ten&quot;␤6.151190ten»
&amp;testee.unwrap($testee-handler);
say testee(10, &quot;ten&quot;);
# OUTPUT: «6.151190ten␤»</pre>
Important ones: candidates, wrap, unwrap, assuming, arity, count
<a name="t17.4"></a> <h1 id="_language_functions.pod6-Defining_Operators">Defining Operators</h1>
<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;+&gt;(Int $x, &quot;same&quot;) { 2 * $x };
say 21 + &quot;same&quot;; # OUTPUT: «42␤»
# defining a new operator
sub postfix:&lt;!&gt;(Int $x where { $x &gt;= 0 }) { [*] 1..$x };
say 6!; # OUTPUT: «720␤»
</pre>
<p>The operator declaration becomes available as soon as possible, so you can recurse into a just-defined operator:</p>
<pre class="code">sub postfix:&lt;!&gt;(Int $x where { $x &gt;= 0 }) {
$x == 0 ?? 1 !! $x * ($x - 1)!
}
say 6!; # OUTPUT: «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&gt;(*@elems) {
&quot;start&quot;, @elems, &quot;end&quot;
}
say START 'a', 'b', 'c' END; # OUTPUT: «(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;!! !!&gt;($left, $inside) {
&quot;$left -&gt; ( $inside )&quot;
}
say 42!! 1 !!; # OUTPUT: «42 -&gt; ( 1 )␤»
</pre>
<p>Blocks can be assigned directly to operator names. Use a variable declarator and prefix the operator name with a <span class="code">&amp;</span>-sigil.</p>
<pre class="code">my &amp;infix:&lt;ieq&gt; = -&gt; |l { [eq] l&gt;&gt;.fc };
say &quot;abc&quot; ieq &quot;Abc&quot;;
# OUTPUT: «True␤»</pre>
<a name="t17.4.1"></a> <h2 id="_language_functions.pod6-Precedence">Precedence</h2>
<p><a id="i117" name="is tighter"></a><span class="indexed"></span><a id="i118" name="is equiv"></a><span class="indexed"></span><a id="i119" name="is looser"></a><span class="indexed"></span> Operator precedence in Perl 6 is specified relatively to existing operators. The traits <span class="code">is tighter</span>, <span class="code">is equiv</span> and <span class="code">is looser</span> can be provided with an operator, the new operators precedence is related to. More than one trait can be applied.</p>
<p>For example, <span class="code">infix:&lt;*&gt;</span> has a tighter precedence than <span class="code">infix:&lt;+&gt;</span>, and squeezing one in between works like this:</p>
<pre class="code">sub infix:&lt;!!&gt;($a, $b) is tighter(&amp;infix:&lt;+&gt;) {
2 * ($a + $b)
}
say 1 + 2 * 3 !! 4; # OUTPUT: «21␤»
</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;!!&gt;($a, $b) is looser(&amp;infix:&lt;*&gt;) { ... }</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="t17.4.2"></a> <h2 id="_language_functions.pod6-Associativity">Associativity</h2>
<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>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;**&gt; </span>:</p>
<pre class="code">say 2 ** (2 ** 3); # OUTPUT: «256␤»
say (2 ** 2) ** 3; # OUTPUT: «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;!&gt;($a; $b; $c)</td></tr>
</table> <p><a id="i120" name="is assoc (trait)"></a><span class="indexed"></span> 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;§&gt;(*@a) is assoc&lt;list&gt; {
'(' ~ @a.join('|') ~ ')';
}
say 1 § 2 § 3; # OUTPUT: «(1|2|3)␤»
</pre>
<a name="t17.5"></a> <h1 id="_language_functions.pod6-Traits">Traits</h1>
<p><i>Traits</i> are subroutines that run at compile time and 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&gt;;
# ^^^^^^^ 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&gt; </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. See <a href="#_type_Sub.pod6-Traits">Sub</a> for details.</p>
<pre class="code">multi sub trait_mod:&lt;is&gt;(Routine $r, :$doubles!) {
$r.wrap({
2 * callsame;
});
}
sub square($x) is doubles {
$x * $x;
}
say square 3; # OUTPUT: «18␤»
</pre>
<p>See <a href="#_type_Routine.pod6">type Routine</a> for the documentation of built-in routine traits.</p>
<a name="t17.6"></a> <h1 id="_language_functions.pod6-Re-dispatching">Re-dispatching</h1>
<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>Fortunately, we have a series of re-dispatching tools that help us to make it easy.</p>
<a name="t17.6.1"></a> <h2 id="_language_functions.pod6-sub_callsame">sub callsame</h2>
<p><a id="i121" name="dispatch callsame"></a><span class="indexed"></span></p>
<p><span class="code">callsame</span> calls the next matching candidate with the same arguments that were used for the current candidate and returns that candidate's return value.</p>
<pre class="code">proto a(|) {*}
multi a(Any $x) {
say &quot;Any $x&quot;;
return 5;
}
multi a(Int $x) {
say &quot;Int $x&quot;;
my $res = callsame;
say &quot;Back in Int with $res&quot;;
}
a 1; # OUTPUT: «Int 1␤Any 1␤Back in Int with 5␤»
</pre>
<a name="t17.6.2"></a> <h2 id="_language_functions.pod6-sub_callwith">sub callwith</h2>
<p><a id="i122" name="dispatch callwith"></a><span class="indexed"></span></p>
<p><span class="code">callwith</span> calls the next matching candidate with arguments provided by users and returns that candidate's return value.</p>
<pre class="code">proto a(|) {*}
multi a(Any $x) {
say &quot;Any $x&quot;;
return 5;
}
multi a(Int $x) {
say &quot;Int $x&quot;;
my $res = callwith($x + 1);
say &quot;Back in Int with $res&quot;;
}
a 1; # OUTPUT: «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. Note that although our parameter <span class="code">$x + 1</span> is an Int, still we call the next candidate in the chain.</p>
<a name="t17.6.3"></a> <h2 id="_language_functions.pod6-sub_nextsame">sub nextsame</h2>
<p><a id="i123" name="dispatch nextsame"></a><span class="indexed"></span></p>
<p><span class="code">nextsame</span> calls the next matching candidate with the same arguments that were used for the current candidate and <b>never</b> returns.</p>
<pre class="code">proto a(|) {*}
multi a(Any $x) {
say &quot;Any $x&quot;;
return 5;
}
multi a(Int $x) {
say &quot;Int $x&quot;;
nextsame;
say &quot;never executed because nextsame doesn't return&quot;;
}
a 1; # OUTPUT: «Int 1␤Any 1␤»
</pre>
<a name="t17.6.4"></a> <h2 id="_language_functions.pod6-sub_nextwith">sub nextwith</h2>
<p><a id="i124" name="dispatch nextwith"></a><span class="indexed"></span></p>
<p><span class="code">nextwith</span> calls the next matching candidate with arguments provided by users and <b>never</b> returns.</p>
<pre class="code">proto a(|) {*}
multi a(Any $x) {
say &quot;Any $x&quot;;
return 5;
}
multi a(Int $x) {
say &quot;Int $x&quot;;
nextwith($x + 1);
say &quot;never executed because nextsame doesn't return&quot;;
}
a 1; # OUTPUT: «Int 1␤Any 2␤»
</pre>
<a name="t17.6.5"></a> <h2 id="_language_functions.pod6-sub_samewith">sub samewith</h2>
<p><a id="i125" name="dispatch samewith"></a><span class="indexed"></span></p>
<p><span class="code">samewith</span> calls current candidate again with arguments provided by users and returns return value of the new instance of current candidate.</p>
<pre class="code">proto a(|) {*}
multi a(Int $x) {
return 1 unless $x &gt; 1;
return $x * samewith($x-1);
}
say (a 10); # OUTPUT: «36288002␤»
</pre>
<a name="t17.6.6"></a> <h2 id="_language_functions.pod6-sub_nextcallee">sub nextcallee</h2>
<p><a id="i126" name="dispatch nextcallee"></a><span class="indexed"></span></p>
<p>Redispatch may be required to call a block that is not the current scope what provides <span class="code">nextsame</span> and friends with the problem to referring to the wrong scope. Use <span class="code">nextcallee</span> to capture the right candidate and call it at the desired time.</p>
<pre class="code">proto pick-winner(|) {*}
multi pick-winner (Int \s) {
my &amp;nextone = nextcallee;
Promise.in(π²).then: { nextone s }
}
multi pick-winner { say &quot;Woot! $^w won&quot; }
with pick-winner ^5 .pick -&gt; \result {
say &quot;And the winner is...&quot;;
await result;
}
# OUTPUT:
# And the winner is...
# Woot! 3 won
</pre>
<p>The Int candidate takes the <span class="code">nextcallee</span> and then fires up a Promise to be executed in parallel, after some timeout, and then returns. We can't use <span class="code">nextsame</span> here, because it'd be trying to <span class="code">nextsame</span> the Promise's block instead of our original routine.</p>
<a name="t17.6.7"></a> <h2 id="_language_functions.pod6-wrapped_routines">wrapped routines</h2>
<p><a id="i127" name="dispatch wrapped routines"></a><span class="indexed"></span></p>
<p>Besides those are mentioned above, re-dispatch is helpful in more situations. One 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(sub ($num) {
nextsame if $num &gt;= 0;
1i * callwith(abs($num));
});
say square-root(4); # OUTPUT: «2␤»
say square-root(-4); # OUTPUT: «0+2i␤»
</pre>
<a name="t17.6.8"></a> <h2 id="_language_functions.pod6-routines_of_parent_class">routines of parent class</h2>
<p><a id="i128" name="dispatch super"></a><span class="indexed"></span></p>
<p>Another use case is to re-dispatch to methods from parent classes.</p>
<pre class="code">class LoggedVersion is Version {
method new(|c) {
note &quot;New version object created with arguments &quot; ~ c.perl;
nextsame;
}
}
say LoggedVersion.new('1.0.2');
</pre>
<a name="t17.7"></a> <h1 id="_language_functions.pod6-Coercion_Types">Coercion Types</h1>
<p>Coercion types force a specific type for routine arguments while allowing the routine itself to accept a wider input. When invoked, the arguments are narrowed automatically to the stricter type, and therefore within the routine the arguments have always the desired type.</p>
<p>In the case the arguments cannot be converted to the stricter type, a <i>Type Check</i> error is thrown.</p>
<pre class="code">sub double(Int(Cool) $x) {
2 * $x
}
say double '21'; # OUTPUT: «42␤»
say double 21; # OUTPUT: «42␤»
say double Any; # Type check failed in binding $x; expected 'Cool' but got 'Any'
</pre>
<p>In the above example, the <a href="#_type_Int.pod6">Int</a> is the target type to which the argument <span class="code">$x</span> will be coerced, and <a href="#_type_Cool.pod6">Cool</a> is the type that the routine accepts as wider input.</p>
<p>If the accepted wider input type is <a href="#_type_Any.pod6">Any</a>, it is possible to abbreviate the coercion <span class="code">Int(Any)</span> omitting the <span class="code">Any</span> type, thus resulting in <span class="code">Int()</span>.</p>
<p>The coercion works by looking for a method with the same name as the target type: if such method is found on the argument, it is invoked to convert the latter to the expected narrow type. From the above, it is clear that it is possible to provide coercion among user types just providing the required methods:</p>
<pre class="code">class Bar {
has $.msg;
}
class Foo {
has $.msg = &quot;I'm a foo!&quot;;
# allows coercion from Foo to Bar
method Bar {
Bar.new(:msg($.msg ~ ' But I am now Bar.'));
}
}
# wants a Bar, but accepts Any
sub print-bar(Bar() $bar) {
say $bar.^name; # OUTPUT: «Bar␤»
say $bar.msg; # OUTPUT: «I'm a foo! But I am now Bar.␤»
}
print-bar Foo.new;
</pre>
<p>In the above code, once a <span class="code">Foo</span> instance is passed as argument to <span class="code">print-bar</span>, the <span class="code">Foo.Bar</span> method is called and the result is placed into <span class="code">$bar</span>.</p>
<p>Coercion types are supposed to work wherever types work, but Rakudo currently (2017.05) only implements them in signatures, for both parameters and return types.</p>
is the above referencing rakudo 2017.05 still valid?
is it worth placing an example about return types?
<a name="t17.8"></a> <h1 id="_language_functions.pod6-sub_MAIN">sub MAIN</h1>
<p><a id="i129" name="MAIN"></a><span class="indexed"></span><a id="i130" name="command line arguments"></a><span class="indexed"></span></p>
<p>The sub with the special name <span class="code">MAIN</span> is executed after all relevant phasers, and its signature is the means by which command line arguments can be parsed. Multi methods are supported and a usage method is automatically generated and displayed if no command line arguments are provided. All command line arguments are also available in <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">@*ARGS</span></a>, which can be mutated before being processed by <span class="code">MAIN</span>.</p>
<p>The return value of <span class="code">MAIN</span> is ignored: using explicitly <span class="code">return</span> will terminate the <span class="code">MAIN</span> sub but the resulting exit code will always be zero (success). To provide an exit code different from 0, call <a href="https://docs.perl6.org/routine/exit">exit</a>.</p>
<pre class="code">#|(optional description for USAGE message)
sub MAIN( Int :$length = 24,
:file($data) where { .IO.f // die &quot;file not found in $*CWD&quot; } = 'file.dat',
Bool :v(:$verbose) #`( either --verbose or -v ) )
{
say $length if $length.defined;
say $data if $data.defined;
say 'Verbosity ', ($verbose ?? 'on' !! 'off');
exit 1;
}</pre>
<a name="t17.8.1"></a> <h2 id="_language_functions.pod6-%*SUB-MAIN-OPTS"><span class="code">%*SUB-MAIN-OPTS</span></h2>
<p>It's possible to alter how arguments are processed before they're passed to <span class="code">sub MAIN {}</span> by setting options in <span class="code">%*SUB-MAIN-OPTS</span> hash. Due to the nature of dynamic variables, one needs to set up its own <span class="code">%*SUB-MAIN-OPTS</span> hash and fill it with the appropriate settings. For instance:</p>
<pre class="code">my %*SUB-MAIN-OPTS =
:named-anywhere, # allow named variables at any location
:!foo, # don't allow foo
;
sub MAIN ($a, $b, :$c, :$d) {
say &quot;Accepted!&quot;
}</pre>
<p>Available options are:</p>
<a name="t17.8.1.1"></a> <h3 id="_language_functions.pod6-named-anywhere"><span class="code">named-anywhere</span></h3>
<p>By default, named arguments to the program cannot be given after any positional arguments are specified. However, if <span class="code">%*SUB-MAIN-OPTS&lt;named-anywhere&gt;</span> is set to a truthy value, named arguments can be specified anywhere, even after positional parameter. For example, the above program can be called with:</p>
<pre class="code">perl6 example.p6 1 --c=2 3 --d=4
</pre>
<a name="t17.9"></a> <h1 id="_language_functions.pod6-sub_USAGE">sub USAGE</h1>
<p><a id="i131" name="USAGE"></a><span class="indexed"></span><a id="i132" name="$*USAGE"></a><span class="indexed"></span></p>
<p>If no multi candidate of <span class="code">MAIN</span> is found for the given command line parameters, the sub <span class="code">USAGE</span> is called. If no such method is found, the compiler will output a default generated usage message.</p>
<pre class="code">#|(is it the answer)
multi MAIN(Int $i){ say $i == 42 ?? 'answer' !! 'dunno' }
#|(divide two numbers)
multi MAIN($a, $b){ say $a/$b }
sub USAGE(){
print Q:c:to/EOH/;
Usage: {$*PROGRAM-NAME} [number]
Prints the answer or 'dunno'.
EOH
}</pre>
<p>The default usage message is available inside <span class="code">sub USAGE</span> via read-only <span class="code">$*USAGE</span> variable. It will be generated based on available <span class="code">sub MAIN</span> candidates and their parameters. You can specify additional extended description for each candidate using <span class="code">#|(...)</span> Pod block to set <a href="#_routine_WHY.pod6"><span class="code">WHY</span></a>.</p>
</div>
<!-- /language/glossary.pod6 --><div class="pod-body"><a id="_language_glossary.pod6"></a><a name="t18"></a><h1 class="title">18 Glossary</h1> <p class="subtitle">Glossary of Perl 6 terminology</p> <a name="t18.1"></a> <h1 id="_language_glossary.pod6-Abstract_Class">Abstract Class <a name="133"></a></h1>
<p>The generic Computer Science term &quot;abstract class&quot; defines the <a href="#17-Interface">interface</a> or <a href="#17-API">#API</a> of a class. In Perl 6, this is implemented using <a href="#17-Roles">roles</a> with <a href="#17-Stub">stubbed</a> methods.</p>
<pre class="code">role Canine {
method bark { ... } # the ... indicates a stub
}
class Dog does Canine {
method bark { say &quot;woof&quot; } # *MUST* be implemented by class
}</pre>
<a name="t18.2"></a> <h1 id="_language_glossary.pod6-Advent_Calendar">Advent Calendar <a name="134"></a></h1>
<p>In the context of Perl 6, a yearly set of blog posts for each day from the 1st until the 25th of December, to be found at <a href="https://perl6advent.wordpress.com">https://perl6advent.wordpress.com</a>.</p>
<a name="t18.3"></a> <h1 id="_language_glossary.pod6-Adverb">Adverb <a name="135"></a></h1>
<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&quot;foo bar&quot;; # &quot;:w&quot; is a Quotelike form modifier adverb
m:g/a|b|c/; # &quot;:g&quot; is also</pre>
TODO: Add this back in when :rotate on infix operators is supported
4 +&gt; 5 :rotate # &quot;:rotate&quot; is an operator adverb
@h{3}:exists; # &quot;:exists&quot; is also, but is known as a subscript adverb
<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 &quot;a&quot; =&gt; 4</pre>
<p>Some other forms that use a colon in ways that have adverb-like semantics are called adverbial forms. One special form starts with an integer value, followed by a name (for the key):</p>
<pre class="code">:20seconds # same as seconds =&gt; 20</pre>
<p>Also see <a href="#17-Colon Pair and Colon List">#Colon Pair and Colon List</a>.</p>
<a name="t18.4"></a> <h1 id="_language_glossary.pod6-Adverbial_Pair">Adverbial Pair <a name="136"></a></h1>
<p>A generalized form of <span class="code">pair notation</span>. They all start with the colon, like:</p>
<table>
<tr><th>adverbial pair</th> <th>pair notation</th></tr>
<tr><td>:foo&lt;bar&gt;</td> <td>foo =&gt; 'bar'</td></tr>
<tr><td>:foo(42)</td> <td>foo =&gt; 42</td></tr>
<tr><td>:42foo</td> <td>foo =&gt; 42</td></tr>
<tr><td>:$foo</td> <td>foo =&gt; $foo</td></tr>
<tr><td>:foo</td> <td>foo =&gt; True</td></tr>
<tr><td>:!foo</td> <td>foo =&gt; False</td></tr>
</table> <p>Also see <a href="#17-Adverb">#Adverb</a> and <a href="#17-Colon Pair and Colon List">#Colon Pair and Colon List</a>.</p>
<a name="t18.5"></a> <h1 id="_language_glossary.pod6-Allomorph">Allomorph <a name="137"></a></h1>
<p>A type that has two related values which may be used depending on the context. For example <a href="#_type_IntStr.pod6">IntStr</a> allomorph <span class="code">is</span> both an <a href="#_type_Int.pod6">Int</a> and a <a href="#_type_Str.pod6">Str</a>, so it will be accepted by anything that expects an <span class="code">Int</span>, a <span class="code">Str</span>, or an <span class="code">IntStr</span>. Keep in mind that certain constructs, such as <a href="#_language_setbagmix.pod6">sets, bags, and mixes</a> care about object identity, and so will not accept an allomorph as equivalent of its components alone.</p>
<p>The <i>allomorph</i> types <a href="#_type_IntStr.pod6">IntStr</a>, <a href="#_type_NumStr.pod6">NumStr</a>, <a href="#_type_RatStr.pod6">RatStr</a> and <a href="#_type_ComplexStr.pod6">ComplexStr</a> may be created as a result of parsing a quoted string:</p>
<pre class="code">say &lt;42&gt;.^name; # OUTPUT: «IntStr␤»
say &lt;42.1e0&gt;.^name; # OUTPUT: «NumStr␤»
say &lt;42.1&gt;.^name; # OUTPUT: «RatStr␤»</pre>
<p>Note: angle brackets can also be used to create literals for which you'd normally need to use some operator (e.g. <span class="code">/</span> for <a href="#_type_Rat.pod6">Rat</a> or <span class="code">+</span> for <a href="#_type_Complex.pod6">Complex</a>). This allows you to use such literals in places where expressions are not allowed, for example, as literals in signatures:</p>
<pre class="code"> # Wrong, can't use an operator there:
multi foo (1/3) { say &quot;It's one third!&quot; }
</pre>
<pre class="code"> # Right, a Rat literal:
multi foo (&lt;1/3&gt;) { say &quot;It's one third!&quot; }
</pre>
<p>If you <i>do</i> want an allomorph and not a literal <a href="#_type_Numeric.pod6">Numeric</a>, then include whitespace around angle brackets:</p>
<pre class="code">say &lt;42/1&gt;.^name; # OUTPUT: «Rat␤»
say &lt;42+0i&gt;.^name; # OUTPUT: «Complex␤»
say &lt; 42+0i &gt;.^name; # OUTPUT: «ComplexStr␤»
say &lt; 42/1 &gt;.^name; # OUTPUT: «RatStr␤»</pre>
<a name="t18.6"></a> <h1 id="_language_glossary.pod6-Anonymous">Anonymous <a name="138"></a></h1>
<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, but you cannot call it by that name:</p>
<pre class="code"> # anonymous, but knows its own name
my $s = anon sub triple($x) { 3 * $x }
say $s.name; # OUTPUT: «triple␤»
</pre>
<pre class="code"> say triple(42); # OUTPUT: «Undeclared routine: triple␤»
</pre>
<a name="t18.7"></a> <h1 id="_language_glossary.pod6-API">API <a name="139"></a></h1>
<p>Application Programming Interface. Ideally, someone using your system or library should be able to do so with knowledge only of the API, but not necessarily knowing anything about the internals or implementation.</p>
<p>See also <a href="#17-Abstract Class">#Abstract Class</a>.</p>
<a name="t18.8"></a> <h1 id="_language_glossary.pod6-Apocalypse">Apocalypse <a name="140"></a></h1>
<p>A document originally written by <a href="#17-TimToady">#TimToady</a>, in which he processed the initial barrage of RFCs that came out of the Perl community. Now only kept as an historical document for reference. See also <a href="#17-Exegesis">#Exegesis</a> and <a href="#17-Synopsis">#Synopsis</a>.</p>
<a name="t18.9"></a> <h1 id="_language_glossary.pod6-Arity">Arity <a name="141"></a></h1>
<p>The number of <a href="#_type_Positional.pod6">positional</a> operands expected by an <a href="#17-Operator">operator</a>, subroutine, method or callable block.</p>
<pre class="code">sub infix:&lt;+&gt;(Foo $a, Foo $b) { $a.Int + $b.Int } # arity of &quot;+&quot; is 2
sub frobnicate($x) { ... } # arity of 1
sub the-answer() { 42 } # arity of 0
-&gt; $key, $value { ... } # arity of 2
</pre>
<p>The arity of a <span class="code">Callable</span> is one of the main selectors in <a href="#17-Multi-Dispatch">multi-dispatch</a>.</p>
<a name="t18.10"></a> <h1 id="_language_glossary.pod6-Autothreading">Autothreading <a name="142"></a></h1>
<p>Autothreading is what happens if you pass a <a href="#_type_Junction.pod6">Junction</a> to a subroutine that expects a parameter of type <a href="#_type_Any.pod6">Any</a> or a subtype thereof (such as anything <a href="#_type_Cool.pod6">Cool</a>). The call is then executed for each value of the junction. The result of these calls is assembled in a new junction of the same type as the original junction.</p>
<pre class="code">sub f($x) { 2 * $x };
say f(1|2|3) == 4; # OUTPUT: «any(False, True, False)␤»</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>. These are then all compared to <span class="code">4</span>, resulting in a junction <span class="code">False|True|False</span>. This process of separating junction arguments into multiple calls to a function is called <i>autothreading</i>.</p>
<p>If you use the resulting junction in a boolean context, such as with an <span class="code">if</span>, it collapses into a single boolean which is <span class="code">True</span> if any of the values in the junction are True.</p>
<pre class="code"> if f(1|2|3) == 4 { # fires because f(2) == 4 is true
say 'success';
}
</pre>
<a name="t18.11"></a> <h1 id="_language_glossary.pod6-Backtracking">Backtracking <a name="143"></a></h1>
<p>Backtracking is the default way a regexp is matched. The engine is allowed to explore several ways moving backward in the string characters in order to allow every piece of a regexp to match something. For more information see <a href="#_language_regexes.pod6-backtracking">Regexp Backtracking section</a>.</p>
<a name="t18.12"></a> <h1 id="_language_glossary.pod6-binder">binder</h1>
<p>When you pass an argument list to a function (or any other callable, like a method or a block), the argument list gets bound to the parameters in the signature. The code that does this is called the <i>binder</i>.</p>
<a name="t18.13"></a> <h1 id="_language_glossary.pod6-block">block <a name="144"></a></h1>
<a name="t18.14"></a> <h1 id="_language_glossary.pod6-bytecode">bytecode <a name="145"></a></h1>
<a name="t18.15"></a> <h1 id="_language_glossary.pod6-Camelia">Camelia <a name="146"></a></h1>
<p>A butterfly image intended primarily to represent Perl 6, The Language.</p>
<a name="t18.16"></a> <h1 id="_language_glossary.pod6-Colon_Pair_and_Colon_List">Colon Pair and Colon List <a name="147"></a> <a name="148"></a></h1>
<p>A colon pair is a shorthand syntax used to create or visually present a <a href="#_type_Pair.pod6">Pair</a> object. The two most common forms are:</p>
<pre class="code">:a(4) # Same as &quot;a&quot; =&gt; 4, same as Pair.new(&quot;a&quot;, 4)
:a&lt;4&gt; # Same as &quot;a&quot; =&gt; &quot;4&quot;, same as Pair.new(&quot;a&quot;, &quot;4&quot;)</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 =&gt; 4, c =&gt; True, d =&gt; False, c =&gt; True</pre>
<p>Finally, if there is a variable with the same name as an intended adverbial pair, you don't have to specify the name twice, but just specify the adverb with the appropriate sigil:</p>
<pre class="code">:$foo # same as foo =&gt; $foo
:@bar # same as bar =&gt; @bar
:%mapper # same as mapper =&gt; %mapper
:&amp;test # same as test =&gt; &amp;test
</pre>
<p>See also <a href="#17-Adverb">#Adverb</a>.</p>
<a name="t18.17"></a> <h1 id="_language_glossary.pod6-Community_Community">Community <a name="149"></a>Community</h1>
<p>See <a href="https://perl6.org/community/">https://perl6.org/community/</a> for information about how to participate in the friendly Perl 6 community.</p>
<a name="t18.18"></a> <h1 id="_language_glossary.pod6-Damian_Conway">Damian Conway</h1>
<p>Original author of the <a href="#17-Exegesis">#Exegesis</a> (among many other things). See also <a href="https://en.wikipedia.org/wiki/Damian_Conway">https://en.wikipedia.org/wiki/Damian_Conway</a>.</p>
<a name="t18.19"></a> <h1 id="_language_glossary.pod6-diffy">diffy <a name="150"></a></h1>
<p>See <a href="#17-Operator">operator</a>. It means the type of the operator result is sufficiently different from its arguments that op= makes little sense</p>
<a name="t18.20"></a> <h1 id="_language_glossary.pod6-Exegesis">Exegesis <a name="151"></a></h1>
<p>A document originally written by <a href="#17-TheDamian">#TheDamian</a>, in which he tried to explain the <a href="#17-Apocalypse">Apocalypses</a> to the common (wo)man. Now only kept as an historical document for reference. See also <a href="#17-Synopsis">#Synopsis</a>.</p>
<a name="t18.21"></a> <h1 id="_language_glossary.pod6-fiddly">fiddly <a name="152"></a></h1>
<p>Too complicated to apply a meta-op to. See <a href="#17-Operator">operator</a>.</p>
<a name="t18.22"></a> <h1 id="_language_glossary.pod6-Huffmanize">Huffmanize</h1>
<p>With reference to <a href="https://en.wikipedia.org/wiki/Huffman_coding">Huffman coding</a>, &quot;huffmanizing&quot; is making things that are commonly used easier, and often shorter, to type. With things that are used less frequently it's both less of a bother to type longer pieces of code and often longer, more descriptive naming is necessary to easily be reminded of what the rarely-used feature does.</p>
<p>For example, printing output is a common task, while performing thread-safe atomic addition on native atomicity-safe integers is much less so. There's a need to &quot;huffmanize&quot; the task printing and that's why you can do it by just typing three letters <a href="#_routine_put.pod6">put</a>. But there's no need to &quot;huffmanize&quot; the rarely-needed atomic operators, which is why you type the lengthier names, such as <a href="#_routine_atomic-inc-fetch.pod6">atomic-inc-fetch</a>. <a href="#_routine_put.pod6">put</a> is a bit of a vague name, but because it's commonly used, it's easy to learn what it does. <a href="#_routine_atomic-inc-fetch.pod6">atomic-inc-fetch</a>, on the other hand is rarer, and the more descriptive name helps recall its purpose better.</p>
<a name="t18.23"></a> <h1 id="_language_glossary.pod6-iffy">iffy <a name="153"></a></h1>
<p>Often used as a boolean value. See <a href="#17-Operator">operator</a>.</p>
<a name="t18.24"></a> <h1 id="_language_glossary.pod6-Instance">Instance <a name="154"></a></h1>
<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 = &quot;hello&quot;; ## this is with builtin types, e.g. Str
if defined($str) {
say &quot;Oh, yeah. I'm defined.&quot;;
}
else {
say &quot;No. Something off? &quot;;
}
## 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="t18.25"></a> <h1 id="_language_glossary.pod6-Interface">Interface <a name="155"></a></h1>
<p>An interface is an <a href="#17-Abstract Class">abstract class</a>.</p>
<a name="t18.26"></a> <h1 id="_language_glossary.pod6-IRC">IRC <a name="156"></a></h1>
<p>Internet Relay Chat. Perl 6 developers and users usually hang out on the <span class="code">#perl6</span> channel of <span class="code">irc.freenode.org</span>. Currently available bots are:</p>
<a name="t18.26.1"></a> <h2 id="_language_glossary.pod6-camelia">camelia <a name="157"></a></h2>
<p>The <a href="#17-Bot">#Bot</a> on the #perl6 <a href="#17-IRC">#IRC</a> channel that evaluates code, e.g.:</p>
<pre class="code">[16:28:27] &lt;lizmat&gt; m: say &quot;Hello world&quot;
[16:28:28] &lt;+camelia&gt; rakudo-moar 812a48: OUTPUT«Hello world␤»
</pre>
<p>This is a handy tool for showing people if the output is (un)expected.</p>
<a name="t18.26.2"></a> <h2 id="_language_glossary.pod6-dalek">dalek <a name="158"></a></h2>
<p>The <a href="#17-Bot">#Bot</a> on the #perl6 <a href="#17-IRC">#IRC</a> channel that reports changes made to various Perl 6 related <a href="#17-Repository">repositories</a>.</p>
<pre class="code">[15:46:40] &lt;+dalek&gt; doc: 2819f25 | lizmat++ | doc/Language/glossary.pod:
[15:46:40] &lt;+dalek&gt; doc: Add stubs for stuff inside the glossary already
[15:46:40] &lt;+dalek&gt; doc: review: https://github.com/perl6/doc/commit/2819f250
</pre>
<a name="t18.26.3"></a> <h2 id="_language_glossary.pod6-yoleaux">yoleaux <a name="159"></a></h2>
<p>The <a href="#17-Bot">#Bot</a> on the #perl6 <a href="#17-IRC">#IRC</a> channel that provides various services to people logged in. Commands to yoleaux (a pun on YOLO) start with a period. Some often used commands are:</p>
<a name="t18.26.3.1"></a> <h3 id="_language_glossary.pod6-.tell">.tell</h3>
<p>Leave a message to another user who is currently not logged in. The message will be relayed as soon as the user says anything on the channel.</p>
<pre class="code">.tell lizmat I've read the glossary
</pre>
<a name="t18.26.3.2"></a> <h3 id="_language_glossary.pod6-.u">.u</h3>
<p>Look up unicode codepoint information from either a codepoint, or the name of a codepoint.</p>
<pre class="code">[16:35:44] &lt;lizmat&gt; .u empty set
[16:35:45] &lt;yoleaux&gt; U+2205 EMPTY SET [Sm] (∅)
[16:36:29] &lt;lizmat&gt; .u ∅
[16:36:30] &lt;yoleaux&gt; U+2205 EMPTY SET [Sm] (∅)
</pre>
<p>Some <a href="#17-IRC">#IRC</a> clients then easily allow you to copy/paste the codepoint in question, which can be sometimes be easier than other unicode codepoint input methods.</p>
<a name="t18.27"></a> <h1 id="_language_glossary.pod6-IRC_Lingo">IRC Lingo</h1>
<p>The following terms are often used on the Perl 6 related <a href="#17-IRC">#IRC</a> channels:</p>
<a name="t18.27.1"></a> <h2 id="_language_glossary.pod6-ALAP">ALAP <a name="160"></a></h2>
<p>As Late As Possible</p>
<a name="t18.27.2"></a> <h2 id="_language_glossary.pod6-autopun">autopun <a name="161"></a></h2>
<p>A self-referencing pun, e.g. &quot;Are you ignorant or apathetic?&quot; - &quot;I don't know, and I don't care.&quot;</p>
<a name="t18.27.3"></a> <h2 id="_language_glossary.pod6-backlog">backlog <a name="162"></a></h2>
<p>That part of a discussion on an <a href="#17-IRC">#IRC</a> channel that you've missed. If it is not or no longer available in your IRC client, you can go to sites such as <a href="http://irc.perl6.org">http://irc.perl6.org</a> to see what has been logged for you.</p>
<a name="t18.27.4"></a> <h2 id="_language_glossary.pod6-Bot">Bot <a name="163"></a></h2>
<p>A program that does automatic tasks on one or more <a href="#17-IRC">#IRC</a> channels by acting like a regular user (as far as the IRC server is concerned) and performing some tasks that may involve answering to users requests. Examples are <a href="#17-camelia">#camelia</a>, <a href="#17-dalek">#dalek</a> and <a href="#17-yoleaux">#yoleaux</a>.</p>
<a name="t18.27.5"></a> <h2 id="_language_glossary.pod6-DWIM">DWIM <a name="164"></a></h2>
<p>Do What I Mean. A programming language designer motto.</p>
<a name="t18.27.6"></a> <h2 id="_language_glossary.pod6-flap">flap <a name="165"></a></h2>
<p>Sometimes a test will fail under some conditions, but not others; when this test passes some test runs and fails others, it's called flapping.</p>
<a name="t18.27.7"></a> <h2 id="_language_glossary.pod6-fossil">fossil <a name="166"></a></h2>
<p>Something in a generally current document that is no longer true but which has not yet been fixed by correcting or removing it.</p>
<a name="t18.27.8"></a> <h2 id="_language_glossary.pod6-FSVO">FSVO <a name="167"></a></h2>
<p>For Some Value Of...</p>
<a name="t18.27.9"></a> <h2 id="_language_glossary.pod6-FTFY">FTFY <a name="168"></a></h2>
<p>Fixed That For You</p>
<a name="t18.27.10"></a> <h2 id="_language_glossary.pod6-IIRC">IIRC <a name="169"></a></h2>
<p>If I Read (or Remember) Correctly</p>
<a name="t18.27.11"></a> <h2 id="_language_glossary.pod6-IMHO">IMHO <a name="170"></a></h2>
<p>In My Humble Opinion</p>
<a name="t18.27.12"></a> <h2 id="_language_glossary.pod6-IWBN">IWBN <a name="171"></a></h2>
<p>It Would Be Nice</p>
<a name="t18.27.13"></a> <h2 id="_language_glossary.pod6-LHF">LHF <a name="172"></a></h2>
<p>Low Hanging Fruit. Usually used in the context of a (relatively) simple task to be performed by a (relative) newbie.</p>
<a name="t18.27.14"></a> <h2 id="_language_glossary.pod6-LGTM">LGTM <a name="173"></a></h2>
<p>Looks Good To Me</p>
<a name="t18.27.15"></a> <h2 id="_language_glossary.pod6-LTA">LTA <a name="174"></a></h2>
<p>Less Than Awesome. Usually used in the context of an error message that is rather non-descriptive or unrelated to the actual error.</p>
<a name="t18.27.16"></a> <h2 id="_language_glossary.pod6-NST">NST <a name="175"></a></h2>
<p>No Such Thing</p>
<a name="t18.27.17"></a> <h2 id="_language_glossary.pod6-Opt">Opt <a name="176"></a></h2>
<p>Short for &quot;optimization&quot;, usually in either the context of <a href="#17-Spesh">spesh</a> or JIT.</p>
<a name="t18.27.18"></a> <h2 id="_language_glossary.pod6-PB">PB <a name="177"></a></h2>
<p>Short for &quot;problem&quot;. As in &quot;that's not the pb&quot;.</p>
<a name="t18.27.19"></a> <h2 id="_language_glossary.pod6-PR">PR <a name="178"></a></h2>
<p>See <a href="#17-Pull Request">#Pull Request</a>.</p>
<a name="t18.27.20"></a> <h2 id="_language_glossary.pod6-P5">P5 <a name="179"></a></h2>
<p>Perl 5</p>
<a name="t18.27.21"></a> <h2 id="_language_glossary.pod6-P6">P6 <a name="180"></a></h2>
<p>Perl 6</p>
<a name="t18.27.22"></a> <h2 id="_language_glossary.pod6-RSN">RSN <a name="181"></a></h2>
<p>Real Soon Now</p>
<a name="t18.27.23"></a> <h2 id="_language_glossary.pod6-RT">RT <a name="182"></a></h2>
<p>Request Tracker (<a href="http://rt.perl.org/">http://rt.perl.org/</a>). The place where all the bugs related to <a href="#17-Rakudo">#Rakudo</a> live.</p>
<a name="t18.27.24"></a> <h2 id="_language_glossary.pod6-TIMTOWTDI">TIMTOWTDI <a name="183"></a></h2>
<p>An alternative form of <a href="#17-TMTOWTDI">#TMTOWTDI</a>, explicitly including the &quot;is&quot; from the contraction &quot;There's&quot;.</p>
<a name="t18.27.25"></a> <h2 id="_language_glossary.pod6-TMI">TMI <a name="184"></a></h2>
<p>Too Much Information.</p>
<a name="t18.27.26"></a> <h2 id="_language_glossary.pod6-TMTOWTDI">TMTOWTDI <a name="185"></a></h2>
<p>&quot;There's More Than One Way To Do It&quot;, the Perl motto.</p>
<a name="t18.27.27"></a> <h2 id="_language_glossary.pod6-UGT">UGT <a name="186"></a></h2>
<p>&quot;Universal Greeting Time&quot; - i.e., it's always &quot;morning&quot;.</p>
<a name="t18.27.28"></a> <h2 id="_language_glossary.pod6-WFM">WFM <a name="187"></a></h2>
<p>Works For Me</p>
<a name="t18.27.29"></a> <h2 id="_language_glossary.pod6-WIP">WIP <a name="188"></a></h2>
<p>Work In Progress</p>
<a name="t18.27.30"></a> <h2 id="_language_glossary.pod6-WP">WP <a name="189"></a></h2>
<p>Wikipedia</p>
<a name="t18.27.31"></a> <h2 id="_language_glossary.pod6-WW">WW <a name="190"></a></h2>
<p>Short for <span class="code">wrong window</span>. When on <a href="#17-IRC">#IRC</a>, someone types something in a channel that was intended for another channel, or for a private message.</p>
<a name="t18.28"></a> <h1 id="_language_glossary.pod6-Larry_Wall">Larry Wall</h1>
<p><a href="#17-Perl">Perl's</a> benevolent dictator for life, among many other things. See also <a href="https://en.wikipedia.org/wiki/Larry_Wall">https://en.wikipedia.org/wiki/Larry_Wall</a>.</p>
<a name="t18.29"></a> <h1 id="_language_glossary.pod6-Lexing">Lexing <a name="191"></a></h1>
<a name="t18.30"></a> <h1 id="_language_glossary.pod6-Literal">Literal <a name="192"></a></h1>
<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
my $s = &quot;Foo&quot;; # the &quot;Foo&quot; is a literal, the $s is a variable</pre>
<a name="t18.31"></a> <h1 id="_language_glossary.pod6-lvalue">lvalue <a name="193"></a></h1>
<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>
<table>
<tr><th>Declaration</th> <th>lvalue</th> <th>Comments</th></tr>
<tr><td>my $x;</td> <td>$x</td> <td></td></tr>
<tr><td>my ($a, $b);</td> <td>($a, $b)</td> <td></td></tr>
<tr><td>has $!attribute;</td> <td>$!attribute</td> <td>Only inside classes</td></tr>
<tr><td>has $.attrib is rw;</td> <td>$.attrib</td> <td></td></tr>
<tr><td>sub a is rw { $x };</td> <td>a()</td> <td></td></tr>
</table> <p>Examples of things that are not lvalues:</p>
<table>
<tr><td>3</td> <td>literals</td></tr>
<tr><td>constant x = 3;</td> <td>constants</td></tr>
<tr><td>has $.attrib;</td> <td>attributes; you can only assign to $!attrib</td></tr>
<tr><td>sub f { }; f();</td> <td>&quot;normal&quot; subs are not writable</td></tr>
<tr><td>sub f($x) { $x = 3 };</td> <td>error - parameters are read-only by default</td></tr>
</table> <p>These are typically called <a href="#17-rvalue">rvalues</a>.</p>
<a name="t18.32"></a> <h1 id="_language_glossary.pod6-Mainline">Mainline <a name="194"></a></h1>
<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.c; # mainline
sub f {
# not in mainline, in sub f
}
f(); # in mainline again</pre>
<p>You can also have the mainline of any package-like declarator, such as class, <a href="#_language_modules.pod6">module</a>, <a href="#_language_grammars.pod6">grammar</a>, etc. These are typically run just after the class/module/grammar have been compiled (or when loaded from a pre-compiled file).</p>
<a name="t18.33"></a> <h1 id="_language_glossary.pod6-MoarVM">MoarVM <a name="195"></a></h1>
<p>MoarVM is short for Metamodel On A Runtime Virtual Machine. It's a virtual machine designed specifically for <a href="#17-NQP">#NQP</a> and its <a href="#_language_mop.pod6">MOP</a>: <a href="#17-6model">#6model</a>. A document about <a href="https://github.com/MoarVM/MoarVM/blob/master/docs/reveal.md">the purpose of MoarVM</a>. MoarVM has some similarities with the Hotspot VM so you may peruse its <a href="http://openjdk.java.net/groups/hotspot/docs/HotSpotGlossary.html">glossary</a> for entries missing from the present one.</p>
<a name="t18.34"></a> <h1 id="_language_glossary.pod6-Multi-Dispatch">Multi-Dispatch <a name="196"></a><a name="197"></a></h1>
<p>The process of picking a candidate for calling of a set of <a href="#_type_Method.pod6">methods</a> or <a href="#_type_Sub.pod6">subs</a> that come by the same name but with different arguments. The most narrow candidate wins. In case of an ambiguity, a routine with <span class="code">is default</span> trait will be chosen if one exists, otherwise an exception is thrown.</p>
<a name="t18.35"></a> <h1 id="_language_glossary.pod6-multi-method">multi-method <a name="198"></a></h1>
<p>A <a href="#_type_Method.pod6">method</a> that has multiple candidates going by the same name and are subject to <a href="#17-Multi-Dispatch">Multi-Dispatch</a>.</p>
<a name="t18.36"></a> <h1 id="_language_glossary.pod6-Niecza">Niecza <a name="199"></a></h1>
<p>An implementation of Perl 6 targeting the .NET platform. No longer actively maintained.</p>
<a name="t18.37"></a> <h1 id="_language_glossary.pod6-Not_Quite_Perl">Not Quite Perl <a name="200"></a></h1>
<p>See <a href="#17-NQP">#NQP</a>.</p>
<a name="t18.38"></a> <h1 id="_language_glossary.pod6-NQP">NQP <a name="201"></a></h1>
<p>NQP is a primitive language for writing subroutines and methods using a subset of the Perl 6 syntax. It's not intended to be a full-fledged programming language, nor does it provide a runtime environment beyond the basic VM primitives. Compilers (such as <a href="#17-Rakudo">#Rakudo</a> typically use NQP to compile action methods that convert a parse tree into its equivalent abstract syntax tree representation.</p>
<a name="t18.39"></a> <h1 id="_language_glossary.pod6-NYI">NYI <a name="202"></a></h1>
<p>Not Yet Implemented</p>
<a name="t18.40"></a> <h1 id="_language_glossary.pod6-opcode">opcode <a name="203"></a></h1>
<a name="t18.41"></a> <h1 id="_language_glossary.pod6-Operator">Operator <a name="204"></a></h1>
<p>An expression is made of operators and operands. More precisely it is made of an operator and operands that can be subexpressions or <a href="#17-value">#value</a>s. Operators are an alternative syntax for a <a href="#17-multi-method">#multi-method</a>. With that syntax, what would be the arguments of the function are named operands instead. Operators are classified into <a href="https://design.perl6.org/S02.html#Grammatical_Categories">categories</a> of categories. A category has a precedence, an arity, and can be <a href="#17-fiddly">#fiddly</a>, <a href="#17-iffy">#iffy</a>, <a href="#17-diffy">#diffy</a>. Perl 6 is very creative as to what is an operator, so there are many categories. Operators are made of many tokens, possibly with a subexpression. For example, <span class="code">@a[0]</span> belongs to the postcircumfix category, is broken into the operand <span class="code">@a</span> and the postcircumfix operator <span class="code">[0]</span> where <span class="code">0</span> is the postcircumfixed subexpression.</p>
<p>The <span class="code">&lt;O(I&lt;...&gt;)&gt; </span> construction gives information about an operator that completes the information provided by its category. Below <span class="code">%conditional</span> is the category, <span class="code">:reducecheck&lt;ternary&gt; </span>, which specifies calling <span class="code">.ternary</span> to post-process the <a href="#17-Parse Tree">parse subtree</a> and <span class="code">:pasttype&lt;if&gt; </span> specifies the NQP <a href="#17-opcode">#opcode</a> generated in the AST from the parse subtree.</p>
<pre class="code">&lt;O('%conditional, :reducecheck&lt;ternary&gt;, :pasttype&lt;if&gt;')&gt;</pre>
<a name="t18.42"></a> <h1 id="_language_glossary.pod6-Parse_Tree">Parse Tree <a name="205"></a></h1>
<a name="t18.43"></a> <h1 id="_language_glossary.pod6-Parameter">Parameter <a name="206"></a></h1>
<p><a href="#_type_Parameter.pod6">Parameter</a> is a class to define parameters to subroutines, method and a <a href="#_type_Callable.pod6">callable blocks</a>. As opposed to the arguments you specify when calling a subroutine/method/callable block.</p>
<pre class="code">sub foo($bar) { say $bar } # $bar is a parameter
foo(42); # 42 is an argument</pre>
<a name="t18.44"></a> <h1 id="_language_glossary.pod6-Parrot">Parrot <a name="207"></a></h1>
<p>A <a href="#17-Virtual Machine">virtual machine</a> designed to run Perl 6 and other dynamic languages. No longer actively maintained.</p>
<a name="t18.45"></a> <h1 id="_language_glossary.pod6-PAST">PAST <a name="208"></a></h1>
<p><a href="#17-Parrot">#Parrot</a> AST.</p>
<a name="t18.46"></a> <h1 id="_language_glossary.pod6-Perl">Perl <a name="209"></a></h1>
<p>The Perl programming language in its many forms.</p>
<a name="t18.47"></a> <h1 id="_language_glossary.pod6-PERL">PERL <a name="210"></a></h1>
<p>A way to describe <a href="#17-Perl">Perl</a> as a language, considered to be improper by many in the <a href="#_language_community.pod6">Perl Community</a>.</p>
<a name="t18.48"></a> <h1 id="_language_glossary.pod6-POD">POD <a name="211"></a></h1>
<p><b>P</b>lain <b>O</b>l' <b>D</b>ocumentation, a documentation format understood by Perl 6. See <a href="https://design.perl6.org/S26.html">S26</a> for details.</p>
<a name="t18.49"></a> <h1 id="_language_glossary.pod6-Pull_Request">Pull Request <a name="212"></a></h1>
<p>A feature of <a href="https://github.com">https://github.com</a> that allows you to make patches to be easily applied using the Github user interface. It means you request someone to do a git pull from your <a href="#17-Repository">repository</a> to hers. In GitHub, it can be done automatically through the web interface. PR is its usual acronym.</p>
<a name="t18.50"></a> <h1 id="_language_glossary.pod6-pugs">pugs <a name="213"></a></h1>
<p><a href="https://en.wikipedia.org/wiki/Pugs">pugs</a> was one of the first interpreters/compilers written for Perl 6. It was written in Haskell by Audrey Tang.</p>
<a name="t18.51"></a> <h1 id="_language_glossary.pod6-QAST">QAST <a name="214"></a></h1>
<p>Successor to <a href="#17-PAST">#PAST</a> ('Q' being the next letter after 'P').</p>
<a name="t18.52"></a> <h1 id="_language_glossary.pod6-Rakudo">Rakudo <a name="215"></a></h1>
<p>Rakudo is the name of a Perl 6 implementation that runs on <a href="#17-MoarVM">#MoarVM</a> and the JVM. It is an abbreviation of <span class="code">Rakuda-do</span>, which, when translated from Japanese, means &quot;The Way of the Camel&quot;. Also, in Japanese, &quot;Rakudo&quot; means &quot;Paradise.&quot;</p>
<a name="t18.53"></a> <h1 id="_language_glossary.pod6-Reify">Reify <a name="216"></a></h1>
<p>In English language, <a href="http://www.dictionary.com/browse/reify">reify means</a> to &quot;to convert into or regard as a concrete thing.&quot; Its meaning in Perl 6 is very similar, in that conceptual things, like &quot;elements of an infinite list&quot; get <i>reified</i> when you try to operate on some of them:</p>
<pre class="code"># A list containing infinite number of un-reified Fibonacci numbers:
my @fibonacci = 1, 1, * + * … ∞;
# We reify 10 of them, looking up the first 10 of them with array index:
say @fibonacci[^10]; # OUTPUT: «(1 1 2 3 5 8 13 21 34 55)␤»
# We reify 5 more: 10 we already reified on previous line, and we need to
# reify 5 more to get the 15th element at index 14. Even though we need only
# the 15th element, the original Seq still has to reify all previous elements:
say @fibonacci[14]; # OUTPUT: «987␤»</pre>
<p>Above we were reifying a <a href="#_type_Seq.pod6">Seq</a> we created with the <a href="#_language_operators.pod6-index-entry-%E2%80%A6_operators">sequence operator</a>, but other things use the concept as well. For example, an un-reified <a href="#_type_Range.pod6">Range</a> is just the two end points. In some languages, calculating the sum of a huge range is a lengthy and memory-consuming process, but Perl 6 calculates it instantly:</p>
<pre class="code">say sum 1 ..9_999_999_999_999; # OUTPUT: «49999999999995000000000000␤»</pre>
<p>Why? Because the sum can be calculated <i>without</i> reifying the Range; that is without figuring out all the elements it contains. This is why this feature exists. You can even make your own things you can reify-on-demand, using <a href="#_syntax_gather%20take.pod6"><span class="code">gather</span> and <span class="code">take</span></a>:</p>
<pre class="code">my $seq = gather {
say &quot;About to make 1st element&quot;; take 1;
say &quot;About to make 2nd element&quot;; take 2;
}
say &quot;Let's reify an element!&quot;;
say $seq[0];
say &quot;Let's reify more!&quot;;
say $seq[1];
say &quot;Both are reified now!&quot;;
say $seq[^2];
# OUTPUT:
# Let's reify an element!
# About to make 1st element
# 1
# Let's reify more!
# About to make 2nd element
# 2
# Both are reified now!
# (1 2)</pre>
<p>Following the output above, you can see the print statements <i>inside</i> the <span class="code">gather</span> got printed only when we reified the individual elements while looking up an element. Also note, the elements got reified just once. When we printed the same elements again on the last line of the example, the messages inside <span class="code">gather</span> we no longer printed. This is because the construct used already-reified elements from the <a href="#_type_Seq.pod6">Seq</a>'s cache.</p>
<p>Note that above we assigned the <span class="code">gather</span> to a <a href="#_type_Scalar.pod6">Scalar</a> container (the <span class="code">$</span> sigil), not the <a href="#_type_Positional.pod6">Positional</a> one (the <span class="code">@</span> sigil). The reason is that the <span class="code">@</span>-sigiled variables are <i>mostly lazy</i>. What this means is they <i>reify the stuff assigned to them</i> right away <i>most of the time</i>. The only time they don't do it is when the items are known to be <a href="#_routine_is-lazy.pod6"><span class="code">is-lazy</span></a>, like our sequence generated with infinity as the end point. Were we to assign the <span class="code">gather</span> to a <span class="code">@</span>-variable, the <span class="code">say</span> statements inside of it would've been printed right away.</p>
<p>Another way to fully-reify a list, is by calling <a href="#_routine_elems.pod6"><span class="code">.elems</span></a> on it. This is the reason why checking whether a list contains any items is best done by using <span class="code">.Bool</span> method (or just using <span class="code">if @array { … }</span>), since you don't need to reify <i>all</i> the elements to find out if there are <span class="code">any</span> of them.</p>
<p>There are times where you <i>do</i> want to fully-reify a list before doing something. For example, the <a href="#_type_IO::Handle.pod6-method_lines"><span class="code">IO::Handle.lines</span></a> returns a <a href="#_type_Seq.pod6">Seq</a>. The following code contains a bug; keeping reification in mind, try to spot it:</p>
<pre class="code"> my $fh = &quot;/tmp/bar&quot;.IO.open;
my $lines = $fh.lines;
close $fh;
say $lines[0];
</pre>
<p>We open a <a href="#_type_IO::Handle.pod6">file handle</a>, then assign return of <a href="#_type_IO::Handle.pod6-method_lines"><span class="code">.lines</span></a> to a <a href="#_type_Scalar.pod6">Scalar</a> variable, so the returned <a href="#_type_Seq.pod6">Seq</a> does not get reified right away. We then <a href="#_routine_close.pod6"><span class="code">close</span></a> the file handle, and try to print an element from <span class="code">$lines</span>.</p>
<p>The bug in the code is by the time we reify the <span class="code">$lines</span> <a href="#_type_Seq.pod6">Seq</a> on the last line, we've <i>already closed</i> the file handle. When the <span class="code">Seq's</span> iterator tries to generate the item we've requested, it results in the error about attempting to read from a closed handle. So, to fix the bug we can either assign to a <span class="code">@</span>-sigiled variable or call <a href="#_routine_elems.pod6"><span class="code">.elems</span></a> on <span class="code">$lines</span> before closing the handle:</p>
<pre class="code"> my $fh = &quot;/tmp/bar&quot;.IO.open;
my @lines = $fh.lines;
close $fh;
say @lines[0]; # no problem!
</pre>
<p>Also good:</p>
<pre class="code"> my $fh = &quot;/tmp/bar&quot;.IO.open;
my $lines = $fh.lines;
say &quot;Read $lines.elems() lines&quot;; #reifying before closing handle
close $fh;
say $lines[0]; # no problem!
</pre>
<a name="t18.54"></a> <h1 id="_language_glossary.pod6-Repository">Repository <a name="217"></a></h1>
<p>A filesystem under control of a source control management application, usually git, that holds the sources for a project, library or application. This file, for instance, is in <a href="https://github.com/perl6/doc">a GitHub repository</a>. Repositories store not only files, but also history of changes and can be used by the developing or writing team for interaction through issues or comments to code.</p>
<a name="t18.55"></a> <h1 id="_language_glossary.pod6-roast">roast <a name="218"></a></h1>
<p>The Perl 6 <a href="#17-test suite">specification tests</a>, which live here: <a href="https://github.com/perl6/roast/">https://github.com/perl6/roast/</a>. Originally developed for <a href="#17-pugs">#pugs</a>, it now serves all Perl 6 implementations. Why roast? It's the <b>r</b>epository <b>o</b>f <b>a</b>ll <b>s</b>pec <b>t</b>ests.</p>
<a name="t18.56"></a> <h1 id="_language_glossary.pod6-Roles">Roles <a name="219"></a></h1>
<p>Roles, mix-ins or traits define interfaces and/or implementation of those interfaces as well as instance variables using them, and are mixed-in when declaring classes that follow that interface. <a href="#17-Abstract Class">Abstract classes</a> are particular examples of Roles where the actual implementation is deferred to the class that uses that Role.</p>
<p>Roles are part of Perl6's <a href="#_language_objects.pod6">object system</a>, and are declared using the keyword <a href="#_syntax_role.pod6">role</a> and used in class declaration via <a href="#_syntax_does.pod6">does</a>.</p>
<a name="t18.57"></a> <h1 id="_language_glossary.pod6-rule">rule <a name="220"></a></h1>
<p>(Used in regular expressions)</p>
<a name="t18.58"></a> <h1 id="_language_glossary.pod6-rvalue">rvalue <a name="221"></a></h1>
<p>A value that can be used on the right hand side of an assignment. See also <a href="#17-lvalue">#lvalue</a>.</p>
<a name="t18.59"></a> <h1 id="_language_glossary.pod6-Sigil">Sigil <a name="222"></a></h1>
<p>In Perl, the sigil is the first character of a variable name. It must be either $, @, %, or &amp; respectively for a <a href="#_type_Scalar.pod6">scalar</a>, <a href="#_type_Array.pod6">array</a>, <a href="#_type_Hash.pod6">hash</a>, or <a href="#_type_Code.pod6">code</a> variable. See also Twigil and role. Also sigiled variables allow short conventions for <a href="#17-Variable Interpolation">variable interpolation</a> in a double quoted string, or even postcircumfix expressions starting with such a variable.</p>
<a name="t18.60"></a> <h1 id="_language_glossary.pod6-Sigilless_Variable">Sigilless Variable <a name="223"></a></h1>
<a name="t18.61"></a> <h1 id="_language_glossary.pod6-Spesh">Spesh <a name="224"></a></h1>
<p>A functionality of the <a href="#17-MoarVM">#MoarVM</a> platform that uses run-time gathered data to improve commonly used pieces of <a href="#17-bytecode">#bytecode</a>. It is much like a JIT compiler, except that those usually output machine code rather than bytecode.</p>
<a name="t18.62"></a> <h1 id="_language_glossary.pod6-STD">STD <a name="225"></a></h1>
<p>STD.pm is the &quot;standard&quot; Perl 6 grammar definition, see <a href="https://github.com/perl6/std/">https://github.com/perl6/std/</a> that was used to implement Perl 6. STD.pm is no longer really a &quot;specification&quot; in a proscriptive sense: it's more of a guideline or model for Perl 6 implementations to follow.</p>
<a name="t18.63"></a> <h1 id="_language_glossary.pod6-Stub">Stub <a name="226"></a></h1>
<a name="t18.64"></a> <h1 id="_language_glossary.pod6-Symbol">Symbol <a name="227"></a></h1>
<p>Fancy alternative way to denote a name. Generally used in the context of <a href="#_language_modules.pod6">module</a>s linking, be it in the OS level, or at the Perl 6 <a href="#17-Virtual Machine">#Virtual Machine</a> level for modules generated from languages targeting these VMs. The set of imported or exported symbols is called the symbol table.</p>
<a name="t18.65"></a> <h1 id="_language_glossary.pod6-Synopsis">Synopsis <a name="228"></a></h1>
<p>The current human-readable description of the Perl 6 language. Still in development. Much more a community effort than the <a href="#17-Apocalypse">Apocalypses</a> and <a href="#17-Exegesis">Exegeses</a> were. The current state of the language is reflected by <a href="#17-roast">#roast</a>, its <a href="#17-test suite">#test suite</a>, not the synopses where speculative material is not always so flagged or more recent additions have not been documented. This is even more true of material that has not been yet implemented.</p>
<a name="t18.66"></a> <h1 id="_language_glossary.pod6-Syntax_Analysis">Syntax Analysis <a name="229"></a></h1>
<a name="t18.67"></a> <h1 id="_language_glossary.pod6-test_suite">test suite <a name="230"></a></h1>
<p>The Perl 6 test suite is <a href="#17-roast">#roast</a></p>
<a name="t18.68"></a> <h1 id="_language_glossary.pod6-ASCII_operator">ASCII operator <a name="231"></a> <a name="232"></a></h1>
“Texas” was used in the past but is now discouraged.
Remove the link when “Texas” goes completely out of use.
<p>The ASCII variant of a non-ASCII Unicode <a href="#17-Operator">operator</a> or <a href="#17-Symbol">symbol</a>. For instance, <span class="code">(elem)</span> corresponds to the <span class="code">∈</span> (&quot;Is this an element of that set?&quot;) operator that comes from set theory. ASCII operators are a workaround to the problem that people don't know how to type Unicode yet. Culturally, while we encourage people to use the Unicode symbols in a vague sort of way, we do not disparage the use of the <a href="#_language_unicode_ascii.pod6">ASCII variants</a>. Well, maybe just a little...</p>
<a name="t18.69"></a> <h1 id="_language_glossary.pod6-TheDamian">TheDamian</h1>
<p><a href="#17-IRC">#IRC</a> screen name for <a href="#17-Damian Conway">#Damian Conway</a>, writer of the original <a href="#17-Exegesis">Exegeses</a>.</p>
<a name="t18.70"></a> <h1 id="_language_glossary.pod6-TimToady">TimToady</h1>
<p><a href="#17-IRC">#IRC</a> screen name for <a href="#17-Larry Wall">#Larry Wall</a>, creator of Perl. The name comes from the pronunciation of <a href="#17-TIMTOWTDI">#TIMTOWTDI</a> as a word.</p>
<a name="t18.71"></a> <h1 id="_language_glossary.pod6-Thunk">Thunk <a name="233"></a></h1>
<p>A piece of code that isn't immediately executed, but doesn't have an independent scope.</p>
<a name="t18.72"></a> <h1 id="_language_glossary.pod6-twine">twine <a name="234"></a></h1>
<p>A data structure used to hold a POD string with embedded formatting codes. For example:</p>
<pre class="code">=begin pod
C&lt;foo&gt;
=end pod
say $=pod[0].contents[0].contents.perl;
</pre>
<p>The output will be:</p>
<pre class="code">[&quot;&quot;, Pod::FormattingCode.new(type =&gt; &quot;C&quot;, meta =&gt; [], config =&gt; {}, contents =&gt; [&quot;foo&quot;]),&quot;&quot;]
</pre>
<p>Note the <span class="code">twine</span> is an array with an odd number of elements beginning with a simple string, alternating with formatting code objects and simple strings, and ending with a simple string. (The formatting code objects are inter<span class="code">twine</span>d with the strings.) The strings may be empty (as shown in the example). A twine with no formatting code will contain one simple string.</p>
<a name="t18.73"></a> <h1 id="_language_glossary.pod6-value">value <a name="235"></a></h1>
<a name="t18.74"></a> <h1 id="_language_glossary.pod6-Value_type">Value type <a name="236"></a></h1>
<p>A type is known as a <b>value type</b> if it is immutable and any instance of that type is interchangeable with any other instance &quot;of the same value&quot;—that is, any instance constructed in the same way. An instance of a value type is often <i>called</i> a <b>value</b> (but should not be confused with <a href="#17-lvalue">#lvalue</a>s or <a href="#17-rvalue">#rvalue</a>s).</p>
<p>For example, numbers are value types, so a number constructed one place in your program with, for instance, the literal <span class="code">3</span> can't be changed in any way—it simply <i>is</i> 3—and any later use of the literal <span class="code">3</span> can safely be pointed at the same place in memory as the first with no ill consequences.</p>
<p>Classes doing the roles <a href="#_type_Numeric.pod6">Numeric</a> and <a href="#_type_Stringy.pod6">Stringy</a> are among a few examples of built-in value types.</p>
<p>A value type is created by ensuring that an instance of the value type is immutable (i.e., its attributes cannot be modified after construction) and that its <a href="#_routine_WHICH.pod6"><span class="code">WHICH</span></a> method returns the same thing every time an instance with the same value is constructed (and conversely returns a different thing every time an instance with a different value is constructed).</p>
<p>The language is free to optimize based on the assumption that equivalent instances of value types are interchangeable, but you should not depend on any such optimization. For instance, if you want <a href="#_routine_clone.pod6"><span class="code">clone</span></a> to return an instance of <span class="code">self</span>, or you want instance construction to be memoized so that re-construction of a previously-constructed value always returns the same instance, you currently must override this behavior yourself.</p>
<p>(The same would hold true of object finalization, but if your instances need special destruction behavior, you almost certainly do not actually have a value type. Values should be thought of as &quot;timeless&quot; and existing in some ideal form outside of your program's memory, like natural values are.)</p>
<a name="t18.75"></a> <h1 id="_language_glossary.pod6-Variable">Variable <a name="237"></a></h1>
<p>A variable is a name for a <a href="#_language_containers.pod6">container</a>.</p>
<a name="t18.76"></a> <h1 id="_language_glossary.pod6-Variable_Interpolation">Variable Interpolation <a name="238"></a></h1>
<a name="t18.77"></a> <h1 id="_language_glossary.pod6-Virtual_Machine">Virtual Machine <a name="239"></a></h1>
<p>A virtual machine is the Perl compiler entity that executes the <a href="#17-bytecode">bytecode</a>. It can optimize the bytecode or generate machine code Just in Time. Examples are <a href="#17-MoarVM">#MoarVM</a>, <a href="#17-Parrot">#Parrot</a> (who are intended to run Perl 6) and more generic virtual machines such as JVM and Javascript.</p>
<a name="t18.78"></a> <h1 id="_language_glossary.pod6-whitespace">whitespace <a name="240"></a></h1>
<a name="t18.79"></a> <h1 id="_language_glossary.pod6-6model">6model <a name="241"></a></h1>
</div>
<!-- /language/grammar_tutorial.pod6 --><div class="pod-body"><a id="_language_grammar_tutorial.pod6"></a><a name="t19"></a><h1 class="title">19 Grammar Tutorial</h1> <p class="subtitle">An introduction to grammars</p> <a name="t19.1"></a> <h1 id="_language_grammar_tutorial.pod6-Before_We_Start">Before We Start</h1>
<a name="t19.1.1"></a> <h2 id="_language_grammar_tutorial.pod6-Why_grammars?">Why grammars?</h2>
<p>Grammars parse strings and return data structures from those strings. Grammars can be used to prepare a program for execution, to determine if a program can run at all (if it's a valid program), to break down a web page into constituent parts, or to identify the different parts of a sentence, among other things.</p>
<a name="t19.1.2"></a> <h2 id="_language_grammar_tutorial.pod6-When_would_I_use_grammars?">When would I use grammars?</h2>
<p>If you have strings to tame or interpret, grammars provide the tools to do the job.</p>
<p>The string could be a file that you're looking to break into sections; perhaps a protocol, like SMTP, where you need to specify which &quot;commands&quot; come after what user-supplied data; maybe you're designing your own domain specific language. Grammars can help.</p>
<a name="t19.1.3"></a> <h2 id="_language_grammar_tutorial.pod6-The_broad_concept_of_grammars">The broad concept of grammars</h2>
<p>Regular expressions (<a href="#_language_regexes.pod6">Regexes</a>) work well for finding patterns in strings. However, for some tasks, like finding multiple patterns at once, or combining patterns, or testing for patterns that may surround strings regular expressions, alone, are not enough.</p>
<p>When working with HTML, you could define a grammar to recognize HTML tags, both the opening and closing elements, and the text in between. You could then organize these elements into data structures, such as arrays or hashes.</p>
<a name="t19.2"></a> <h1 id="_language_grammar_tutorial.pod6-Getting_More_Technical">Getting More Technical</h1>
<a name="t19.2.1"></a> <h2 id="_language_grammar_tutorial.pod6-The_conceptual_overview">The conceptual overview</h2>
<p>Grammars are a special kind of class. You declare and define a grammar exactly as you would any other class, except that you use the <i>grammar</i> keyword instead of <i>class</i>.</p>
<pre class="code">grammar G { ... }
</pre>
<p>Grammars are made up of methods that define a regex, a token, or a rule. These are all varieties of different types of match methods. Once you have a grammar defined, you call it and pass in a string for parsing.</p>
<pre class="code">my $matchObject = G.parse($string);
</pre>
<p>Now, you may be wondering, if I have all these regexes defined that just return their results, how does that help with parsing strings that may be ahead or backwards in a string, or things that need to be combined from many of those regexes... and that's where grammar actions come in.</p>
<p>For every &quot;method&quot; you match in your grammar, you get an action you can use to act on that match. You also get an overarching action that you can use to tie together all your matches and to build a data structure. This overarching method is called <span class="code">TOP</span> by default.</p>
<a name="t19.2.2"></a> <h2 id="_language_grammar_tutorial.pod6-The_technical_overview">The technical overview</h2>
<p>As already mentioned, grammars are declared using the <i>grammar</i> keyword and its &quot;methods&quot; are declared with <i>regex</i>, or <i>token</i>, or <i>rule</i>.</p>
<ul><li><p>Regex methods are slow but thorough, which will look back in the string and really try.</p>
</li></ul> <ul><li><p>Token methods are faster than regex methods and ignore whitespace.</p>
</li></ul> <ul><li><p>Rule methods are the same as token methods except whitespace is not ignored.</p>
</li></ul> <p>When a method (regex, token or rule) matches in the grammar, the string matched is put into a <a href="#_type_Match.pod6">match object</a> and keyed with the same name as the method.</p>
<pre class="code">grammar G {
token TOP { &lt;thingy&gt; .* }
token thingy { 'clever_text_keyword' }
}
</pre>
<p>If you were to use <span class="code">my $match = G.parse($string)</span> and your string started with 'clever_text_keyword', you would get a match object back that contained 'clever_text_keyword' keyed by the name of <span class="code">&lt;thingy&gt;</span> in your match object.</p>
<p>The <span class="code">TOP</span> method (whether regex, token, or rule) is the overarching pattern that must match everything (by default). If the parsed string doesn't match the TOP regex, your returned match object will be empty (<span class="code">Nil</span>).</p>
<p>As you can see above, in <span class="code">TOP</span>, the <span class="code">&lt;thingy&gt;</span> token is mentioned. The <span class="code">&lt;thingy&gt;</span> is defined on the next line. That means that <span class="code">'clever_text_keyword'</span> <b>must</b> be the first thing in the string, or the grammar parse will fail and we'll get an empty match. This is great for recognizing a malformed string that should be discarded.</p>
<a name="t19.3"></a> <h1 id="_language_grammar_tutorial.pod6-Learning_By_Example_-_a_REST_Contrivance">Learning By Example - a REST Contrivance</h1>
<p>Let's suppose we'd like to parse a URI into the component parts that make up a RESTful request. We want the URIs to work like this:</p>
<ul><li><p>The first part of the URI will be the &quot;subject&quot;, like a part, or a product, or a person.</p>
</li></ul> <ul><li><p>The second part of the URI will be the &quot;command&quot;, the standard CRUD functions (create, retrieve, update, or delete).</p>
</li></ul> <ul><li><p>The third part of the URI will be arbitrary data, perhaps the specific ID we'll be working with or a long list of data separated by &quot;/&quot;'s.</p>
</li></ul> <ul><li><p>When we get a URI, we'll want 1-3 above to be placed into a data structure that we can easily work with (and later enhance).</p>
</li></ul> <p>So, if we have &quot;/product/update/7/notify&quot;, we would want our grammar to give us a match object that has a <span class="code">subject</span> of &quot;product&quot;, a <span class="code">command</span> of &quot;update&quot;, and <span class="code">data</span> of &quot;7/notify&quot;.</p>
<p>We'll start by defining a grammar class and some match methods for the subject, command, and data. We'll use the token declarator since we don't care about whitespace.</p>
<pre class="code">grammar REST {
token subject { \w+ }
token command { \w+ }
token data { .* }
}
</pre>
<p>So far, this REST grammar says we want a subject that will be just <i>word</i> characters, a command that will be just <i>word</i> characters, and data that will be everything else left in the string.</p>
<p>Next, we'll want to arrange these matching tokens within the larger context of the URI. That's what the TOP method allows us to do. We'll add the TOP method and place the names of our tokens within it, together with the rest of the patterns that makes up the overall pattern. Note how we're building a larger regex from our named regexes.</p>
<pre class="code">grammar REST {
token TOP { '/' &lt;subject&gt; '/' &lt;command&gt; '/' &lt;data&gt; }
token subject { \w+ }
token command { \w+ }
token data { .* }
}
</pre>
<p>With this code, we can already get the three parts of our RESTful request:</p>
<pre class="code">my $match = REST.parse('/product/update/7/notify');
say $match;
# OUTPUT: «「/product/update/7/notify」␤
# subject =&gt; 「product」
# command =&gt; 「update」
# data =&gt; 「7/notify」»
</pre>
<p>The data can be accessed directly by using <span class="code">$match&lt;subject&gt;</span> or <span class="code">$match&lt;command&gt;</span> or <span class="code">$match&lt;data&gt;</span> to return the values parsed. They each contain match objects that you can work further with, such as coercing into a string ( <span class="code">$match&lt;command&gt;.Str</span> ).</p>
<a name="t19.3.1"></a> <h2 id="_language_grammar_tutorial.pod6-Adding_some_flexibility">Adding some flexibility</h2>
<p>So far, the grammar will handle retrieves, deletes and updates. However, a <i>create</i> command doesn't have the third part (the <i>data</i> portion). This means the grammar will fail to match if we try to parse a create URI. To avoid this, we need to make that last <i>data</i> position match optional, along with the '/' preceding it. This is accomplished by adding a question mark to the grouped '/' and <i>data</i> components of the TOP token, to indicate their optional nature, just like a normal regex.</p>
<p>So, now we have:</p>
<pre class="code">grammar REST {
token TOP { '/' &lt;subject&gt; '/' &lt;command&gt; [ '/' &lt;data&gt; ]? }
token subject { \w+ }
token command { \w+ }
token data { .* }
}
my $m = REST.parse('/product/create');
say $m&lt;subject&gt;, $m&lt;command&gt;;
# OUTPUT: «「product」「create」␤»
</pre>
<p>Next, assume that the URIs will be entered manually by a user and that the user might accidentally put spaces between the '/'s. If we wanted to accommodate for this, we could replace the '/'s in TOP with a token that allowed for spaces.</p>
<pre class="code">grammar REST {
token TOP { &lt;slash&gt;&lt;subject&gt;&lt;slash&gt;&lt;command&gt;[&lt;slash&gt;&lt;data&gt;]? }
token subject { \w+ }
token command { \w+ }
token data { .* }
token slash { \s* '/' \s* }
}
my $m = REST.parse('/ product / update /7 /notify');
say $m;
# OUTPUT: «「/ product / update /7 /notify」␤
# slash =&gt; 「/ 」
# subject =&gt; 「product」
# slash =&gt; 「 / 」
# command =&gt; 「update」
# slash =&gt; 「 /」
# data =&gt; 「7 /notify」»
</pre>
<p>We're getting some extra junk in the match object now, with those slashes. There's techniques to clean that up that we'll get to later.</p>
<a name="t19.3.2"></a> <h2 id="_language_grammar_tutorial.pod6-Adding_some_constraints">Adding some constraints</h2>
<p>We want our RESTful grammar to allow for CRUD operations only. Anything else we want to fail to parse. That means our &quot;command&quot; above should have one of four values: create, retrieve, update or delete.</p>
<p>There are several ways to accomplish this. For example, you could change the command method:</p>
<pre class="code">token command { \w+ }
# …becomes…
token command { 'create'|'retrieve'|'update'|'delete' }
</pre>
<p>For a URI to parse successfully, the second part of the string between '/'s must be one of those CRUD values, otherwise the parsing fails. Exactly what we want.</p>
<p>There's another technique that provides greater flexibility and improved readability when options grow large: <i>proto-regexes</i>.</p>
<p>To utilize these proto-regexes (multimethods, in fact) to limit ourselves to the valid CRUD options, we'll replace <span class="code">token command</span> with the following:</p>
<pre class="code">proto token command {*}
token command:sym&lt;create&gt; { &lt;sym&gt; }
token command:sym&lt;retrieve&gt; { &lt;sym&gt; }
token command:sym&lt;update&gt; { &lt;sym&gt; }
token command:sym&lt;delete&gt; { &lt;sym&gt; }
</pre>
<p>The <span class="code">sym</span> keyword is used to create the various proto-regex options. Each option is named (e.g., <span class="code">sym&lt;update&gt;</span>), and for that option's use, a special <span class="code">&lt;sym&gt;</span> token is auto-generated with the same name.</p>
<p>The <span class="code">&lt;sym&gt;</span> token, as well as other user-defined tokens, may be used in the proto-regex option block to define the specific <i>match condition</i>. Regex tokens are compiled forms and, once defined, cannot subsequently be modified by adverb actions (e.g., <span class="code">:i</span>). Therefore, as it's auto-generated, the special <span class="code">&lt;sym&gt;</span> token is useful only where an exact match of the option name is required.</p>
<p>If, for one of the proto-regex options, a match condition occurs, then the whole proto's search terminates. The matching data, in the form of a match object, is assigned to the parent proto token. If the special <span class="code">&lt;sym&gt;</span> token was employed and formed all or part of the actual match, then it's preserved as a sub-level in the match object, otherwise it's absent.</p>
<p>Using proto-regex like this gives us a lot of flexibility. For example, instead of returning <span class="code">&lt;sym&gt;</span>, which in this case is the entire string that was matched, we could instead enter our own string, or do other funny stuff. We could do the same with the <span class="code">token subject</span> method and limit it also to only parsing correctly on valid subjects (like 'part' or 'people', etc.).</p>
<a name="t19.3.3"></a> <h2 id="_language_grammar_tutorial.pod6-Putting_our_RESTful_grammar_together">Putting our RESTful grammar together</h2>
<p>This is what we have for processing our RESTful URIs, so far:</p>
<pre class="code">grammar REST
{
token TOP { &lt;slash&gt;&lt;subject&gt;&lt;slash&gt;&lt;command&gt;[&lt;slash&gt;&lt;data&gt;]? }
proto token command {*}
token command:sym&lt;create&gt; { &lt;sym&gt; }
token command:sym&lt;retrieve&gt; { &lt;sym&gt; }
token command:sym&lt;update&gt; { &lt;sym&gt; }
token command:sym&lt;delete&gt; { &lt;sym&gt; }
token subject { \w+ }
token data { .* }
token slash { \s* '/' \s* }
}
</pre>
<p>Let's look at various URIs and see how they work with our grammar.</p>
<pre class="code">my @uris = ['/product/update/7/notify',
'/product/create',
'/item/delete/4'];
for @uris -&gt; $uri {
my $m = REST.parse($uri);
say &quot;Sub: $m&lt;subject&gt; Cmd: $m&lt;command&gt; Dat: $m&lt;data&gt;&quot;;
}
# OUTPUT: «Sub: product Cmd: update Dat: 7/notify␤
# Sub: product Cmd: create Dat: ␤
# Sub: item Cmd: delete Dat: 4␤»
</pre>
<p>Note that since <span class="code">&lt;data&gt;</span> matches nothing on the second string, <span class="code">$m&lt;data&gt;</span> will be <span class="code">Nil</span>, then using it in string context in the <span class="code">say</span> function warns.</p>
<p>With just this part of a grammar, we're getting almost everything we're looking for. The URIs get parsed and we get a data structure with the data.</p>
<p>The <i>data</i> token returns the entire end of the URI as one string. The 4 is fine. However from the '7/notify', we only want the 7. To get just the 7, we'll use another feature of grammar classes: <i>actions</i>.</p>
<a name="t19.4"></a> <h1 id="_language_grammar_tutorial.pod6-Grammar_Actions">Grammar Actions</h1>
<p>Grammar actions are used within grammar classes to do things with matches. Actions are defined in their own classes, distinct from grammar classes.</p>
<p>You can think of grammar actions as a kind of plug-in expansion module for grammars. A lot of the time you'll be happy using grammars all by their own. But when you need to further process some of those strings, you can plug in the Actions expansion module.</p>
<p>To work with actions, you use a named parameter called <span class="code">actions</span> which should contain an instance of your actions class. With the code above, if our actions class called REST-actions, we would parse the URI string like this:</p>
<pre class="code">my $matchObject = REST.parse($uri, actions =&gt; REST-actions.new);
# …or if you prefer…
my $matchObject = REST.parse($uri, :actions(REST-actions.new));
</pre>
<p>If you <i>name your action methods with the same name as your grammar methods</i> (tokens, regexes, rules), then when your grammar methods match, your action method with the same name will get called automatically. The method will also be passed the corresponding match object (represented by the <span class="code">$/</span> variable).</p>
<p>Let's turn to an example.</p>
<a name="t19.4.1"></a> <h2 id="_language_grammar_tutorial.pod6-Grammars_by_example_with_actions">Grammars by example with actions</h2>
<p>Here we are back to our grammar.</p>
<pre class="code">grammar REST
{
token TOP { &lt;slash&gt;&lt;subject&gt;&lt;slash&gt;&lt;command&gt;[&lt;slash&gt;&lt;data&gt;]? }
proto token command {*}
token command:sym&lt;create&gt; { &lt;sym&gt; }
token command:sym&lt;retrieve&gt; { &lt;sym&gt; }
token command:sym&lt;update&gt; { &lt;sym&gt; }
token command:sym&lt;delete&gt; { &lt;sym&gt; }
token subject { \w+ }
token data { .* }
token slash { \s* '/' \s* }
}
</pre>
<p>Recall that we want to further process the data token &quot;7/notify&quot;, to get the 7. To do this, we'll create an action class that has a method with the same name as the named token. In this case, our token is named <span class="code">data</span> so our method is also named <span class="code">data</span>.</p>
<pre class="code">class REST-actions
{
method data($/) { $/.split('/') }
}
</pre>
<p>Now when we pass the URI string through the grammar, the <i>data token match</i> will be passed to the <i>REST-actions' data method</i>. The action method will split the string by the '/' character and the first element of the returned list will be the ID number (7 in the case of &quot;7/notify&quot;).</p>
<p>But not really; there's a little more.</p>
<a name="t19.4.2"></a> <h2 id="_language_grammar_tutorial.pod6-Keeping_grammars_with_actions_tidy_with_make_and_made">Keeping grammars with actions tidy with <span class="code">make</span> and <span class="code">made</span></h2>
<p>If the grammar calls the action above on data, the data method will be called, but nothing will show up in the big <span class="code">TOP</span> grammar match result returned to our program. In order to make the action results show up, we need to call <a href="#_routine_make.pod6">make</a> on that result. The result can be many things, including strings, array or hash structures.</p>
<p>You can imagine that the <span class="code">make</span> places the result in a special contained area for a grammar. Everything that we <span class="code">make</span> can be accessed later by <a href="#_routine_made.pod6">made</a>.</p>
<p>So instead of the REST-actions class above, we should write:</p>
<pre class="code">class REST-actions
{
method data($/) { make $/.split('/') }
}
</pre>
<p>When we add <span class="code">make</span> to the match split (which returns a list), the action will return a data structure to the grammar that will be stored separately from the <span class="code">data</span> token of the original grammar. This way, we can work with both if we need to.</p>
<p>If we want to access just the ID of 7 from that long URI, we access the first element of the list returned from the <span class="code">data</span> action that we <span class="code">made</span>:</p>
<pre class="code">my $uri = '/product/update/7/notify';
my $match = REST.parse($uri, actions =&gt; REST-actions.new);
say $match&lt;data&gt;.made[0]; # OUTPUT: «7␤»
say $match&lt;command&gt;.Str; # OUTPUT: «update␤»
</pre>
<p>Here we call <span class="code">made</span> on data, because we want the result of the action that we <span class="code">made</span> (with <span class="code">make</span>) to get the split array. That's lovely! But, wouldn't it be lovelier if we could <span class="code">make</span> a friendlier data structure that contained all of the stuff we want, rather than having to coerce types and remember arrays?</p>
<p>Just like Grammar's <span class="code">TOP</span>, which matches the entire string, actions have a TOP method as well. We can <span class="code">make</span> all of the individual match components, like <span class="code">data</span> or <span class="code">subject</span> or <span class="code">command</span>, and then we can place them in a data structure that we will <span class="code">make</span> in TOP. When we return the final match object, we can then access this data structure.</p>
<p>To do this, we add the method <span class="code">TOP</span> to the action class and <span class="code">make</span> whatever data structure we like from the component pieces.</p>
<p>So, our action class becomes:</p>
<pre class="code">class REST-actions
{
method TOP ($/) {
make { subject =&gt; $&lt;subject&gt;.Str,
command =&gt; $&lt;command&gt;.Str,
data =&gt; $&lt;data&gt;.made }
}
method data($/) { make $/.split('/') }
}
</pre>
<p>Here in the <span class="code">TOP</span> method, the <span class="code">subject</span> remains the same as the subject we matched in the grammar. Also, <span class="code">command</span> returns the valid <span class="code">&lt;sym&gt;</span> that was matched (create, update, retrieve, or delete). We coerce each into <span class="code">.Str</span>, as well, since we don't need the full match object.</p>
<p>We want to make sure to use the <span class="code">made</span> method on the <span class="code">$&lt;data&gt;</span> object, since we want to access the split one that we <span class="code">made</span> with <span class="code">make</span> in our action, rather than the proper <span class="code">$&lt;data&gt;</span> object.</p>
<p>After we <span class="code">make</span> something in the <span class="code">TOP</span> method of a grammar action, we can then access all the custom values by calling the <span class="code">made</span> method on the grammar result object. The code now becomes</p>
<pre class="code">my $uri = '/product/update/7/notify';
my $match = REST.parse($uri, actions =&gt; REST-actions.new);
my $rest = $match.made;
say $rest&lt;data&gt;[0]; # OUTPUT: «7␤»
say $rest&lt;command&gt;; # OUTPUT: «update␤»
say $rest&lt;subject&gt;; # OUTPUT: «product␤»
</pre>
<p>If the complete return match object is not needed, you could return only the made data from your action's <span class="code">TOP</span>.</p>
<pre class="code">my $uri = '/product/update/7/notify';
my $rest = REST.parse($uri, actions =&gt; REST-actions.new).made;
say $rest&lt;data&gt;[0]; # OUTPUT: «7␤»
say $rest&lt;command&gt;; # OUTPUT: «update␤»
say $rest&lt;subject&gt;; # OUTPUT: «product␤»
</pre>
<p>Oh, did we forget to get rid of that ugly array element number? Hmm. Let's make something new in the grammar's custom return in <span class="code">TOP</span>... how about we call it <span class="code">subject-id</span> and have it set to element 0 of <span class="code">&lt;data&gt;</span>.</p>
<pre class="code">class REST-actions
{
method TOP ($/) {
make { subject =&gt; $&lt;subject&gt;.Str,
command =&gt; $&lt;command&gt;.Str,
data =&gt; $&lt;data&gt;.made,
subject-id =&gt; $&lt;data&gt;.made[0] }
}
method data($/) { make $/.split('/') }
}
</pre>
<p>Now we can do this instead:</p>
<pre class="code">my $uri = '/product/update/7/notify';
my $rest = REST.parse($uri, actions =&gt; REST-actions.new).made;
say $rest&lt;command&gt;; # OUTPUT: «update␤»
say $rest&lt;subject&gt;; # OUTPUT: «product␤»
say $rest&lt;subject-id&gt;; # OUTPUT: «7␤»
</pre>
<p>Here's the final code:</p>
<pre class="code">grammar REST
{
token TOP { &lt;slash&gt;&lt;subject&gt;&lt;slash&gt;&lt;command&gt;[&lt;slash&gt;&lt;data&gt;]? }
proto token command {*}
token command:sym&lt;create&gt; { &lt;sym&gt; }
token command:sym&lt;retrieve&gt; { &lt;sym&gt; }
token command:sym&lt;update&gt; { &lt;sym&gt; }
token command:sym&lt;delete&gt; { &lt;sym&gt; }
token subject { \w+ }
token data { .* }
token slash { \s* '/' \s* }
}
class REST-actions
{
method TOP ($/) {
make { subject =&gt; $&lt;subject&gt;.Str,
command =&gt; $&lt;command&gt;.Str,
data =&gt; $&lt;data&gt;.made,
subject-id =&gt; $&lt;data&gt;.made[0] }
}
method data($/) { make $/.split('/') }
}
</pre>
<a name="t19.4.3"></a> <h2 id="_language_grammar_tutorial.pod6-Add_actions_directly">Add actions directly</h2>
<p>Above we see how to associate grammars with action objects and perform actions on the match object. However, when we want to deal with the match object, that isn't the only way. See the example below:</p>
<pre class="code">grammar G {
rule TOP { &lt;function-define&gt; }
rule function-define {
'sub' &lt;identifier&gt;
{
say &quot;func &quot; ~ $&lt;identifier&gt;.made;
make $&lt;identifier&gt;.made;
}
'(' &lt;parameter&gt; ')' '{' '}'
{ say &quot;end &quot; ~ $/.made; }
}
token identifier { \w+ { make ~$/; } }
token parameter { \w+ { say &quot;param &quot; ~ $/; } }
}
G.parse('sub f ( a ) { }');
# OUTPUT: «func f␤param a␤end f␤»
</pre>
<p>This example is a reduced portion of a parser. Let's focus more on the feature it shows.</p>
<p>First, we can add actions inside the grammar itself, and such actions are performed once the control flow of the regex arrives at them. Note that action object's method will always be performed after the whole regex item matched. Second, it shows what <span class="code">make</span> really does, which is no more than a sugar of <span class="code">$/.made = ...</span>. And this trick introduces a way to pass messages from within a regex item.</p>
<p>Hopefully this has helped introduce you to the grammars in Perl 6 and shown you how grammars and grammar action classes work together. For more information, check out the more advanced <a href="https://docs.perl6.org/language/grammars">Perl Grammar Guide</a>.</p>
<p>For more grammar debugging, see <a href="https://github.com/jnthn/grammar-debugger">Grammar::Debugger</a>. This provides breakpoints and color-coded MATCH and FAIL output for each of your grammar tokens.</p>
</div>
<!-- /language/grammars.pod6 --><div class="pod-body"><a id="_language_grammars.pod6"></a><a name="t20"></a><h1 class="title">20 Grammars</h1> <p class="subtitle">Parsing and interpreting text</p> <p>Grammar is 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="t20.1"></a> <h1 id="_language_grammars.pod6-Named_Regexes"><a name="242"></a>Named Regexes</h1>
<p>The main ingredient of grammars is named <a href="#_language_regexes.pod6">regexes</a>. While the syntax of <a href="#_language_regexes.pod6">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 regex number { \d+ [ \. \d+ ]? }
</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 so &quot;32.51&quot; ~~ &amp;number; # OUTPUT: «True␤»
say so &quot;15 + 4.5&quot; ~~ /&lt;number&gt;\s* '+' \s*&lt;number&gt;/ # OUTPUT: «True␤»
</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; # OUTPUT: «True␤»
say so $s ~~ &amp;fails-but-fast; # OUTPUT: «False␤»
# the entire string get taken by the .+
</pre>
<p>Note that non-backtracking works on terms, that is, as the example below, if you have matched something, then you will never backtrack. But when you fail to match, if there is another candidate introduced by <span class="code">|</span> or <span class="code">||</span>, you will retry to match again.</p>
<pre class="code">my token tok-a { .* d };
my token tok-b { .* d | bd };
say so &quot;bd&quot; ~~ &amp;tok-a; # OUTPUT: «False␤»
say so &quot;bd&quot; ~~ &amp;tok-b; # OUTPUT: «True␤»
</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.pod6-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 so 'onceuponatime' ~~ &amp;non-space-y; # OUTPUT: «True␤»
say so 'once upon a time' ~~ &amp;non-space-y; # OUTPUT: «False␤»
say so 'onceuponatime' ~~ &amp;space-y; # OUTPUT: «False␤»
say so 'once upon a time' ~~ &amp;space-y; # OUTPUT: «True␤»
</pre>
<a name="t20.2"></a> <h1 id="_language_grammars.pod6-Creating_Grammars"><a name="243"></a>Creating Grammars</h1>
<p class="subtitle">Group of named regexes that form a formal grammar</p> <p><a href="#_type_Grammar.pod6">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, you can add actions within the grammar, or an <a href="#_language_grammars.pod6-Action_Objects">action object</a> is recommended to be used in conjunction with the grammar.</p>
<a name="t20.2.1"></a> <h2 id="_language_grammars.pod6-Proto_regexes"><a name="244"></a>Proto regexes</h2>
<p>If you have a lot of alternations, it may become difficult to produce readable code or subclass your grammar. In the Actions class below, the ternary in <span class="code">method TOP</span> is less than ideal and it becomes even worse the more operations we add:</p>
<pre class="code">grammar Calculator {
token TOP { [ &lt;add&gt; | &lt;sub&gt; ] }
rule add { &lt;num&gt; '+' &lt;num&gt; }
rule sub { &lt;num&gt; '-' &lt;num&gt; }
token num { \d+ }
}
class Calculations {
method TOP ($/) { make $&lt;add&gt; ?? $&lt;add&gt;.made !! $&lt;sub&gt;.made; }
method add ($/) { make [+] $&lt;num&gt;; }
method sub ($/) { make [-] $&lt;num&gt;; }
}
say Calculator.parse('2 + 3', actions =&gt; Calculations).made;
# OUTPUT: «5␤»</pre>
<p>To make things better, we can use proto regexes that look like <span class="code">:sym&lt;...&gt;</span> adverbs on tokens:</p>
<pre class="code">grammar Calculator {
token TOP { &lt;calc-op&gt; }
proto rule calc-op {*}
rule calc-op:sym&lt;add&gt; { &lt;num&gt; '+' &lt;num&gt; }
rule calc-op:sym&lt;sub&gt; { &lt;num&gt; '-' &lt;num&gt; }
token num { \d+ }
}
class Calculations {
method TOP ($/) { make $&lt;calc-op&gt;.made; }
method calc-op:sym&lt;add&gt; ($/) { make [+] $&lt;num&gt;; }
method calc-op:sym&lt;sub&gt; ($/) { make [-] $&lt;num&gt;; }
}
say Calculator.parse('2 + 3', actions =&gt; Calculations).made;
# OUTPUT: «5␤»</pre>
<p>In the grammar, the alternation has now been replaced with <span class="code">&lt;calc-op&gt;</span>, which is essentially the name of a group of values we'll create. We do so by defining a rule prototype with <span class="code">proto rule calc-op</span>. Each of our previous alternations have been replaced by a new <span class="code">rule calc-op</span> definition and the name of the alternation is attached with <span class="code">:sym&lt;&gt;</span> adverb.</p>
<p>In the actions class, we now got rid of the ternary operator and simply take the <span class="code">.made</span> value from the <span class="code">$&lt;calc-op&gt;</span> match object. And the actions for individual alternations now follow the same naming pattern as in the grammar: <span class="code">method calc-op:sym&lt;add&gt;</span> and <span class="code">method calc-op:sym&lt;sub&gt;</span>.</p>
<p>The real beauty of this method can be seen when you subclass that grammar and actions class. Let's say we want to add a multiplication feature to the calculator:</p>
<pre class="code">grammar BetterCalculator is Calculator {
rule calc-op:sym&lt;mult&gt; { &lt;num&gt; '*' &lt;num&gt; }
}
class BetterCalculations is Calculations {
method calc-op:sym&lt;mult&gt; ($/) { make [*] $&lt;num&gt; }
}
say BetterCalculator.parse('2 * 3', actions =&gt; BetterCalculations).made;
# OUTPUT: «6␤»
</pre>
<p>All we had to add are additional rule and action to the <span class="code">calc-op</span> group and the thing works—all thanks to proto regexes.</p>
<a name="t20.2.2"></a> <h2 id="_language_grammars.pod6-Special_Tokens">Special Tokens</h2>
<a name="t20.2.2.1"></a> <h3 id="_language_grammars.pod6-TOP"><a name="245"></a><span class="code">TOP</span></h3>
<pre class="code">grammar Foo {
token TOP { \d+ }
}</pre>
<p>The <span class="code">TOP</span> token is the default first token attempted to match when parsing with a grammar. Note that if you're parsing with <a href="#_type_Grammar.pod6-method_parse"><span class="code">.parse</span></a> method, <span class="code">token TOP</span> is automatically anchored to the start and end of the string. If you don't want to parse the whole string, look up <a href="#_type_Grammar.pod6-method_subparse"><span class="code">.subparse</span></a>.</p>
<p>Using <span class="code">rule TOP</span> or <span class="code">regex TOP</span> are also acceptable.</p>
<p>A different token can be chosen to be matched first using the <span class="code">:rule</span> named argument to <span class="code">.parse</span>, <span class="code">.subparse</span>, or <span class="code">.parsefile</span>. These are all <span class="code">Grammar</span> methods.</p>
<a name="t20.2.2.2"></a> <h3 id="_language_grammars.pod6-ws"><a name="246"></a><span class="code">ws</span></h3>
<p>When <span class="code">rule</span> instead of <span class="code">token</span> is used, any whitespace after an atom is turned into a non-capturing call to <span class="code">ws</span>, written as <span class="code">&lt;.ws&gt;</span> where <span class="code">.</span> means non-capturing. That is to say:</p>
<pre class="code">rule entry { &lt;key&gt; '=' &lt;value&gt; }</pre>
<p>Is the same as:</p>
<pre class="code">token entry { &lt;key&gt; &lt;.ws&gt; '=' &lt;.ws&gt; &lt;value&gt; &lt;.ws&gt; }</pre>
<p>The default <span class="code">ws</span> matches one or more whitespace characters (<span class="code">\s</span>) or a word boundary (<span class="code">&lt;|w&gt;</span>):</p>
<pre class="code"># First &lt;.ws&gt; matches word boundary at the start of the line
# and second &lt;.ws&gt; matches the whitespace between 'b' and 'c'
say 'ab c' ~~ /&lt;.ws&gt; ab &lt;.ws&gt; c /; # OUTPUT: «「ab c」␤»
# Failed match: there is neither any whitespace nor a word
# boundary between 'a' and 'b'
say 'ab' ~~ /. &lt;.ws&gt; b/; # OUTPUT: «Nil␤»
# Successful match: there is a word boundary between ')' and 'b'
say ')b' ~~ /. &lt;.ws&gt; b/; # OUTPUT: «「)b」␤»</pre>
<p>You can also redefine the default <span class="code">ws</span> token:</p>
<pre class="code">grammar Foo {
rule TOP { \d \d }
}.parse: &quot;4 \n\n 5&quot;; # Succeeds
grammar Bar {
rule TOP { \d \d }
token ws { \h* }
}.parse: &quot;4 \n\n 5&quot;; # Fails</pre>
<a name="t20.2.2.3"></a> <h3 id="_language_grammars.pod6-Always_Succeed_Assertion"><a name="247"></a>Always Succeed Assertion</h3>
<p>The <span class="code">&lt;?&gt;</span> is the <i>always succeed</i> assertion. When used as a grammar token, it can be used to trigger an Action class method. In the following grammar we look for Arabic digits and define a <span class="code">succ</span> token with the always succeed assertion.</p>
<p>In the action class, we use calls to the <span class="code">succ</span> method to do set up (in this case, we prepare a new element in <span class="code">@!numbers</span>). In the <span class="code">digit</span> method, we convert an Arabic digit into a Devanagari digit and add it to the last element of <span class="code">@!numbers</span>. Thanks to <span class="code">succ</span>, the last element will always be the number for the currently parsed <span class="code">digit</span> digits.</p>
<pre class="code">grammar Digifier {
rule TOP {
[ &lt;.succ&gt; &lt;digit&gt;+ ]+
}
token succ { &lt;?&gt; }
token digit { &lt;[0..9]&gt; }
}
class Devanagari {
has @!numbers;
method digit ($/) { @!numbers[*-1] ~= $/.ord.&amp;[+](2358).chr }
method succ ($) { @!numbers.push: '' }
method TOP ($/) { make @!numbers[^(*-1)] }
}
say Digifier.parse('255 435 777', actions =&gt; Devanagari.new).made;
# OUTPUT: «(२५५ ४३५ ७७७)␤»</pre>
<a name="t20.2.3"></a> <h2 id="_language_grammars.pod6-Methods_in_Grammar">Methods in Grammar</h2>
<p>It's fine to use methods instead of rules or tokens in a grammar, as long as they return a <a href="#_type_Cursor.pod6">/type/Cursor</a>:</p>
<pre class="code">grammar DigitMatcher {
method TOP (:$full-unicode) {
$full-unicode ?? self.num-full !! self.num-basic;
}
token num-full { \d+ }
token num-basic { &lt;[0..9]&gt;+ }
}</pre>
<p>The grammar above will attempt different matches depending on the arguments provided by parse methods:</p>
<pre class="code">say +DigitMatcher.subparse: '12७१७९०९', args =&gt; \(:full-unicode);
# OUTPUT: «12717909␤»
say +DigitMatcher.subparse: '12७१७९०९', args =&gt; \(:!full-unicode);
# OUTPUT: «12␤»
</pre>
<a name="t20.3"></a> <h1 id="_language_grammars.pod6-Action_Objects"><a name="248"></a>Action Objects</h1>
<p>A successful grammar match gives you a parse tree of <a href="#_type_Match.pod6">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.pod6">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">grammar TestGrammar {
token TOP { \d+ }
}
class TestActions {
method TOP($/) {
$/.make(2 + $/);
}
}
my $match = TestGrammar.parse('40', actions =&gt; TestActions.new);
say $match; # OUTPUT: «「40」␤»
say $match.made; # OUTPUT: «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="#_routine_parse.pod6">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&gt;</span> as a shortcut for <span class="code">$/&lt;capture&gt;</span>).</p>
<p>A slightly more involved example follows:</p>
<pre class="code">grammar KeyValuePairs {
token TOP {
[&lt;pair&gt; \n+]*
}
token ws {
\h*
}
rule pair {
&lt;key=.identifier&gt; '=' &lt;value=.identifier&gt;
}
token identifier {
\w+
}
}
class KeyValuePairsActions {
method pair ($/) {
$/.make: $&lt;key&gt;.made =&gt; $&lt;value&gt;.made
}
method identifier($/) {
# subroutine `make` is the same as calling .make on $/
make ~$/
}
method TOP ($match) {
# can use any variable name for parameter, not just $/
$match.make: $match&lt;pair&gt;».made
}
}
my $actions = KeyValuePairsActions.new;
my $res = KeyValuePairs.parse(q:to/EOI/, :$actions).made;
second=b
hits=42
perl=6
EOI
for @$res -&gt; $p {
say &quot;Key: $p.key()\tValue: $p.value()&quot;;
}
</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.pod6">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>
</div>
<!-- /language/haskell-to-p6.pod6 --><div class="pod-body"><a id="_language_haskell-to-p6.pod6"></a><a name="t21"></a><h1 class="title">21 Perl 6 from Haskell - Nutshell</h1> <p class="subtitle">Learning Perl 6 from Haskell, in a nutshell: What do I already know?</p> <p>Haskell and Perl 6 are <i>very</i> different languages. This is obvious. However, that does not mean there are not similarities or shared ideas! This page attempts to get a Haskell user up and running with Perl 6. The Haskell user may find that they need not abandon all of their Haskelly thoughts while scripting in Perl 6.</p>
<p>Note that this should not be mistaken for a beginner tutorial or overview of Perl 6; it is intended as a technical reference for Perl 6 learners with a strong Haskell background.</p>
<a name="t21.1"></a> <h1 id="_language_haskell-to-p6.pod6-Types">Types</h1>
<a name="t21.1.1"></a> <h2 id="_language_haskell-to-p6.pod6-Types_vs_Values">Types vs Values</h2>
<p>In Haskell, you have type level programming and then value level programming.</p>
<pre class="code">plusTwo :: Integer -&gt; Integer -- Types
plusTwo x = x + 2 -- Values
</pre>
<p>You do not mix types and values in Haskell like the below</p>
<pre class="code">plusTwo 2 -- This is valid
plusTwo Integer -- This is not valid
</pre>
<p>In Perl 6, types (AKA type objects) live on the same level as values</p>
<pre class="code">sub plus-two(Int $x --&gt; Int) { $x + 2 }
plus-two(2); # This is valid
plus-two(Int); # This is valid
</pre>
<p>I will illustrate this unique aspect of Perl 6 with one more example:</p>
<pre class="code">multi sub is-string(Str $ --&gt; True) {}
multi sub is-string(Any $ --&gt; False) {}
is-string('hello'); #True
is-string(4); #False
</pre>
<a name="t21.1.2"></a> <h2 id="_language_haskell-to-p6.pod6-Maybe">Maybe</h2>
<p>In Haskell, you have a Maybe type that allows you to forgo the worry of null types. Let's say you have a hypothetical function that parses a String to an Integer:</p>
<pre class="code">parseInt :: String -&gt; Maybe Integer
case parseInt myString of
Just x -&gt; x
Nothing -&gt; 0
</pre>
<p>In Perl 6, since type objects coexist with regular objects, we have the concept of Defined and Undefined objects. Plain type objects are undefined while instantiated objects are defined.</p>
<pre class="code">sub parse-int(Str $s --&gt; Int) { ... }
my $string = {...};
given parse-int($string) {
when Int:D { $_ }
when Int:U { 0 }
}
</pre>
<p>So in Perl 6 we have type constraints that indicate the definedness of a type. These are</p>
<pre class="code">Int:D; # This is a defined Int.
Int:U; # This is an undefined Int, AKA a type object
Int:_; # This is either defined or undefined.
</pre>
<p>If we wanted to be explicit in the above example (probably a good idea), we could add the <span class="code">:_</span> constraint on the return type. This would let the user know that they should account for both defined and undefined return values. We could also use other methods and constructs that specifically test for definedness.</p>
<pre class="code">sub parse-int(Str $s --&gt; Int:_) { ... }
# One way to do it
my $string = {...};
given parse-int($string) {
when Int:D { $_ }
when Int:U { 0 }
}
# Another way to do it
my Int $number = parse-int($string);
if $number.defined { $number } else { 0 }
# A better way
with parse-int($string) { $_ } else { 0 }
# With the defined-or operator
parse-int($string) // 0
</pre>
<p>The <span class="code">with</span> operator that you see above is like <span class="code">if</span>, except it explicitly tests for definedness and then passes the result to the following block. Similarly, <span class="code">without</span> tests that the object is undefined and also passes the result to the following block.</p>
<p>For more natural control flow with undefined and defined types, Perl 6 introduces <span class="code">andthen</span> and <span class="code">orelse</span>.</p>
<pre class="code">sub parse-int(Str $s --&gt; Int:_) { ... }
my $string = {...};
my $result = parse-int($string) orelse 0;
sub hello() { say 'hi' }
hello() andthen say 'bye';
</pre>
<p>TODO: include a better example for andthen that makes sense. Maybe using promise objects?</p>
<p>So in practice, Perl 6 does not have the concept of a null type, but rather of defined or undefined types.</p>
<a name="t21.1.3"></a> <h2 id="_language_haskell-to-p6.pod6-Data_Definitions">Data Definitions</h2>
<p>Perl 6 is fundamentally an Object Oriented language. However, it also gives you the freedom to write in virtually any paradigm you wish. If you only want to pure functions that take an object and return a new object, you can certainly do so.</p>
<p>Here is a Haskell code example:</p>
<pre class="code">data Point = Point x y
moveUp :: Point -&gt; Point
moveUp (Point x y) = Point x (y + 1)
</pre>
<p>And an equivalent Perl 6 example:</p>
<pre class="code">class Point { has $.x; has $.y; }
sub move-up(Point $p --&gt; Point) {
Point.new(x =&gt; $p.x, y =&gt; $p.y + 1)
}
</pre>
<p>The code I illustrated above is an example of a Product Type. If instead you'd like to write a Sum Type, there is not an exact equivalent in Perl 6. The closest thing would be an Enum.</p>
<pre class="code">data Animal = Dog | Cat | Bird | Horse
testAnimal :: Animal -&gt; String
testAnimal Dog = &quot;Woof&quot;
testAnimal Horse = &quot;Neigh&quot;
</pre>
<p>A Perl 6 Enum does not fit the same exact use cases, but it can be used in putting constraints on types.</p>
<pre class="code">enum Animal &lt; Dog Cat Bird Horse &gt;;
proto sub test-animal( Animal ) {*}
multi sub test-animal( Dog ) { 'Woof' }
multi sub test-animal( Animal::Horse ) { 'Neigh' } # more explicit
say test-animal Animal::Dog; # more explicit
say test-animal Horse;
</pre>
<a name="t21.1.4"></a> <h2 id="_language_haskell-to-p6.pod6-Type_Aliases_and_Subsets">Type Aliases and Subsets</h2>
<p>In Haskell, you can alias an existing type to simply increase clarity of intent and re-use existing types.</p>
<pre class="code">type Name = String
fullName :: Name -&gt; Name -&gt; Name
fullName first last = first ++ last
</pre>
<p>The equivalent in Perl 6 is the following.</p>
<pre class="code">my constant Name = Str;
sub full-name ( Name \first, Name \last --&gt; Name ) { first ~ last }
</pre>
<p>It should be noted that in Perl 6, one can also create a subset of an existing type.</p>
<pre class="code">subset Name of Str where *.chars &lt; 20;
sub full-name(Name $first, Name $last) {
$first ~ $last
}
full-name(&quot;12345678901234567890111&quot;, &quot;Smith&quot;) # This does not compile, as the first parameter
# doesn't fit the Name type
</pre>
<a name="t21.1.5"></a> <h2 id="_language_haskell-to-p6.pod6-Typeclasses">Typeclasses</h2>
<p>TODO</p>
<p>explain how Perl 6 roles compare to Haskell typeclasses</p>
<a name="t21.2"></a> <h1 id="_language_haskell-to-p6.pod6-Functions">Functions</h1>
<a name="t21.2.1"></a> <h2 id="_language_haskell-to-p6.pod6-Definitions_and_Signatures">Definitions and Signatures</h2>
<p>Matching</p>
<p>Haskell makes heavy use of pattern matching in function definitions.</p>
<pre class="code">greeting :: String -&gt; String
greeting &quot;&quot; = &quot;Hello, World!&quot;
greeting &quot;bub&quot; = &quot;Hey bub.&quot;
greeting name = &quot;Hello, &quot; ++ name ++ &quot;!&quot;
</pre>
<p>Perl 6 does this as well! You just use the <span class="code">multi</span> keyword to signify that it is a multiple dispatch function.</p>
<pre class="code">proto greeting ( Str --&gt; Str ) {*}
multi greeting ( &quot;&quot; --&gt; &quot;Hello, World!&quot; ) {}
multi greeting ( &quot;bub&quot; --&gt; &quot;Hey bub.&quot; ) {}
multi greeting ( \name ) { &quot;Hello, &quot; ~ name ~ &quot;!&quot; }
</pre>
<p>The <span class="code">proto</span> declarator is not necessary, but can sometimes aid in making sure that all multis follow your business rules. Using a variable name in the signature of the proto would provide more information in error messages, and for introspection.</p>
<pre class="code">proto greeting ( Str \name --&gt; Str ) {*}
say &amp;greeting.signature; # (Str \name --&gt; Str)
</pre>
<p>An interesting thing to note in the Perl 6 code above is that passing values like <span class="code">'bub'</span> as a function parameter is just syntax sugar for a <span class="code">where</span> guard.</p>
<p>Using the example from the &quot;Pattern Matching&quot; section of this page, you can see the guards that are used behind the scenes to constrain our function arguments.</p>
<pre class="code">multi greeting ( &quot;&quot; --&gt; &quot;Hello, World!&quot; ) {}
multi greeting ( &quot;bub&quot; --&gt; &quot;Hey bub.&quot; ) {}
# The above is the same as the below
multi greeting(Str \name where '' ) {'Hello, World!'}
multi greeting(Str \name where 'bub' ) {'Hey bub.'}
# The above is the same as the below, again.
multi greeting(Str \name where $_ ~~ '' ) {'Hello, World!'}
multi greeting(Str \name where $_ ~~ 'bub') {'Hey bub.'}
</pre>
<p><span class="code">$_</span> is known as the topic variable. It assumes the form of whatever is appropriate. The smart match operator <span class="code">~~</span> figures out the best way to determine if the left matches the right, be it number ranges, strings, etc. Our three examples above go from most sugared (top), to least sugared (bottom).</p>
<p>The bottom examples above could be wrapped in curly braces, making it more obvious that it is a code block. Note that a where clause may also take an explicit Callable.</p>
<pre class="code">multi greeting(Str \name where { $_ ~~ '' } ) {'Hello, World!'}
multi greeting(Str \name where -&gt; $thing { $thing ~~ '' } ) {'Hello, World!'}
multi greeting ( Str \name where { Bool.pick } --&gt; 'True' ){}
multi greeting ( Str \name where &amp;some-subroutine ){…}
</pre>
<p>If you read the section in this page on subsets, you'll notice that &quot;where&quot; is used in the making of subsets as well as here. The usage of &quot;where&quot; in both areas is exactly the same.</p>
<p>When using <span class="code">where</span>, note that the order of definition is important, just like in Haskell.</p>
<pre class="code">multi greeting ( Str \name where '' --&gt; 'Hello, World!' ){}
multi greeting ( Str \name where { Bool.pick } --&gt; 'True' ){}
multi greeting ( Str \name where 'bub' --&gt; 'Hey, bub.' ){}
say greeting '' ; # will never say True
say greeting 'bub'; # about 50% of the time it will say True
</pre>
<p>Deconstruction</p>
<p>TODO</p>
<a name="t21.2.2"></a> <h2 id="_language_haskell-to-p6.pod6-Currying">Currying</h2>
<p>TODO</p>
<p>.assuming vs currying</p>
<p>method chaining vs currying</p>
<a name="t21.2.3"></a> <h2 id="_language_haskell-to-p6.pod6-Composing">Composing</h2>
<p>TODO</p>
<p>show function composition operator. Maybe explain a more perl6ish way to do this though.</p>
<a name="t21.3"></a> <h1 id="_language_haskell-to-p6.pod6-Case_/_Matching">Case / Matching</h1>
<p>Haskell makes heavy use of case matching like the below:</p>
<pre class="code">case number of
2 -&gt; &quot;two&quot;
4 -&gt; &quot;four&quot;
8 -&gt; &quot;eight&quot;
_ -&gt; &quot;don't care&quot;
</pre>
<p>In Perl 6 you can achieve this same thing with the given/when structure:</p>
<pre class="code">my $number = {...};
given $number {
when 2 { &quot;two&quot; }
when 4 { &quot;four&quot; }
when 8 { &quot;eight&quot; }
default { &quot;don't care&quot; }
}
</pre>
<p>Note that the order of the <span class="code">when</span>'s is also significant, just like with the <span class="code">where</span>'s in the guard section of this page.</p>
<a name="t21.4"></a> <h1 id="_language_haskell-to-p6.pod6-Lists">Lists</h1>
<p>TODO</p>
<p>explain difference between perl6 Array, Sequence, List. Explain data shapes in regards to the <span class="code">@</span> sigil. Explain how you can convert an Array to a flattened list of objects with <span class="code">|@</span></p>
<p>data shapes become quite intuitive, but it takes a bit of practice.</p>
<a name="t21.4.1"></a> <h2 id="_language_haskell-to-p6.pod6-List_Comprehensions">List Comprehensions</h2>
<p>There are no explicit list comprehensions in Perl6. But rather, you can achieve list comprehensions a couple of different ways.</p>
<p>Here is a trivial example in Haskell:</p>
<pre class="code">evens = [ x | x &lt;- [0..100], even x ]
</pre>
<p>And now in Perl6 :</p>
<pre class="code"># using `if` and `for`
my @evens = ($_ if $_ %% 2 for 0..100);
# using gather/take to build a Seq
my $evens = gather for 0..100 { take $_ if $_ %% 2 };
# using gather/take to build an Array
my @evens = gather for 0..100 { take $_ if $_ %% 2 };
</pre>
<p>Since <span class="code">for</span> is always eager it is generally better to use <span class="code">map</span> or <span class="code">grep</span> which will inherit the laziness or eagerness of its list argument.</p>
<pre class="code">my @evens = map { $_ if $_ %% 2 }, 0..100;
my @evens = grep { $_ %% 2 }, 0..100;
# using a Whatever lambda
my @evens = grep * %% 2, 0..100;
</pre>
<p>Here is the creation of tuples in Haskell:</p>
<pre class="code">tuples = [(i,j) | i &lt;- [1,2],
j &lt;- [1..4] ]
-- [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]
</pre>
<p>And in Perl6:</p>
<pre class="code">my @tuples = 1,2 X 1..4;
# [(1,1), (1,2), (1,3), (1,4), (2,1), (2,2), (2,3), (2,4)]
</pre>
<p>See this design document for more information on what kinds of list comprehensions are possible in Perl6: http://design.perl6.org/S04.html#The_do-once_loop</p>
<p>As you can see, when you get into some more advanced Haskell list comprehensions, Perl6 does not translate exactly the same, but it's possible to do the same things, nonetheless.</p>
<a name="t21.4.2"></a> <h2 id="_language_haskell-to-p6.pod6-Fold">Fold</h2>
<p>Fold in Haskell is called Reduce in Perl 6.</p>
<pre class="code">mySum = foldl `+` 0 numList
</pre>
<pre class="code">my @numbers = {...};
reduce { $^a + $^b }, 0, |@numbers;
@numbers.reduce({$^a + $^b}, with =&gt; 0)
</pre>
<p>However, in Perl 6, if you want to use an infix operator (+ - / % etc) there is a nice little helper called the Reduction Metaoperator.</p>
<pre class="code">my @numbers = {...};
[+] @numbers # This is the same
[+] 0, @numbers # as this
</pre>
<p>It inserts the operator in between all values in the list and produces a result, just like Fold.</p>
<p>In Haskell you, you have foldl and foldr. In Perl 6, this difference is determined by the associativity attached to the operator/subroutine.</p>
<pre class="code">sub two-elem-list ( \a, \b ) { ( a, b ) }
# you can use a subroutine as an infix operator
say 'a' [&amp;two-elem-list] 'b'; # (a b)
# as the reduction prefix meta operator takes an infix operator, it will work there too;
[[&amp;two-elem-list]] 1..5; # ((((1 2) 3) 4) 5)
say (1..5).reduce: &amp;two-elem-list; # ((((1 2) 3) 4) 5)
# right associative
sub right-two-elem-list( \a, \b ) is assoc&lt;right&gt; { ( a, b ) }
say (1..5).reduce: &amp;right-two-elem-list; # (1 (2 (3 (4 5))))
# XXX there is possibly a bug here as this currently doesn't look at
# XXX the associativity of &amp;right-two-elem-list and just always does left assoc
say [[&amp;right-two-elem-list]] 1..5;
# chaining
say [&lt;] 1..5; # True
say (1..5).reduce: &amp;[&lt;]; # True
</pre>
<a name="t21.4.3"></a> <h2 id="_language_haskell-to-p6.pod6-Map">Map</h2>
<p>TODO</p>
<a name="t21.4.4"></a> <h2 id="_language_haskell-to-p6.pod6-Ranges">Ranges</h2>
<p>Haskell and Perl 6 both allow you to specify ranges of values.</p>
<pre class="code">myRange1 = 10..100
myRange2 = 1.. -- Infinite
myRange3 = 'a'..'h' -- Letters work too
</pre>
<pre class="code">my $range1 = 10..100;
my $range2 = 1..*; # Infinite
my $range3 = 'a'..'h'; # Letters work too
</pre>
<a name="t21.4.5"></a> <h2 id="_language_haskell-to-p6.pod6-Laziness_vs_Eagerness">Laziness vs Eagerness</h2>
<p>In the examples above, you have the concept of laziness displayed very plainly. Perl 6 has laziness only where it makes the most sense. For example, in the range 10..100, this is eager because it has a definite end. If a list does not have a definite end, then the list should clearly be lazy.</p>
<pre class="code">(1 .. 100).is-lazy; # False
(1 .. Inf).is-lazy; # True
</pre>
<p>These are the &quot;sane defaults&quot; that Perl 6 takes pride in. But they are still defaults and can be changed into one or the other.</p>
<pre class="code">(1 .. 100).lazy.is-lazy; # True
(1 .. 100).lazy.eager.is-lazy; # False
</pre>
<a name="t21.5"></a> <h1 id="_language_haskell-to-p6.pod6-Contexts_(let-in_/_where)">Contexts (let-in / where)</h1>
<p>TODO</p>
<p>explain how <span class="code">given/when</span> and <span class="code">with/without</span> and <span class="code">for loops</span> open lexical scopes with the argument as the context.</p>
<p>compare it to let/in and where constructs maybe?</p>
<a name="t21.6"></a> <h1 id="_language_haskell-to-p6.pod6-Parsers">Parsers</h1>
<a name="t21.6.1"></a> <h2 id="_language_haskell-to-p6.pod6-Parser_Combinators_vs_Grammars">Parser Combinators vs Grammars</h2>
<p>TODO</p>
</div>
<!-- /language/io-guide.pod6 --><div class="pod-body"><a id="_language_io-guide.pod6"></a><a name="t22"></a><h1 class="title">22 Input/Output The Definitive Guide</h1> <p class="subtitle">Correctly use Perl 6 IO</p> <a name="t22.1"></a> <h1 id="_language_io-guide.pod6-The_Basics">The Basics</h1>
<p>The vast majority of common IO work is done by the <a href="#_type_IO::Path.pod6">IO::Path</a> type. If you want to read from or write to a file in some form or shape, this is the class you want. It abstracts away the details of file handles (or &quot;file descriptors&quot;) and so you mostly don't even have to think about them.</p>
<p>Behind the scenes, <a href="#_type_IO::Path.pod6">IO::Path</a> works with <a href="#_type_IO::Handle.pod6">IO::Handle</a>; a class which you can use directly if you need a bit more control than what <a href="#_type_IO::Path.pod6">IO::Path</a> provides. When working with other processes, e.g. via <a href="#_type_Proc.pod6">Proc</a> or <a href="#_type_Proc::Async.pod6">Proc::Async</a> types, you'll also be dealing with a <i>subclass</i> of <a href="#_type_IO::Handle.pod6">IO::Handle</a>: the <a href="#_type_IO::Pipe.pod6">IO::Pipe</a>.</p>
<p>Lastly, you have the <a href="#_type_IO::CatHandle.pod6">IO::CatHandle</a>, as well as <a href="#_type_IO::Spec.pod6">IO::Spec</a> and its subclasses, that you'll rarely, if ever, use directly. These classes give you advanced features, such as operating on multiple files as one handle, or low-level path manipulations.</p>
<p>Along with all these classes, Perl 6 provides several subroutines that let you indirectly work with these classes. These come in handy if you like functional programming style or in Perl 6 one liners.</p>
<p>While <a href="#_type_IO::Socket.pod6">IO::Socket</a> and its subclasses also have to do with Input and Output, this guide does not cover them.</p>
<a name="t22.2"></a> <h1 id="_language_io-guide.pod6-Navigating_Paths">Navigating Paths</h1>
<a name="t22.2.1"></a> <h2 id="_language_io-guide.pod6-What's_an_IO::Path_Anyway?">What's an IO::Path Anyway?</h2>
<p>To represent paths as either files or directories, use <a href="#_type_IO::Path.pod6">IO::Path</a> type. The simplest way to obtain an object of that type is to coerce a <a href="#_type_Str.pod6">Str</a> by calling <a href="#_routine_IO.pod6"><span class="code">.IO</span></a> method on it:</p>
<pre class="code">say 'my-file.txt'.IO; # OUTPUT: «&quot;my-file.txt&quot;.IO␤»</pre>
<p>It may seem like something is missing here—there is no volume or absolute path involved—but that information is actually present in the object. You can see it by using <a href="#_routine_perl.pod6"><span class="code">.perl</span></a> method:</p>
<pre class="code">say 'my-file.txt'.IO.perl;
# OUTPUT: «IO::Path.new(&quot;my-file.txt&quot;, :SPEC(IO::Spec::Unix), :CWD(&quot;/home/camelia&quot;))␤»</pre>
<p>The two extra attributes—<span class="code">SPEC</span> and <span class="code">CWD</span>—specify what type of operating system semantics the path should use as well as the &quot;current working directory&quot; for the path, i.e. if it's a relative path, then it's relative to that directory.</p>
<p>This means that regardless of how you made one, an <a href="#_type_IO::Path.pod6">IO::Path</a> object technically always refers to an absolute path. This is why its <a href="#_routine_absolute.pod6"><span class="code">.absolute</span></a> and <a href="#_routine_relative.pod6"><span class="code">.relative</span></a> methods return <a href="#_type_Str.pod6">Str</a> objects and they are the correct way to stringify a path.</p>
<p>However, don't be in a rush to stringify anything. Pass paths around as <a href="#_type_IO::Path.pod6">IO::Path</a> objects. All the routines that operate on paths can handle them, so there's no need to convert them.</p>
<a name="t22.2.2"></a> <h2 id="_language_io-guide.pod6-Working_with_Files">Working with Files</h2>
<a name="t22.2.2.1"></a> <h3 id="_language_io-guide.pod6-Writing_into_files">Writing into files</h3>
<a name="t22.2.2.1.1"></a> <h4 id="_language_io-guide.pod6-Writing_new_content">Writing new content</h4>
<p>Let's make some files and write and read data from them! The <a href="#_routine_spurt.pod6"><span class="code">spurt</span></a> and <a href="#_routine_slurp.pod6"><span class="code">slurp</span></a> routines write and read the data in one chunk. Unless you're working with very large files that are difficult to store entirely in memory all at the same time, these two routines are for you.</p>
<pre class="code">&quot;my-file.txt&quot;.IO.spurt: &quot;I ♥ Perl!&quot;;
</pre>
<p>The code above creates a file named <span class="code">my-file.txt</span> in the current directory and then writes text <span class="code">I ♥ Perl!</span> into it. If Perl 6 is your first language, celebrate your accomplishment! Try to open the file you created with some other program to verify what you wrote with your program. If you already know some other language, you may be wondering if this guide missed anything like handling encoding or error conditions.</p>
<p>However, that is all the code you need. The string will be encoded in <span class="code">utf-8</span> encoding by default and the errors are handled via the <a href="#_type_Failure.pod6">Failure</a> mechanism: these are exceptions you can handle using regular conditionals. In this case, we're letting all potential <a href="#_type_Failure.pod6">Failures</a> get sunk after the call and so any <a href="#_type_Exception.pod6">Exceptions</a> they contain will be thrown.</p>
<a name="t22.2.2.1.2"></a> <h4 id="_language_io-guide.pod6-Appending_content">Appending content</h4>
<p>If you wanted to add more content to the file we made in previous section, you could note the <a href="#_routine_spurt.pod6"><span class="code">spurt</span> documentation</a> mentions <span class="code">:append</span> argument. However, for finer control, let's get ourselves an <a href="#_type_IO::Handle.pod6">IO::Handle</a> to work with:</p>
<pre class="code">my $fh = 'my-file.txt'.IO.open: :a;
$fh.print: &quot;I count: &quot;;
$fh.print: &quot;$_ &quot; for ^10;
$fh.close;
</pre>
<p>The <a href="#_routine_open.pod6"><span class="code">.open</span></a> method call opens our <a href="#_type_IO::Path.pod6">IO::Path</a> and returns an <a href="#_type_IO::Handle.pod6">IO::Handle</a>. We passed <span class="code">:a</span> as argument, to indicate we want to open the file for writing in append mode.</p>
<p>In the next two lines of code, we use the usual <a href="#_routine_print.pod6"><span class="code">.print</span></a> method on that <a href="#_type_IO::Handle.pod6">IO::Handle</a> to print a line with 11 pieces of text (the <span class="code">'I count: '</span> string and 10 numbers). Note that, once again, <a href="#_type_Failure.pod6">Failure</a> mechanism takes care of all the error checking for us. If the <a href="#_routine_open.pod6"><span class="code">.open</span></a> fails, it returns a <a href="#_type_Failure.pod6">Failure</a>, which will throw when we attempt to call method <a href="#_routine_print.pod6"><span class="code">.print</span></a> on it.</p>
<p>Finally, we close the <a href="#_type_IO::Handle.pod6">IO::Handle</a> by calling the <a href="#_routine_close.pod6"><span class="code">.close</span></a> method on it. It is <i>important that you do it</i>, especially in large programs or ones that deal with a lot of files, as many systems have limits to how many files a program can have open at the same time. If you don't close your handles, eventually you'll reach that limit and the <a href="#_routine_open.pod6"><span class="code">.open</span></a> call will fail. Note that unlike some other languages, Perl 6 does not use reference counting, so the file handles <b>are NOT closed</b> when the scope they're defined in is left. They will be closed only when they're garbage collected and failing to close the handles may cause your program to reach the file limit <i>before</i> the open handles get a chance to get garbage collected.</p>
<a name="t22.2.2.2"></a> <h3 id="_language_io-guide.pod6-Reading_from_files">Reading from files</h3>
<a name="t22.2.2.2.1"></a> <h4 id="_language_io-guide.pod6-Using_IO::Path">Using IO::Path</h4>
<p>We've seen in previous sections that writing stuff to files is a single-line of code in Perl 6. Reading from them, is similarly easy:</p>
<pre class="code">say 'my-file.txt'.IO.slurp; # OUTPUT: «I ♥ Perl!␤»
say 'my-file.txt'.IO.slurp: :bin; # OUTPUT: «Buf[uint8]:0x&lt;49 20 e2 99 a5 20 50 65 72 6c 21&gt;␤»
</pre>
<p>The <a href="#_routine_slurp.pod6"><span class="code">.slurp</span></a> method reads entire contents of the file and returns them as a single <a href="#_type_Str.pod6">Str</a> object, or as a <a href="#_type_Buf.pod6">Buf</a> object, if binary mode was requested, by specifying <span class="code">:bin</span> named argument.</p>
<p>Since <a href="#_routine_slurp.pod6">slurping</a> loads the entire file into memory, it's not ideal for working with huge files.</p>
<p>The <a href="#_type_IO::Path.pod6">IO::Path</a> type offers two other handy methods: <a href="#_type_IO::Path.pod6-method_words"><span class="code">.words</span></a> and <a href="#_type_IO::Path.pod6-method_lines"><span class="code">.lines</span></a> that lazily read the file in smaller chunks and return <a href="#_type_Seq.pod6">Seq</a> objects that (by default) don't keep already-consumed values around.</p>
<p>Here's an example that finds lines in a text file that mention Perl and prints them out. Despite the file itself being too large to fit into available <a href="https://en.wikipedia.org/wiki/Random-access_memory">RAM</a>, the program will not have any issues running, as the contents are processed in small chunks:</p>
<pre class="code">.say for '500-PetaByte-File.txt'.IO.lines.grep: *.contains: 'Perl';
</pre>
<p>Here's another example that prints the first 100 words from a file, without loading it entirely:</p>
<pre class="code">.say for '500-PetaByte-File.txt'.IO.words: 100
</pre>
<p>Note that we did this by passing a limit argument to <a href="#_type_IO::Path.pod6-method_words"><span class="code">.words</span></a> instead of, say, using <a href="#_language_operators.pod6-index-entry-array_indexing_operator-array_subscript_operator-array_indexing_operator">a list indexing operation</a>. The reason for that is there's still a file handle in use under the hood, and until you fully consume the returned <a href="#_type_Seq.pod6">Seq</a>, the handle will remain open. If nothing references the <a href="#_type_Seq.pod6">Seq</a>, eventually the handle will get closed, during a garbage collection run, but in large programs that work with a lot of files, it's best to ensure all the handles get closed right away. So, you should always ensure the <a href="#_type_Seq.pod6">Seq</a> from <a href="#_type_IO::Path.pod6">IO::Path</a>'s <a href="#_type_IO::Path.pod6-method_words"><span class="code">.words</span></a> and <a href="#_type_IO::Path.pod6-method_lines"><span class="code">.lines</span></a> methods is <a href="#_language_glossary.pod6-index-entry-Reify">fully reified</a>; and the limit argument is there to help you with that.</p>
<a name="t22.2.2.2.2"></a> <h4 id="_language_io-guide.pod6-Using_IO::Handle">Using IO::Handle</h4>
<p>Of course, you can read from files using the <a href="#_type_IO::Handle.pod6">IO::Handle</a> type, which gives you a lot finer control over what you're doing:</p>
<pre class="code">given 'some-file.txt'.IO.open {
say .readchars: 8; # OUTPUT: «I ♥ Perl␤»
.seek: 1, SeekFromCurrent;
say .readchars: 15; # OUTPUT: «I ♥ Programming␤»
.close
}
</pre>
<p>The <a href="#_type_IO::Handle.pod6">IO::Handle</a> gives you <a href="#_type_IO::Handle.pod6-method_read">.read</a>, <a href="#_type_IO::Handle.pod6-method_readchars">.readchars</a>, <a href="#_type_IO::Handle.pod6-routine_get">.get</a>, <a href="#_type_IO::Handle.pod6-method_getc">.getc</a>, <a href="#_type_IO::Handle.pod6-routine_words">.words</a>, <a href="#_type_IO::Handle.pod6-routine_lines">.lines</a>, <a href="#_type_IO::Handle.pod6-routine_slurp">.slurp</a>, <a href="#_type_IO::Handle.pod6-method_comb">.comb</a>, <a href="#_type_IO::Handle.pod6-method_split">.split</a>, and <a href="#_type_IO::Handle.pod6-method_Supply">.Supply</a> methods to read data from it. Plenty of options; and the catch is you need to close the handle when you're done with it.</p>
<p>Unlike some languages, the handle won't get automatically closed when the scope it's defined in is left. Instead, it'll remain open until it's garbage collected. To make the closing business easier, some of the methods let you specify a <span class="code">:close</span> argument, you can also use the <a href="#_language_phasers.pod6-index-entry-will_trait"><span class="code">will leave</span> trait</a>, or the <span class="code">does auto-close</span> trait provided by the <a href="https://modules.perl6.org/dist/Trait::IO"><span class="code">Trait::IO</span></a> module.</p>
<a name="t22.3"></a> <h1 id="_language_io-guide.pod6-The_Wrong_Way_To_Do_Things">The Wrong Way To Do Things</h1>
<p>This section describes how NOT to do Perl 6 IO.</p>
<a name="t22.3.1"></a> <h2 id="_language_io-guide.pod6-Leave_$*SPEC_Alone">Leave $*SPEC Alone</h2>
<p>You may have heard of <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*SPEC</span></a> and seen some code or books show its usage for splitting and joining path fragments. Some of the routine names it provides may even look familiar to what you've used in other languages.</p>
<p>However, unless you're writing your own IO framework, you almost never need to use <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*SPEC</span></a> directly. <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*SPEC</span></a> provides low-level stuff and its use will not only make your code tough to read, you'll likely introduce security issues (e.g. null characters)!</p>
<p>The <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a> type is the workhorse of Perl 6 world. It caters to all the path manipulation needs as well as provides shortcut routines that let you avoid dealing with file handles. Use that instead of the <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*SPEC</span></a> stuff.</p>
<p>Tip: you can join path parts with <span class="code">/</span> and feed them to <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a>'s routines; they'll still do The Right Thing™ with them, regardless of the operating system.</p>
<pre class="code"># WRONG!! TOO MUCH WORK!
my $fh = open $*SPEC.catpath: '', 'foo/bar', $file;
my $data = $fh.slurp;
$fh.close;
</pre>
<pre class="code"># RIGHT! Use IO::Path to do all the dirty work
my $data = 'foo/bar'.IO.add($file).slurp;
</pre>
<p>However, it's fine to use it for things not otherwise provided by <a href="#_type_IO::Path.pod6">IO::Path</a>. For example, the <a href="#_routine_devnull.pod6"><span class="code">.devnull</span> method</a>:</p>
<pre class="code">{
temp $*OUT = open :w, $*SPEC.devnull;
say &quot;In space no one can hear you scream!&quot;;
}
say &quot;Hello&quot;;
</pre>
<a name="t22.3.2"></a> <h2 id="_language_io-guide.pod6-Stringifying_IO::Path">Stringifying IO::Path</h2>
<p>Don't use the <span class="code">.Str</span> method to stringify <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a> objects, unless you just want to display them somewhere for information purposes or something. The <span class="code">.Str</span> method returns whatever basic path string the <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a> was instantiated with. It doesn't consider the value of the <a href="#_type_IO::Path.pod6-attribute_CWD"><span class="code">$.CWD</span> attribute</a>. For example, this code is broken:</p>
<pre class="code"># WRONG!! .Str DOES NOT USE $.CWD!
my $path = 'foo'.IO;
chdir 'bar';
run &lt;tar -cvvf archive.tar&gt;, ~$path;
</pre>
<p>The <a href="#_routine_chdir.pod6"><span class="code">chdir</span></a> call changed the value of the current directory, but the <span class="code">$path</span> we created is relative to the directory before that change.</p>
<p>However, the <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a> object <i>does</i> know what directory it's relative to. We just need to use <a href="#_routine_absolute.pod6"><span class="code">.absolute</span></a> or <a href="#_routine_relative.pod6"><span class="code">.relative</span></a> to stringify the object. Both routines return a <a href="#_type_Str.pod6"><span class="code">Str</span></a> object; they only differ in whether the result is an absolute or relative path. So, we can fix our code like this:</p>
<pre class="code"># RIGHT!! .absolute does consider the value of $.CWD!
my $path = 'foo'.IO;
chdir 'bar';
run &lt;tar -cvvf archive.tar&gt;, $path.absolute;
# Also good:
run &lt;tar -cvvf archive.tar&gt;, $path.relative;
</pre>
<a name="t22.3.3"></a> <h2 id="_language_io-guide.pod6-Be_mindful_of_$*CWD">Be mindful of $*CWD</h2>
<p>While usually out of view, every <a href="#_type_IO::Path.pod6"><span class="code">IO::Path</span></a> object, by default, uses the current value of <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*CWD</span></a> to set its <a href="#_type_IO::Path.pod6-attribute_CWD"><span class="code">$.CWD</span> attribute</a>. This means there are two things to pay attention to.</p>
<a name="t22.3.3.1"></a> <h3 id="_language_io-guide.pod6-temp_the_$*CWD">temp the $*CWD</h3>
<p>This code is a mistake:</p>
<pre class="code"># WRONG!!
my $*CWD = &quot;foo&quot;.IO;
</pre>
<p>The <span class="code">my $*CWD</span> made <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*CWD</span></a> undefined. The <a href="#_routine_IO.pod6"><span class="code">.IO</span></a> coercer then goes ahead and sets the <a href="#_type_IO::Path.pod6-attribute_CWD"><span class="code">$.CWD</span> attribute</a> of the path it's creating to the stringified version of the undefined <span class="code">$*CWD</span>; an empty string.</p>
<p>The correct way to perform this operation is use <a href="#_routine_temp.pod6"><span class="code">temp</span></a> instead of <span class="code">my</span>. It'll localize the effect of changes to <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*CWD</span></a>, just like <span class="code">my</span> would, but it won't make it undefined, so the <a href="#_routine_IO.pod6"><span class="code">.IO</span></a> coercer will still get the correct old value:</p>
<pre class="code">temp $*CWD = &quot;foo&quot;.IO;
</pre>
<p>Better yet, if you want to perform some code in a localized <a href="#_language_variables.pod6-Dynamic_variables"><span class="code">$*CWD</span></a>, use the <a href="#_routine_indir.pod6"><span class="code">indir</span> routine</a> for that purpose.</p>
</div>
<!-- /language/io.pod6 --><div class="pod-body"><a id="_language_io.pod6"></a><a name="t23"></a><h1 class="title">23 Input/Output</h1> <p class="subtitle">File-related operations</p> <p>Here we present a quick overview of the file-related input/output operations. Details can be found in the documentation for the <a href="#_type_IO.pod6">IO</a> role, as well as the <a href="#_type_IO::Handle.pod6">IO::Handle</a> and <a href="#_type_IO::Path.pod6">IO::Path</a> types.</p>
<a name="t23.1"></a> <h1 id="_language_io.pod6-Reading_from_files">Reading from files</h1>
<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 &quot;testfile&quot;, :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 = &quot;testfile&quot;.IO.slurp;
# or in procedural form:
$contents = slurp &quot;testfile&quot;
</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="t23.1.1"></a> <h2 id="_language_io.pod6-Line_by_line">Line by line</h2>
<p>Of course, we also have the option to read a file line-by-line. The new line separator (i.e., <span class="code">$*IN.nl-in</span>) will be excluded.</p>
<pre class="code">for 'huge-csv'.IO.lines -&gt; $line {
# Do something with $line
}
# or if you'll be processing later
my @lines = 'huge-csv'.IO.lines;
</pre>
<a name="t23.2"></a> <h1 id="_language_io.pod6-Writing_to_files">Writing to files</h1>
<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 &quot;testfile&quot;, :w;
$fh.print(&quot;data and stuff\n&quot;);
$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 &quot;testfile&quot;, :w;
$fh.say(&quot;data and stuff&quot;);
$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 &quot;testfile&quot;, &quot;data and stuff\n&quot;;
</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 &quot;testfile&quot;, &quot;latin1 text: äöüß&quot;, enc =&gt; &quot;latin1&quot;;
</pre>
<p>To write formatted strings to a file, use the <a href="#_routine_printf.pod6">printf</a> function of <a href="#_type_IO::Handle.pod6">IO::Handle</a>.</p>
<pre class="code">my $fh = open &quot;testfile&quot;, :w;
$fh.printf(&quot;formatted data %04d\n&quot;, 42);
$fh.close;
</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 &quot;testfile&quot;, :a;
$fh.print(&quot;more data\n&quot;);
$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 &quot;testfile&quot;, :a;
$fh.say(&quot;more data&quot;);
$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 &quot;testfile&quot;, &quot;more data\n&quot;, :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="t23.3"></a> <h1 id="_language_io.pod6-Copying_and_renaming_files">Copying and renaming files</h1>
<p>Routines <span class="code">copy</span>, <span class="code">rename</span>, and <span class="code">move</span> are available to avoid low-level system commands. See details at <a href="#_routine_copy.pod6">copy</a>, <a href="#_routine_rename.pod6">rename</a>, and <a href="#_routine_move.pod6">move</a>. Some examples:</p>
<pre class="code">my $filea = 'foo';
my $fileb = 'foo.bak';
my $filec = '/disk1/foo'; # note 'diskN' is assumed to be a physical storage device
copy $filea, $fileb; # overwrites $fileb if it exists
copy $filea, $fileb, :createonly; # fails if $fileb exists
rename $filea, 'new-foo'; # overwrites 'new-foo' if it exists
rename $filea, 'new-foo', :createonly; # fails if 'new-foo' exists
# use move when a system-level rename may not work
move $fileb, '/disk2/foo'; # overwrites '/disk2/foo' if it exists
move $fileb, '/disk2/foo', :createonly; # fails if '/disk2/foo' exists
</pre>
<a name="t23.4"></a> <h1 id="_language_io.pod6-Checking_files_and_directories">Checking files and directories</h1>
<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 &quot;nonexistent_file&quot;.IO.e {
say &quot;file exists&quot;;
}
else {
say &quot;file doesn't exist&quot;;
}
</pre>
<p>It is also possible to use the colon pair syntax to achieve the same thing:</p>
<pre class="code">if &quot;path/to/file&quot;.IO ~~ :e {
say 'file exists';
}
</pre>
<pre class="code">my $file = &quot;path/to/file&quot;;
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 &quot;testfile&quot;.IO.e; # OUTPUT: «True␤»
say &quot;lib&quot;.IO.e; # OUTPUT: «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 &quot;testfile&quot;.IO.d; # OUTPUT: «False␤»
say &quot;lib&quot;.IO.d; # OUTPUT: «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 &quot;testfile&quot;.IO.f; # OUTPUT: «True␤»
say &quot;lib&quot;.IO.f; # OUTPUT: «False␤»
</pre>
<p>There are other methods that can be used to query a file or directory, some useful ones are:</p>
<pre class="code">my $f = &quot;file&quot;;
say $f.IO.modified; # return time of last file (or directory) change
say $f.IO.accessed; # return last time file (or directory) was read
say $f.IO.s; # return size of file (or directory inode) in bytes
</pre>
<p>See more methods and details at <a href="#_type_IO::Path.pod6">IO::Path</a>.</p>
<a name="t23.5"></a> <h1 id="_language_io.pod6-Getting_a_directory_listing">Getting a directory listing</h1>
<p>To list the contents of the current directory, use the <span class="code">dir</span> function. It returns a list of <a href="#_type_IO::Path.pod6">IO::Path</a> objects.</p>
<pre class="code">say dir; # OUTPUT: «&quot;/path/to/testfile&quot;.IO &quot;/path/to/lib&quot;.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 &quot;/etc/&quot;; # OUTPUT: «&quot;/etc/ld.so.conf&quot;.IO &quot;/etc/shadow&quot;.IO ....␤»</pre>
<a name="t23.6"></a> <h1 id="_language_io.pod6-Creating_and_removing_directories">Creating and removing directories</h1>
<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 &quot;newdir&quot;;
</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 &quot;newdir&quot; or die &quot;$!&quot;;
</pre>
<p>Use <span class="code">rmdir</span> to remove <i>empty</i> directories:</p>
<pre class="code">rmdir &quot;newdir&quot; or die &quot;$!&quot;;
</pre>
</div>
<!-- /language/ipc.pod6 --><div class="pod-body"><a id="_language_ipc.pod6"></a><a name="t24"></a><h1 class="title">24 Inter-Process Communication</h1> <p class="subtitle">Programs running other programs and communicating with them</p> <p><a id="i249" name="IPC"></a><span class="indexed"></span></p>
<a name="t24.1"></a> <h1 id="_language_ipc.pod6-running"><a name="250"></a>running</h1>
<p>Many programs need to be able to run other programs. Running a program in Perl 6 is as easy as:</p>
<pre class="code">run 'git', 'status';</pre>
<p>This line runs the program named &quot;git&quot; and passes &quot;git&quot; and &quot;status&quot; to its command-line. It will find the program using the <span class="code">%*ENV&lt;PATH&gt; </span> setting.</p>
<p>If you would like to run a program by sending a command-line to the shell, there's a tool for that as well. All shell meta characters are interpreted by the shell, including pipes, redirects, environment variable substitutions and so on.</p>
<pre class="code">shell 'ls -lR | gzip -9 &gt; ls-lR.gz';</pre>
<p>Caution should be taken when using <span class="code">shell</span> with user input.</p>
<a name="t24.2"></a> <h1 id="_language_ipc.pod6-proc"><a name="251"></a>proc</h1>
<p>Both <span class="code">run</span> and <span class="code">shell</span> return a <a href="#_type_Proc.pod6">Proc</a> object, which can be used to communicate with the process in more detail. Please note that unless you close all output pipes, the program will usually not terminate.</p>
<pre class="code">my $git = run 'git', 'log', '--oneline', :out;
for $git.out.lines -&gt; $line {
my ($sha, $subject) = $line.split: ' ', 2;
say &quot;$subject [$sha]&quot;;
}
$git.out.close();</pre>
<p>If the program fails (exits with a non-zero exit code), it will throw an exception when the returned <a href="#_type_Proc.pod6">Proc</a> object is sunk. You can save it into a variable, even anonymous one, to prevent the sinking:</p>
<pre class="code">$ = run '/bin/false'; # does not sink the Proc and so does not throw</pre>
<p>You can tell the <span class="code">Proc</span> object to capture output as a file handle by passing the <span class="code">:out</span> and <span class="code">:err</span> flags. You may also pass input via the <span class="code">:in</span> flag.</p>
<pre class="code">my $echo = run 'echo', 'Hello, world', :out;
my $cat = run 'cat', '-n', :in($echo.out), :out;
say $cat.out.get;
$cat.out.close();</pre>
<p>You may also use <span class="code">Proc</span> to capture the PID, send signals to the application, and check the exitcode.</p>
<pre class="code">my $crontab = run 'crontab', '-l';
if $crontab.exitcode == 0 {
say 'crontab -l ran ok';
}
else {
say 'something went wrong';
}</pre>
<a name="t24.3"></a> <h1 id="_language_ipc.pod6-async"><a name="252"></a>async</h1>
<p>When you need more control over the communication with and from another process, you will want to make use of <a href="#_type_Proc::Async.pod6">Proc::Async</a>. This class provides support for asynchronous communication with a program, as well as the ability to send signals to that program.</p>
<pre class="code"># Get ready to run the program
my $log = Proc::Async.new('tail', '-f', '/var/log/system.log');
$log.stdout.tap(-&gt; $buf { print $buf });
$log.stderr.tap(-&gt; $buf { $*ERR.print($buf) });
# Start the program
my $done = $log.start;
sleep 10;
# Tell the program to stop
$log.kill('QUIT');
# Wait for the program to finish
await $done;
</pre>
<p>Here is a small program that uses the &quot;tail&quot; program to print out the contents of the log named <span class="code">system.log</span> for 10 seconds and then tells the program to stop with a QUIT signal.</p>
<p>Whereas <span class="code">Proc</span> provides access to output using <span class="code">IO::Handle</span>s, <span class="code">Proc::Async</span> provides access using asynchronous supplies (see <a href="#_type_Supply.pod6">Supply</a>).</p>
<p>If you want to run a program and do some work while you wait for the original program to finish, the <span class="code">start</span> routine returns a <a href="#_type_Promise.pod6">Promise</a>, which is kept when the program quits.</p>
<p>Use the <span class="code">write</span> method to pass data into the program.</p>
</div>
<!-- /language/list.pod6 --><div class="pod-body"><a id="_language_list.pod6"></a><a name="t25"></a><h1 class="title">25 Lists, Sequences, and Arrays</h1> <p class="subtitle">Positional data constructs</p> <p>Lists have been a central part of computing since before there were computers, during which time many devils have taken up residence in their details. They were actually one of the hardest parts of Perl 6 to design, but through persistence and patience, Perl 6 has arrived with an elegant system for handling them.</p>
<a name="t25.1"></a> <h1 id="_language_list.pod6-Literal_Lists">Literal Lists</h1>
<p>Literal <a href="#_type_List.pod6"><span class="code">List</span> s</a> are created with commas and semicolons <b>not</b> with parentheses, so:</p>
<pre class="code">1, 2; # This is two-element list
(1, 2); # This is also a List, in parentheses
(1; 2); # same List (see below)
(1); # This is not a List, just a 1 in parentheses
(1,); # This is a one-element List</pre>
<p>There is one exception, empty lists are created with just parenthesis:</p>
<pre class="code"> (); # This is an empty List
(,); # This is a syntax error
</pre>
<p>Note that hanging commas are just fine as long as the beginning and end of a list are clear, so feel free to use them for easy code editing.</p>
<p>Parentheses can be used to mark the beginning and end of a <span class="code">List</span>, so:</p>
<pre class="code">(1, 2), (1, 2); # This is a list of two lists.</pre>
<p><span class="code">List</span>s of <span class="code">List</span>s can also be created by combining comma and semicolon. This is also called multi-dimensional syntax, because it is most often used to index multidimensional arrays.</p>
<pre class="code">say so (1,2; 3,4) eqv ((1,2), (3,4));
# OUTPUT: «True␤»
say so (1,2; 3,4;) eqv ((1,2), (3,4));
# OUTPUT: «True␤»
say so (&quot;foo&quot;;) eqv (&quot;foo&quot;) eqv ((&quot;foo&quot;)); # not a list
# OUTPUT: «True␤»</pre>
<p>Unlike a comma, a hanging semicolon does not create a multidimensional list in a literal. However, be aware that this behavior changes in most argument lists, where the exact behavior depends on the function... but will usually be:</p>
<pre class="code">say('foo';); # a list with one element and the empty list
# OUTPUT: «(foo)()␤»
say(('foo';)); # no list, just the string &quot;foo&quot;
# OUTPUT: «foo␤»</pre>
<p>Because the semicolon doubles as a <a href="#_language_control.pod6-statements">statement terminator</a> it will end a literal list when used at the top level, instead creating a statement list. If you want to create a statement list inside parenthesis, use a sigil before the parenthesis:</p>
<pre class="code">say so (42) eqv $(my $a = 42; $a;);
# OUTPUT: «True␤»
say so (42,42) eqv (my $a = 42; $a;);
# OUTPUT: «True␤»</pre>
<p>Individual elements can be pulled out of a list using a subscript. The first element of a list is at index number zero:</p>
<pre class="code">say (1, 2)[0]; # says 1
say (1, 2)[1]; # says 2
say (1, 2)[2]; # says Nil
say (1, 2)[-1]; # Error
say ((&lt;a b&gt;,&lt;c d&gt;),(&lt;e f&gt;,&lt;g h&gt;))[1;0;1]; # says &quot;f&quot;
</pre>
<a name="t25.2"></a> <h1 id="_language_list.pod6-The_@_sigil">The @ sigil</h1>
<p>Variables in Perl 6 whose names bear the <span class="code">@</span> sigil are expected to contain some sort of list-like object. Of course, other variables may also contain these objects, but <span class="code">@</span>-sigiled variables always do, and are expected to act the part.</p>
<p>By default, when you assign a <span class="code">List</span> to an <span class="code">@</span>-sigiled variable, you create an <span class="code">Array</span>. Those are described below. If, instead you want to put an actual <span class="code">List</span> into an <span class="code">@</span>-sigiled variable, you can use binding with <span class="code">:=</span> instead.</p>
<pre class="code">my @a := 1, 2, 3;</pre>
<p>One of the ways <span class="code">@</span>-sigiled variables act like lists is by always supporting <a href="#_language_subscripts.pod6">positional subscripting</a>. Anything bound to a <span class="code">@</span>-sigiled value must support the <a href="#_type_Positional.pod6">Positional</a> role which guarantees this:</p>
<pre class="code">my @a := 1; # Type check failed in binding; expected Positional but got Int</pre>
<a name="t25.3"></a> <h1 id="_language_list.pod6-Reset_a_List_Container">Reset a List Container</h1>
<p>To remove all elements from a Positional container assign <a href="#_type_Slip.pod6-Empty"><span class="code">Empty</span></a>, the empty list <span class="code">()</span> or a <span class="code">Slip</span> of the empty list to the container.</p>
<pre class="code">my @a = 1, 2, 3;
@a = ();
@a = Empty;
@a = |();</pre>
<a name="t25.4"></a> <h1 id="_language_list.pod6-Iteration">Iteration</h1>
<p>All lists may be iterated, which means taking each element from the list in order and stopping after the last element:</p>
<pre class="code">for 1, 2, 3 { .say } # OUTPUT: «1␤2␤3␤»</pre>
<a name="t25.5"></a> <h1 id="_language_list.pod6-Testing_for_Elements">Testing for Elements</h1>
<p>To test for elements convert the <span class="code">List</span> or <span class="code">Array</span> to a <a href="#_type_Set.pod6"><span class="code">Set</span></a> or use a Set <a href="#_language_setbagmix.pod6">operator</a>.</p>
<pre class="code">my @a = &lt;foo bar buzz&gt;;
say @a.Set&lt;bar buzz&gt;; # OUTPUT: «(True True)␤»
say so 'bar' ∈ @a; # OUTPUT: «True␤»</pre>
<a name="t25.5.1"></a> <h2 id="_language_list.pod6-Sequences">Sequences</h2>
<p>Not all lists are born full of elements. Some only create as many elements as they are asked for. These are called sequences, which are of type <a href="#_type_Seq.pod6">Seq</a>. As it so happens, loops return <span class="code">Seq</span>s.</p>
<pre class="code">(loop { 42.say })[2] # OUTPUT: «42␤42␤42␤»</pre>
<p>So, it is fine to have infinite lists in Perl 6, just so long as you never ask them for all their elements. In some cases, you may want to avoid asking them how long they are too – Perl 6 will try to return <span class="code">Inf</span> if it knows a sequence is infinite, but it cannot always know.</p>
TODO link or describe C&lt;...&gt;
<p>Although the <span class="code">Seq</span> class does provide some positional subscripting, it does not provide the full interface of <span class="code">Positional</span>, so an <span class="code">@</span>-sigiled variable may <b>not</b> be bound to a <span class="code">Seq</span>.</p>
<pre class="code">my @s := Seq.new(&lt;a b c&gt;); CATCH { default { say .^name, ' ', .Str } }
# OUTPUT «Type check failed in binding to $iter; expected Iterator but got List ($(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;))␤ in block &lt;unit&gt; at &lt;tmp&gt; line 1␤␤»</pre>
<p>This is because the <span class="code">Seq</span> does not keep values around after you have used them. This is useful behavior if you have a very long sequence, as you may want to throw values away after using them, so that your program does not fill up memory. For example, when processing a file of a million lines:</p>
<pre class="code">for 'filename'.IO.lines -&gt; $line {
do-something-with($line);
}
</pre>
<p>You can be confident that the entire content of the file will not stay around in memory, unless you are explicitly storing the lines somewhere.</p>
<p>On the other hand, you may want to keep old values around in some cases. It is possible to hide a <span class="code">Seq</span> inside a <span class="code">List</span>, which will still be lazy, but will remember old values. This is done by calling the <span class="code">.list</span> method. Since this <span class="code">List</span> fully supports <span class="code">Positional</span>, you may bind it directly to an <span class="code">@</span>-sigiled variable.</p>
<pre class="code">my @s := (loop { 42.say }).list;
@s[2]; # says 42 three times
@s[1]; # does not say anything
@s[4]; # says 42 two more times</pre>
<p>You may also use the <span class="code">.cache</span> method instead of <span class="code">.list</span>, depending on how you want the references handled. See the <a href="#_type_Seq.pod6">page on <span class="code">Seq</span></a> for details.</p>
TODO document .iterator
<a name="t25.5.2"></a> <h2 id="_language_list.pod6-Slips">Slips</h2>
<p>Sometimes you want to insert the elements of a list into another list. This can be done with a special type of list called a <a href="#_type_Slip.pod6">Slip</a>.</p>
<pre class="code">say (1, (2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «False␤»
say (1, Slip.new(2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «True␤»
say (1, slip(2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «True␤»</pre>
<p>Another way to make a <span class="code">Slip</span> is with the <span class="code">|</span> prefix operator. Note that this has a tighter precedence than the comma, so it only affects a single value, but unlike the above options, it will break <a href="#_type_Scalar.pod6">Scalars</a>.</p>
<pre class="code">say (1, |(2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «True␤»
say (1, |$(2, 3), 4) eqv (1, 2, 3, 4); # OUTPUT: «True␤»
say (1, slip($(2, 3)), 4) eqv (1, 2, 3, 4); # OUTPUT: «False␤»</pre>
<a name="t25.6"></a> <h1 id="_language_list.pod6-Lazy_Lists">Lazy Lists <a name="253"></a></h1>
<p>Lists can be lazy, what means that their values are computed on demand and stored for later use. To create a lazy list use <a href="#_language_control.pod6-gather/take">gather/take</a> or the <a href="#_language_operators.pod6-infix_...">sequence operator</a>. You can also write a class that implements the role <a href="#_type_Iterable.pod6">Iterable</a> and returns <span class="code">True</span> on a call to <a href="#_routine_is-lazy.pod6">is-lazy</a>. Please note that some methods like <span class="code">elems</span> cannot be called on a lazy List and will result in a thrown <a href="#_type_Exception.pod6">Exception</a>.</p>
<pre class="code"># This list is lazy and elements will not be available
# until explicitly requested.
my @l = lazy 0..5;
say @l.is-lazy; # OUTPUT: «True␤»
say @l[]; # OUTPUT: «[...]␤»
# Once all elements have been retrieved, the List
# is no longer considered lazy.
eager @l; # Forcing eager evaluation
say @l.is-lazy; # OUTPUT: «False␤»
say @l[]; # OUTPUT: «[0 1 2 3 4 5]␤»</pre>
<p>A common use case for lazy Lists are the processing of infinite sequences of numbers, whose values have not been computed yet and cannot be computed in their entirety. Specific values in the List will only be computed when they are needed.</p>
<pre class="code">my @l = 1, 2, 4, 8 ... Inf;
say @l[0..16];
# OUTPUT: «(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536)␤»</pre>
<a name="t25.7"></a> <h1 id="_language_list.pod6-Immutability">Immutability</h1>
<p>The lists we have talked about so far (<span class="code">List</span>, <span class="code">Seq</span> and <span class="code">Slip</span>) are all immutable. This means you cannot remove elements from them, or re-bind existing elements:</p>
<pre class="code">(1, 2, 3)[0]:delete; # Error Can not remove elements from a List
(1, 2, 3)[0] := 0; # Error Cannot use bind operator with this left-hand side
(1, 2, 3)[0] = 0; # Error Cannot modify an immutable Int
</pre>
<p>However, if any of the elements is wrapped in a <a href="#_type_Scalar.pod6"><span class="code">Scalar</span></a> you can still change the value which that <span class="code">Scalar</span> points to:</p>
<pre class="code">my $a = 2;
(1, $a, 3)[1] = 42;
$a.say; # OUTPUT: «42␤»</pre>
<p>...that is, it is only the list structure itself – how many elements there are and each element's identity – that is immutable. The immutability is not contagious past the identity of the element.</p>
<a name="t25.8"></a> <h1 id="_language_list.pod6-List_Contexts">List Contexts</h1>
<p>So far we have mostly dealt with lists in neutral contexts. Lists are actually very context sensitive on a syntactical level.</p>
<a name="t25.8.1"></a> <h2 id="_language_list.pod6-List_Assignment_Context">List Assignment Context</h2>
<p>When a list appears on the right hand side of an assignment into a <span class="code">@</span>-sigiled variable, it is &quot;eagerly&quot; evaluated. This means that a <span class="code">Seq</span> will be iterated until it can produce no more elements. This is one of the places you do not want to put an infinite list, lest your program hang and, eventually, run out of memory:</p>
<pre class="code">my $i = 3;
my @a = (loop { $i.say; last unless --$i }); # OUTPUT: «3␤2␤1␤»
say &quot;take off!&quot;;</pre>
<a name="t25.8.2"></a> <h2 id="_language_list.pod6-Flattening_&quot;Context&quot;">Flattening &quot;Context&quot;</h2>
<p>When you have a list that contains sub-lists, but you only want one flat list, you may flatten the list to produce a sequence of values as if all parentheses were removed. This works no matter how many levels deep the parentheses are nested.</p>
<pre class="code">say (1, (2, (3, 4)), 5).flat eqv (1, 2, 3, 4, 5) # OUTPUT: «True␤»</pre>
<p>This is not really a syntactical &quot;context&quot; as much as it is a process of iteration, but it has the appearance of a context.</p>
<p>Note that <a href="#_type_Scalar.pod6"><span class="code">Scalar</span> s</a> around a list will make it immune to flattening:</p>
<pre class="code">for (1, (2, $(3, 4)), 5).flat { .say } # OUTPUT: «1␤2␤(3 4)␤5␤»</pre>
<p>...but an <span class="code">@</span>-sigiled variable will spill its elements.</p>
<pre class="code">my @l := 2, (3, 4);
for (1, @l, 5).flat { .say }; # OUTPUT: «1␤2␤3␤4␤5␤»
my @a = 2, (3, 4); # Arrays are special, see below
for (1, @a, 5).flat { .say }; # OUTPUT: «1␤2␤(3 4)␤5␤»</pre>
<a name="t25.8.3"></a> <h2 id="_language_list.pod6-Argument_List_(Capture)_Context">Argument List (Capture) Context</h2>
<p>When a list appears as arguments to a function or method call, special syntax rules are at play: the list is immediately converted into a <span class="code">Capture</span>. A <span class="code">Capture</span> itself has a List (<span class="code">.list</span>) and a Hash (<span class="code">.hash</span>). Any <span class="code">Pair</span> literals whose keys are not quoted, or which are not parenthesized, never make it into <span class="code">.list</span>. Instead, they are considered to be named arguments and squashed into <span class="code">.hash</span>. See the <a href="#_type_Capture.pod6">page on <span class="code">Capture</span></a> for the details of this processing.</p>
<p>Consider the following ways to make a new <span class="code">Array</span> from a <span class="code">List</span>. These ways place the <span class="code">List</span> in an argument list context and because of that, the <span class="code">Array</span> only contains <span class="code">1</span> and <span class="code">2</span> but not the <span class="code">Pair</span> <span class="code">:c(3)</span>, which is ignored.</p>
<pre class="code">Array.new(1, 2, :c(3));
Array.new: 1, 2, :c(3);
new Array: 1, 2, :c(3);</pre>
<p>In contrast, these ways do not place the <span class="code">List</span> in argument list context, so all the elements, even the <span class="code">Pair</span> <span class="code">:c(3)</span>, are placed in the <span class="code">Array</span>.</p>
<pre class="code">Array.new((1, 2, :c(3)));
(1, 2, :c(3)).Array;
my @a = 1, 2, :c(3); Array.new(@a);
my @a = 1, 2, :c(3); Array.new: @a;
my @a = 1, 2, :c(3); new Array: @a;</pre>
<p>In argument list context the <span class="code">|</span> prefix operator applied to a <span class="code">Positional</span> will always slip list elements as positional arguments to the Capture, while a <span class="code">|</span> prefix operator applied to an <span class="code">Associative</span> will slip pairs in as named parameters:</p>
<pre class="code">my @a := 2, &quot;c&quot; =&gt; 3;
Array.new(1, |@a, 4); # Array contains 1, 2, :c(3), 4
my %a = &quot;c&quot; =&gt; 3;
Array.new(1, |%a, 4); # Array contains 1, 4</pre>
<a name="t25.8.4"></a> <h2 id="_language_list.pod6-Slice_Indexing_Context">Slice Indexing Context</h2>
<p>From the perspective of the <span class="code">List</span> inside a <a href="#_language_subscripts.pod6-Slices">slice subscript</a>, is only remarkable in that it is unremarkable: because <a href="#_language_subscripts.pod6-Adverbs">adverbs</a> to a slice are attached after the <span class="code">]</span>, the inside of a slice is <b>not</b> an argument list, and no special processing of pair forms happens.</p>
<p>Most <span class="code">Positional</span> types will enforce an integer coercion on each element of a slice index, so pairs appearing there will generate an error, anyway:</p>
<pre class="code">(1, 2, 3)[1, 2, :c(3)] # OUTPUT: «Method 'Int' not found for invocant of class 'Pair'␤»
</pre>
<p>...however this is entirely up to the type – if it defines an order for pairs, it could consider <span class="code">:c(3)</span> a valid index.</p>
<p>Indices inside a slice are usually not automatically flattened, but neither are sublists usually coerced to <span class="code">Int</span>. Instead, the list structure is kept intact, causing a nested slice operation that replicates the structure in the result:</p>
<pre class="code">say (&quot;a&quot;, &quot;b&quot;, &quot;c&quot;)[(1, 2), (0, 1)] eqv ((&quot;b&quot;, &quot;c&quot;), (&quot;a&quot;, &quot;b&quot;)) # OUTPUT: «True␤»</pre>
<a name="t25.8.5"></a> <h2 id="_language_list.pod6-Range_as_Slice">Range as Slice</h2>
<p>A <a href="#_type_Range.pod6"><span class="code">Range</span></a> is a container for a lower and a upper boundary. Generating a slice with a <span class="code">Range</span> will include any index between those bounds, including the bounds. For infinite upper boundaries we agree with mathematicians that <span class="code">Inf</span> equals <span class="code">Inf-1</span>.</p>
<pre class="code">my @a = 1..5;
say @a[0..2]; # OUTPUT: «(1 2 3)␤»
say @a[0..^2]; # OUTPUT: «(1 2)␤»
say @a[0..*]; # OUTPUT: «(1 2 3 4 5)␤»
say @a[0..^*]; # OUTPUT: «(1 2 3 4 5)␤»
say @a[0..Inf-1]; # OUTPUT: «(1 2 3 4 5)␤»</pre>
<a name="t25.8.6"></a> <h2 id="_language_list.pod6-Array_Constructor_Context">Array Constructor Context</h2>
<p>Inside an Array Literal, the list of initialization values is not in capture context and is just a normal list. It is, however, eagerly evaluated just as in assignment.</p>
<pre class="code">[ 1, 2, :c(3) ] eqv Array.new((1, 2, :c(3))); # OUTPUT: «True␤»
[while $++ &lt; 2 { 42.say; 43 }].map: *.say; # OUTPUT: «42␤42␤43␤43␤»
(while $++ &lt; 2 { 42.say; 43 }).map: *.say; # OUTPUT: «42␤43␤42␤43␤»</pre>
<p>Which brings us to Arrays...</p>
<a name="t25.9"></a> <h1 id="_language_list.pod6-Arrays">Arrays</h1>
<p>Arrays differ from lists in three major ways: Their elements may be typed, they automatically itemize their elements, and they are mutable. Otherwise they are Lists and are accepted wherever lists are.</p>
<pre class="code">say Array ~~ List # OUTPUT: «True␤»</pre>
<p>A fourth, more subtle, way they differ is that when working with Arrays, it can sometimes be harder to maintain laziness or work with infinite sequences.</p>
<a name="t25.9.1"></a> <h2 id="_language_list.pod6-Typing">Typing</h2>
<p><a id="i254" name="typed array"></a><span class="indexed"></span><a id="i255" name="[ ] (typed array)"></a><span class="indexed"></span> Arrays may be typed such that their slots perform a typecheck whenever they are assigned to. An Array that only allows <span class="code">Int</span> values to be assigned is of type <span class="code">Array[Int]</span> and one can create one with <span class="code">Array[Int].new</span>. If you intend to use an <span class="code">@</span>-sigiled variable only for this purpose, you may change its type by specifying the type of the elements when declaring it:</p>
<pre class="code">my Int @a = 1, 2, 3; # An Array that contains only Ints
my @b := Array[Int].new(1, 2, 3); # Same thing, but the variable is not typed
say @b eqv @a; # says True.
my @c = 1, 2, 3; # An Array that can contain anything
say @b eqv @c; # says False because types do not match
say @c eqv (1, 2, 3); # says False because one is a List
say @b eq @c; # says True, because eq only checks values
say @b eq (1, 2, 3); # says True, because eq only checks values
@a[0] = 42; # fine
@a[0] = &quot;foo&quot;; # error: Type check failed in assignment
</pre>
<p>In the above example we bound a typed Array object to a <span class="code">@</span>-sigil variable for which no type had been specified. The other way around does not work – you may not bind an Array that has the wrong type to a typed <span class="code">@</span>-sigiled variable:</p>
<pre class="code">my @a := Array[Int].new(1, 2, 3); # fine
@a := Array[Str].new(&quot;a&quot;, &quot;b&quot;); # fine, can be re-bound
my Int @b := Array[Int].new(1, 2, 3); # fine
@b := Array.new(1, 2, 3); # error: Type check failed in binding
</pre>
<p>When working with typed arrays, it is important to remember that they are nominally typed. This means the declared type of an array is what matters. Given the following sub declaration:</p>
<pre class="code">sub mean(Int @a) {
@a.sum / @a.elems
}</pre>
<p>Calls that pass an Array[Int] will be successful:</p>
<pre class="code">my Int @b = 1, 3, 5;
say mean(@b); # @b is Array[Int]
say mean(Array[Int].new(1, 3, 5)); # Anonymous Array[Int]
say mean(my Int @ = 1, 3, 5); # Another anonymous Array[Int]
</pre>
<p>However, the following calls will all fail, due to passing an untyped array, even if the array just happens to contain Int values at the point it is passed:</p>
<pre class="code">my @c = 1, 3, 5;
say mean(@c); # Fails, passing untyped Array
say mean([1, 3, 5]); # Same
say mean(Array.new(1, 3, 5)); # Same again
</pre>
<p>Note that in any given compiler, there may be fancy, under-the-hood, ways to bypass the type check on arrays, so when handling untrusted input, it can be good practice to perform additional type checks, where it matters:</p>
<pre class="code">for @a -&gt; Int $i { $_++.say };
</pre>
<p>However, as long as you stick to normal assignment operations inside a trusted area of code, this will not be a problem, and typecheck errors will happen promptly during assignment to the array, if they cannot be caught at compile time. None of the core functions provided in Perl 6 for operating on lists should ever produce a wonky typed Array.</p>
<p>Nonexistent elements (when indexed), or elements to which <span class="code">Nil</span> has been assigned, will assume a default value. This default may be adjusted on a variable-by-variable basis with the <span class="code">is default</span> trait. Note that an untyped <span class="code">@</span>-sigiled variable has an element type of <span class="code">Mu</span>, however its default value is an undefined <span class="code">Any</span>:</p>
<pre class="code">my @a;
@a.of.perl.say; # OUTPUT: «Mu␤»
@a.default.perl.say; # OUTPUT: «Any␤»
@a[0].say; # OUTPUT: «(Any)␤»
my Numeric @n is default(Real);
@n.of.perl.say; # OUTPUT: «Numeric␤»
@n.default.perl.say; # OUTPUT: «Real␤»
@n[0].say; # OUTPUT: «(Real)␤»</pre>
<a name="t25.9.2"></a> <h2 id="_language_list.pod6-Fixed_Size_Arrays">Fixed Size Arrays</h2>
<p>To limit the dimensions of an <span class="code">Array</span> provide the dimensions separated by <span class="code">,</span> or <span class="code">;</span> in brackets after the name of the array container. The values of such an <span class="code">Arrays</span> will default to <span class="code">Any</span>. The shape can be accessed at runtime via the <span class="code">shape</span> method.</p>
<pre class="code">my @a[2,2];
say @a.perl;
# OUTPUT: «Array.new(:shape(2, 2), [Any, Any], [Any, Any])␤»
say @a.shape;
# OUTPUT: «(2 2)␤»</pre>
<p>Assignment to a fixed size Array will promote a List of Lists to an Array of Arrays.</p>
<pre class="code">my @a[2;2] = (1,2; 3,4);
@a[1;1] = 42;
say @a.perl;
# OUTPUT: «Array.new(:shape(2, 2), [1, 2], [3, 42])␤»</pre>
<a name="t25.9.3"></a> <h2 id="_language_list.pod6-Itemization">Itemization</h2>
<p>For most uses, Arrays consist of a number of slots each containing a <span class="code">Scalar</span> of the correct type. Each such <span class="code">Scalar</span>, in turn, contains a value of that type. Perl 6 will automatically type-check values and create Scalars to contain them when Arrays are initialized, assigned to, or constructed.</p>
<p>This is actually one of the trickiest parts of Perl 6 list handling to get a firm understanding of.</p>
<p>First, be aware that because itemization in Arrays is assumed, it essentially means that <span class="code">$(…)</span>s are being put around everything that you assign to an array, if you do not put them there yourself. On the other side, Array.perl does not put <span class="code">$</span> to explicitly show scalars, unlike List.perl:</p>
<pre class="code">((1, 2), $(3, 4)).perl.say; # says &quot;((1, 2), $(3, 4))&quot;
[(1, 2), $(3, 4)].perl.say; # says &quot;[(1, 2), (3, 4)]&quot;
# ...but actually means: &quot;[$(1, 2), $(3, 4)]&quot;</pre>
<p>It was decided all those extra dollar signs and parentheses were more of an eye sore than a benefit to the user. Basically, when you see a square bracket, remember the invisible dollar signs.</p>
<p>Second, remember that these invisible dollar signs also protect against flattening, so you cannot really flatten the elements inside of an Array with a normal call to <span class="code">flat</span> or <span class="code">.flat</span>.</p>
<pre class="code">((1, 2), $(3, 4)).flat.perl.say; # OUTPUT: «(1, 2, $(3, 4)).Seq␤»
[(1, 2), $(3, 4)].flat.perl.say; # OUTPUT: «($(1, 2), $(3, 4)).Seq␤»</pre>
<p>Since the square brackets do not themselves protect against flattening, you can still spill the elements out of an Array into a surrounding list using <span class="code">flat</span>.</p>
<pre class="code">(0, [(1, 2), $(3, 4)], 5).flat.perl.say; # OUTPUT: «(0, $(1, 2), $(3, 4), 5).Seq␤»</pre>
<p>...the elements themselves, however, stay in one piece.</p>
<p>This can irk users of data you provide if you have deeply nested Arrays where they want flat data. Currently they have to deeply map the structure by hand to undo the nesting:</p>
<pre class="code">say gather [0, [(1, 2), [3, 4]], $(5, 6)].deepmap: *.take; # OUTPUT: «(1 2 3 4 5 6)␤»</pre>
<p>...future versions of Perl 6 might find a way to make this easier. However, not returning Arrays or itemized lists from functions, when non-itemized lists are sufficient, is something that one should consider as a courtesy to their users:</p>
<ul><li><p>use Slips when you want to always merge with surrounding lists</p>
</li></ul> <ul><li><p>use non-itemized lists when you want to make it easy for the user to flatten</p>
</li></ul> <ul><li><p>use itemized lists to protect things the user probably will not want flattened</p>
</li></ul> <ul><li><p>use Arrays as non-itemized lists of itemized lists, if appropriate,</p>
</li></ul> <ul><li><p>use Arrays if the user is going to want to mutate the result without copying it first.</p>
</li></ul> <p>The fact that all elements of an array are itemized (in <span class="code">Scalar</span> containers) is more a gentleman's agreement than a universally enforced rule, and it is less well enforced that typechecks in typed arrays. See the section below on binding to Array slots.</p>
<a name="t25.9.4"></a> <h2 id="_language_list.pod6-Literal_Arrays">Literal Arrays</h2>
<p>Literal Arrays are constructed with a List inside square brackets. The List is eagerly iterated (at compile time if possible) and values in the list are each type-checked and itemized. The square brackets themselves will spill elements into surrounding lists when flattened, but the elements themselves will not spill due to the itemization.</p>
<a name="t25.9.5"></a> <h2 id="_language_list.pod6-Mutability">Mutability</h2>
<p>Unlike lists, Arrays are mutable. Elements may deleted, added, or changed.</p>
<pre class="code">my @a = &quot;a&quot;, &quot;b&quot;, &quot;c&quot;;
@a.say; # OUTPUT: «[a b c]␤»
@a.pop.say; # OUTPUT: «c␤»
@a.say; # OUTPUT: «[a b]␤»
@a.push(&quot;d&quot;);
@a.say; # OUTPUT: «[a b d]␤»
@a[1, 3] = &quot;c&quot;, &quot;c&quot;;
@a.say; # OUTPUT: «[a c d c]␤»</pre>
<a name="t25.9.5.1"></a> <h3 id="_language_list.pod6-Assigning">Assigning</h3>
<p>Assignment of a list to an Array is eager. The list will be entirely evaluated, and should not be infinite or the program may hang. Assignment to a slice of an <span class="code">Array</span> is, likewise, eager, but only up to the requested number of elements, which may be finite:</p>
<pre class="code">my @a;
@a[0, 1, 2] = (loop { 42 });
@a.say; # OUTPUT: «[42 42 42]␤»</pre>
<p>During assignment, each value will be typechecked to ensure it is a permitted type for the <span class="code">Array</span>. Any <span class="code">Scalar</span> will be stripped from each value and a new <span class="code">Scalar</span> will be wrapped around it.</p>
<a name="t25.9.5.2"></a> <h3 id="_language_list.pod6-Binding">Binding</h3>
<p>Individual Array slots may be bound the same way <span class="code">$</span>-sigiled variables are:</p>
<pre class="code">my $b = &quot;foo&quot;;
my @a = 1, 2, 3;
@a[2] := $b;
@a.say; # OUTPUT: «[1 2 &quot;foo&quot;]␤»
$b = &quot;bar&quot;;
@a.say; # OUTPUT: «[1 2 &quot;bar&quot;]␤»</pre>
<p>...but binding Array slots directly to values is strongly discouraged. If you do, expect surprises with built-in functions. The only time this would be done is if a mutable container that knows the difference between values and Scalar-wrapped values is needed, or for very large Arrays where a native-typed array cannot be used. Such a creature should never be passed back to unsuspecting users.</p>
</div>
<!-- /language/modules-core.pod6 --><div class="pod-body"><a id="_language_modules-core.pod6"></a><a name="t26"></a><h1 class="title">26 Core Modules</h1> <p class="subtitle">Core modules that may be useful to module authors</p> <p>The Rakudo implementation has a few modules included you may want to use. The following is a list of them, along with links to their source code.</p>
<ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/CompUnit/Repository/Staging.pm"><span class="code">CompUnit::Repository::Staging</span></a> Used by distribution build tools</p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/NativeCall.pm6"><span class="code">NativeCall</span></a> Native Calling Interface (<a href="https://docs.perl6.org/language/nativecall.html">docs</a>)</p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/NativeCall/Types.pm6"><span class="code">NativeCall::Types</span></a> Used by <span class="code">NativeCall</span></p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/NativeCall/Compiler/GNU.pm6"><span class="code">NativeCall::Compiler::GNU</span></a> Used by <span class="code">NativeCall</span></p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/NativeCall/Compiler/MSVC.pm6"><span class="code">NativeCall::Compiler::MSVC</span></a> Used by <span class="code">NativeCall</span></p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/Pod/To/Text.pm6"><span class="code">Pod::To::Text</span></a> Used by several external modules</p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/Test.pm6"><span class="code">Test</span></a> Test routines (<a href="#_language_testing.pod6">docs</a>)</p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/experimental.pm6"><span class="code">experimental</span></a></p>
</li></ul> <ul><li><p><a href="https://github.com/rakudo/rakudo/blob/master/lib/newline.pm6"><span class="code">newline</span></a></p>
</li></ul></div>
<!-- /language/modules-extra.pod6 --><div class="pod-body"><a id="_language_modules-extra.pod6"></a><a name="t27"></a><h1 class="title">27 Module Development Utilities</h1> <p class="subtitle">What can help you write/test/improve your module(s)</p> <p>Here is a list of modules that you can find in the Perl 6 ecosystem which aim to make the experience of developing Perl 6 modules more fun.</p>
<a name="t27.1"></a> <h1 id="_language_modules-extra.pod6-Module_builder_and_Authoring_tools">Module builder and Authoring tools</h1>
<p>Some modules and tools to help you with generating files that are part of a module distribution.</p>
<ul><li><p><a href="https://modules.perl6.org/dist/App::Mi6">App::Mi6</a> Minimal authoring tool for Perl 6</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/META6">META6</a> Do things with Perl 6 META files</p>
</li></ul> <ul><li><p><a href="https://bitbucket.org/rightfold/module-skeleton">Module::Skeleton</a> Generate a skeleton module</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/p6doc">p6doc</a> Generate documentation end-products</p>
</li></ul> <a name="t27.2"></a> <h1 id="_language_modules-extra.pod6-Tests">Tests</h1>
<p>Some tests of module quality.</p>
<ul><li><p><a href="https://modules.perl6.org/dist/Test::META">Test::META</a> Test your META6.json file</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/Test::Output">Test::Output</a> Test the output to STDOUT and STDERR your program generates</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/Proc::Screen">Test::Screen</a> Use <b>GNU screen</b> to test full screen VT applications</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/Test::When">Test::When</a> Control when your tests are run (author testing, online testing, etc.)</p>
</li></ul> <a name="t27.3"></a> <h1 id="_language_modules-extra.pod6-NativeCall">NativeCall</h1>
<p>Here some modules to help you work with NativeCall.</p>
<ul><li><p><a href="https://modules.perl6.org/dist/NativeHelpers::Array">NativeHelpers::Array</a> Provides routines to deal with CArray</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/App::GPTrixie">App::GPTrixie</a> Generate NativeCall code from C headers file</p>
</li></ul> <ul><li><p><a href="https://modules.perl6.org/dist/NativeCall::TypeDiag">NativeCall::TypeDiag</a> Provides routines to test your CStruct</p>
</li></ul> <a name="t27.4"></a> <h1 id="_language_modules-extra.pod6-Sample_modules">Sample modules</h1>
<p>Modules that exist only as minimalist examples, tests for installers, or skeletons.</p>
<ul><li><p><a href="https://modules.perl6.org/dist/Foo">Foo</a> A module with two distributions of different versions</p>
</li></ul></div>
<!-- /language/modules.pod6 --><div class="pod-body"><a id="_language_modules.pod6"></a><a name="t28"></a><h1 class="title">28 Modules</h1> <p class="subtitle">How to create, use and distribute Perl 6 modules</p> <a name="t28.1"></a> <h1 id="_language_modules.pod6-Creating_and_Using_Modules">Creating and Using Modules</h1>
<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.pod6-Classes">classes</a>, <a href="#_language_objects.pod6-Roles">roles</a>, <a href="#_type_Grammar.pod6">grammars</a>), <a href="#_language_functions.pod6">subroutines</a>, and sometimes <a href="#_language_variables.pod6">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 &quot;module&quot; as a set of source files in a namespace.</p>
<a name="t28.1.1"></a> <h2 id="_language_modules.pod6-Basic_Structure">Basic Structure</h2>
<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, 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 <span class="code">.pm6</span> extension, and scripts or executables use the <span class="code">.p6</span>. Test files use the <span class="code">.t</span> extension.</p>
<a name="t28.1.2"></a> <h2 id="_language_modules.pod6-Loading_and_Basic_Importing">Loading and Basic Importing</h2>
<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="t28.1.2.1"></a> <h3 id="_language_modules.pod6-need"><a name="256"></a>need</h3>
<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="t28.1.2.2"></a> <h3 id="_language_modules.pod6-use"><a name="257"></a>use</h3>
<p><span class="code">use</span> loads and then imports from a compunit at compile time. It will look for files that end in <span class="code">.pm</span> or <span class="code">.pm6</span>. See <a href="#27-Finding_Modules">here</a> for where the runtime will look for modules.</p>
<pre class="code">use MyModule;
</pre>
<p>It is equivalent to:</p>
<pre class="code"><a href="#_language_modules.pod6-need">need</a> MyModule;
import MyModule;
</pre>
<p>See also <a href="#_language_modules.pod6-Exporting_and_Selective_Importing">Selective Importing</a> to restrict what you import.</p>
<a name="t28.1.2.3"></a> <h3 id="_language_modules.pod6-require"><a name="258"></a>require</h3>
<p><span class="code">require</span> loads a compunit and imports definite symbols at runtime.</p>
<pre class="code">say &quot;loading MyModule&quot;;
require MyModule;</pre>
<p>The compunit name can be in a runtime variable if you put it inside an indirect lookup.</p>
<pre class="code">my $name = 'MyModule';
require ::($name);</pre>
<p>The symbols provided by the loaded module will not be imported into the current scope. You may use <a href="#_language_packages.pod6-index-entry-::()">dynamic lookup</a> or <a href="#_language_typesystem.pod6-subset">dynamic subsets</a> to use them by providing the fully qualified name of a symbol.</p>
<p>To import symbols you must define them at compile time. <b>NOTE:</b> <span class="code">require</span> is lexically scoped:</p>
<pre class="code">sub do-something {
require MyModule &lt;&amp;something&gt;;
say ::('MyModule'); # MyModule symbol exists here
something() # &amp;something will be defined here
}
say ::('MyModule'); # This will NOT contain the MyModule symbol
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 <span class="code">require</span> will fail.</p>
<p>A <span class="code">require</span> with compile-time symbol will install a placeholder <span class="code">package</span> that will be updated to the loaded module, class, or package. Note that the placeholder will be kept, <b>even if require failed to load the module.</b> This means that checking if a module loaded like this is wrong:</p>
<pre class="code"># *** WRONG: ***
try require Foo;
if ::('Foo') ~~ Failure { say &quot;Failed to load Foo!&quot;; }
# *** WRONG: ***</pre>
<p>As the compile-time installed package causes <span class="code">::('Foo')</span> to never be a <span class="code">Failure</span>. The correct way is:</p>
<pre class="code"># Use return value to test whether loading succeeded:
(try require Foo) === Nil and say &quot;Failed to load Foo!&quot;;
# Or use a run-time symbol lookup with require, to avoid compile-time
# package installation:
try require ::('Foo');
if ::('Foo') ~~ Failure {
say &quot;Failed to load Foo!&quot;;
}</pre>
<a name="t28.1.3"></a> <h2 id="_language_modules.pod6-Exporting_and_Selective_Importing">Exporting and Selective Importing</h2>
<a name="t28.1.3.1"></a> <h3 id="_language_modules.pod6-is_export">is export</h3>
<p>Packages, subroutines, variables, constants and enums are exported by marking them with the <a href="#_routine_is export.pod6">is export</a> trait (also note the tags available for indicating authors and versions).</p>
<pre class="code">unit module MyModule:ver&lt;1.0.3&gt;:auth&lt;John Hancock (jhancock@example.com)&gt;;
our $var is export = 3;
sub foo is export { ... };
constant FOO is export = &quot;foobar&quot;;
enum FooBar is export &lt;one two three&gt;;
# 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, &quot;is export&quot; 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 so that 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) { ... } # objects with tag ':MANDATORY' are always exported
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>
<p>Note there currently is no way for the user to import a single object if the module author hasn't made provision for that, and it is not an easy task at the moment (see RT #127305). One way the author can provide such access is to give each <span class="code">export</span> trait its own unique tag. (And the tag can be the object name!) Then the user can either (1) import all objects:</p>
<pre class="code">use Foo :ALL;
</pre>
<p>or (2) import one or more objects selectively:</p>
<pre class="code">use Foo :bar, :s5;
</pre>
<p>Notes:</p>
<p>1. The <span class="code">:MANDATORY</span> tag on an exported sub ensures it will be exported no matter whether the using program adds any tag or not.</p>
<p>2. All exported subs without an explicit tag are implicitly <span class="code">:DEFAULT</span>.</p>
<p>3. The space after the module name and before the tag is mandatory.</p>
<p>4. Multiple import tags may be used (separated by commas). For example:</p>
<pre class="code"># main.pl
use lib 'lib';
use MyModule :day, :night; # pants, sunglasses, torch
</pre>
<p>5. Multiple tags may be used in the <span class="code">export</span> trait, but they must all be separated by either commas, or whitespace, but not both.</p>
<pre class="code">sub foo() is export(:foo :s2 :net) {}
sub bar() is export(:bar, :s3, :some) {}
</pre>
<a name="t28.1.3.2"></a> <h3 id="_language_modules.pod6-UNIT::EXPORT::*">UNIT::EXPORT::*</h3>
<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&gt;.kv -&gt; $number, $name {
for &lt;sqrt log&gt; -&gt; $func {
OUR::{'&amp;' ~ $func ~ '-of-' ~ $name } := sub { $number.&quot;$func&quot;() };
}
}
}
</pre>
<pre class="code"># main.pl
use MyModule;
say sqrt-of-four; # OUTPUT: «2␤»
say log-of-zero; # OUTPUT: «-Inf␤»
</pre>
<a name="t28.1.3.3"></a> <h3 id="_language_modules.pod6-EXPORT">EXPORT <a name="259"></a></h3>
<p>You can export arbitrary symbols with an <span class="code">EXPORT</span> sub. <span class="code">EXPORT</span> must return a <a href="#_type_Map.pod6">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' =&gt; 'one',
'@array' =&gt; &lt;one two three&gt;,
'%hash' =&gt; %( one =&gt; 'two', three =&gt; 'four' ),
'&amp;doit' =&gt; sub { say 'Greetings from exported sub' },
'ShortName' =&gt; MyModule::Class
)
}
</pre>
<pre class="code"># main.pl
use lib 'lib';
use MyModule;
say $var; # OUTPUT: «one␤»
say @array; # OUTPUT: «(one two three)␤»
say %hash; # OUTPUT: «{one =&gt; two, three =&gt; four}␤»
doit(); # OUTPUT: «Greetings from exported sub␤»
say ShortName.new; # OUTPUT: «MyModule::Class.new␤»
</pre>
<p>Note, <span class="code">EXPORT</span> can't be declared inside a package because it is 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 =&gt; MyModule::Class if $short_name
)
}
sub always is export(:MANDATORY) { say &quot;works&quot; }
#import with :ALL or :DEFAULT to get
sub shy is export { say &quot;you found me!&quot; }
</pre>
<pre class="code"># main.pl
use lib 'lib';
use MyModule 'foo';
say foo.new(); # OUTPUT: «MyModule::Class.new␤»
always(); # OK - is imported
shy(); # FAIL - won't be imported
</pre>
<p>You can combine `EXPORT` with type captures for interesting effect. This example creates a `?` postfix which will only work on <a href="#_type_Cool.pod6">Cool</a>s.</p>
<pre class="code"># lib/MakeQuestionable.pm
sub EXPORT(::Questionable) {
my multi postfix:&lt;?&gt;(Questionable $_) { .so };
%(
'&amp;postfix:&lt;?&gt;' =&gt; &amp;postfix:&lt;?&gt;,
)
}
</pre>
<pre class="code">use MakeQuestionable Cool;
say ( 0?, 1?, {}?, %( a =&gt; &quot;b&quot; )? ).join(' '); # OUTPUT: «False True False True␤»
</pre>
<a name="t28.1.4"></a> <h2 id="_language_modules.pod6-Introspection">Introspection</h2>
<p>To list exported symbols of a module first query the export tags supported by the module.</p>
<pre class="code">use URI::Escape;
say URI::Escape::EXPORT::.keys;
# OUTPUT: «(DEFAULT ALL)␤»</pre>
<p>Then use the tag you like and pick the symbol by its name.</p>
<pre class="code">say URI::Escape::EXPORT::DEFAULT::.keys;
# OUTPUT: «(&amp;uri-escape &amp;uri-unescape &amp;uri_escape &amp;uri_unescape)␤»
my &amp;escape-uri = URI::Escape::EXPORT::DEFAULT::&lt;&amp;uri_escape&gt;;</pre>
<a name="t28.1.5"></a> <h2 id="_language_modules.pod6-Finding_Modules">Finding Modules</h2>
<p>It is up to the module installer to know where <span class="code">compunit</span> expects modules to be placed. There will be a location provided by the distribution and in the current home directory. In any case, letting the module installer deal with your modules is a safe bet.</p>
<pre class="code">cd your-module-dir
zef --force install .
</pre>
<p><a id="i260" name="use lib"></a><span class="indexed"></span> A user may have a collection of modules not found in the normal ecosystem, maintained by a module or package manager, but needed regularly. Instead of using the <span class="code">use lib</span> pragma one can use the <span class="code">PERL6LIB</span> environment variable to point to module locations. For example:</p>
<pre class="code">export PERL6LIB=/path/to/my-modules,/path/to/more/modules
</pre>
<p>Note that the comma (',') is used as the directory separator.</p>
<p>The include path will be searched recursively for any modules when Rakudo is started. Directories that start with a dot are ignored and symlinks are followed.</p>
<a name="t28.2"></a> <h1 id="_language_modules.pod6-Distributing_Modules">Distributing Modules</h1>
<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>Currently there are two different module ecosystems (module distribution networks) available:</p>
<ul><li><p><b>CPAN</b> This is the same ecosystem Perl5 is using. Modules are uploaded as <i>.zip</i> or <i>.tar.gz</i> files on <a href="https://pause.perl.org/">PAUSE</a>.</p>
</li></ul> <ul><li><p><b>p6c</b> Up until recently the only ecosystem, but soon to be deprecated. It is based on Github repositories which are directly accessed. It has only limited capability for versioning.</p>
</li></ul> <p>The process of sharing your module consists of two steps, preparing the module and uploading the module to one of the ecosystems.</p>
<a name="t28.2.1"></a> <h2 id="_language_modules.pod6-Preparing_the_Module">Preparing the Module</h2>
<p>For a module to work in any of the ecosystems, it needs to follow a certain structure. Here is how to do that:</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>.</p>
</li></ul> <ul><li><p>Make your project directory look like this:</p>
<pre class="code">Vortex-TotalPerspective/
|-- lib
| `-- Vortex
| `-- TotalPerspective.pm
|-- LICENSE
|-- META6.json
|-- 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/master/LICENSE">its license</a> into your own <span class="code">LICENSE</span> file.</p>
</li></ul> <ul><li><p>The license field in META6.json The license field should be one of the standardized names listed here: https://spdx.org/licenses/, in the case of the <b>Artistic 2.0</b> license which is what many of our ecosystem modules use, its identifier is <span class="code">Artistic-2.0</span>. Having standardized identifiers make it easy for humans and computers alike to know which license was actually used by looking at the metadata!</p>
</li></ul> <ul><li><p>My license is not on spdx.org or using your own license If you can't find your license on <span class="code">spdx.org</span> or you use your own license, you should put the licenses name in the license field, and under more details here https://design.perl6.org/S22.html#license</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>.</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. 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. Follow the same folder structure as the <span class="code">lib</span> directory like so:</p>
<pre class="code">doc
`-- Vortex
`-- TotalPerspective.pod6
</pre>
</li></ul> <ul><li><p>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'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.</p>
</li></ul> <ul><li><p>Make your <a id="i261" name="META6.json"></a><span class="indexed"><span class="code">META6.json</span></span> file look something like this:</p>
<pre class="code">{
&quot;perl&quot; : &quot;6.c&quot;,
&quot;name&quot; : &quot;Vortex::TotalPerspective&quot;,
&quot;version&quot; : &quot;0.0.1&quot;,
&quot;description&quot; : &quot;Wonderful simulation to get some perspective.&quot;,
&quot;authors&quot; : [ &quot; <var class="replaceable">Your Name</var> &quot; ],
&quot;license&quot; : &quot;Artistic-2.0&quot;,
&quot;provides&quot; : {
&quot;Vortex::TotalPerspective&quot; : &quot;lib/Vortex/TotalPerspective.pm&quot;
},
&quot;depends&quot; : [ ],
&quot;resources&quot; : [ ],
&quot;source-url&quot; : &quot;git://github.com/ <var class="replaceable">you</var> /Vortex-TotalPerspective.git&quot;
}
</pre>
<p>For choosing a version numbering scheme, perhaps use &quot;major.minor.patch&quot; (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 that you wish to be installed, only module files that are explicitly included here will be installed and available with <span class="code">use</span> or <span class="code">require</span> in other programs.</p>
<p>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 META6.json file.</p>
<p>There are more fields described in the <a href="https://design.perl6.org/S22.html#META6.json">META design documents</a>, but not all of these are implemented by existing package managers. Hence you should stick to the fields described in the above example block to ensure compatibility with existing package managers.</p>
</li></ul> <ul><li><p>To test your module you can use the following command to install the module directly from the module folder you just created.</p>
<pre class="code">zef install ./your-module-folder
</pre>
</li></ul> <a name="t28.2.2"></a> <h2 id="_language_modules.pod6-Upload_your_Module_to_CPAN">Upload your Module to CPAN</h2>
<p>Uploading a module to CPAN is the preferred way of distributing Perl 6 modules.</p>
<p>it requires having a <a href="https://pause.perl.org/">PAUSE</a> user account. If you don't have an account already go there and apply for an account. The process takes about 5 minutes and some e-mail back and forth.</p>
<ul><li><p>Create a package of your module:</p>
<pre class="code">cd your-module-folder
tar czf Vortex-TotalPerspective-0.0.1.tar.gz --transform s/^\./Vortex-TotalPerspective-0.0.1/ --exclude-vcs --exclude=.[^/]*
</pre>
<p>If you use git you can also use the following command to create a package directly for a given commit.</p>
<pre class="code">git archive --prefix=Vortex-TotalPerspective-0.0.1/ -o ../Vortex-TotalPerspective-0.0.1.tar.gz HEAD
</pre>
</li></ul> <ul><li><p>Go to <a href="https://pause.perl.org/">PAUSE</a>, log in and click on <a href="https://pause.perl.org/pause/authenquery?ACTION=add_uri">Upload a file to CPAN</a>.</p>
</li></ul> <ul><li><p>Make sure you select <span class="code">Perl6</span> as the <i>Target Directory</i>. For your first upload, you have to enter the string <span class="code">Perl6</span> in the text field. On subsequent uploads, you can select the <span class="code">Perl6</span> directory from select box above the input field.</p>
</li></ul> <ul><li><p>Select your file and click <i>Upload</i>!</p>
<p><i>Make sure you have a META6.json file in your dist and that the dist version you're uploading is higher than the currently uploaded version. Those are the most common upload errors.</i></p>
</li></ul> <a name="t28.2.3"></a> <h2 id="_language_modules.pod6-Upload_your_Module_to_p6c">Upload your Module to p6c</h2>
<p><i>The p6c ecosystem is soon to be deprecated, so you should consider using the CPAN ecosystem instead.</i></p>
<p>If you want to use the <i>p6c</i> ecosystem you need to use git for your module's version control. The instructions herein assume that you have a <a href="https://github.com">GitHub</a> account so that your module can be shared from its GitHub repository, however another provider such as <a href="https://about.gitlab.com/">GitLab</a> should work as long as it works in a similar way.</p>
<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 repository for it on GitHub. See <a href="https://help.github.com/">GitHub's help docs</a> if necessary. Your GitHub repository should be named the same as your project directory. Immediately after creating the GitHub repo, GitHub shows you how to configure your local repository to know about your GitHub repository.</p>
</li></ul> <ul><li><p>Push your project to GitHub.</p>
</li></ul> <ul><li><p>Consider setting up automated testing (see <a href="https://docs.travis-ci.com/user/languages/perl6">https://docs.travis-ci.com/user/languages/perl6</a>).</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/">https://modules.perl6.org/</a>, please view the log file at <a href="https://modules.perl6.org/update.log">https://modules.perl6.org/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 <a id="i262" name=""></a><span class="indexed">zef</span> module installer tool which is included with Rakudo Star Perl 6:</p>
<pre class="code">zef install Vortex::TotalPerspective
</pre>
<p>This will download your module to its own working directory (<span class="code">~/.zef</span>), build it there, and install the module into your local Perl 6 installation directory.</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="t28.3"></a> <h1 id="_language_modules.pod6-Modules_and_Tools_Related_to_Module_Authoring">Modules and Tools Related to Module Authoring</h1>
<p>You can find a list of modules and tools that aim to improve the experience of writing/test modules at <a href="#_language_modules-extra.pod6">Modules Extra</a></p>
<a name="t28.3.1"></a> <h2 id="_language_modules.pod6-Contact_Information">Contact Information</h2>
<p>To discuss module development in general, or if your module would fill a need in the ecosystem, naming, etc., you can use the <a href="irc://irc.freenode.net/#perl6">#perl6 on irc.freenode.net</a> IRC channel.</p>
<p>To discuss toolchain specific questions, you can use the <a href="irc://irc.freenode.net/#perl6-toolchain">#perl6-toolchain on irc.freenode.net</a> IRC channel. A repository to discuss tooling issues is also available at <a href="https://github.com/perl6/toolchain-bikeshed">https://github.com/perl6/toolchain-bikeshed</a>.</p>
</div>
<!-- /language/mop.pod6 --><div class="pod-body"><a id="_language_mop.pod6"></a><a name="t29"></a><h1 class="title">29 Meta-Object Protocol</h1> <p class="subtitle">Introspection and the Perl 6 Object System</p> <p><a id="i263" name="MOP"></a><span class="indexed"></span> <a id="i264" name="Introspection"></a><span class="indexed"></span></p>
<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 <a href="#_type_Metamodel::ClassHOW.pod6">meta model</a>:</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 =&gt; '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="t29.1"></a> <h1 id="_language_mop.pod6-Metamethods">Metamethods</h1>
<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 creating your own methods with ALLCAPS names. This will avoid conflicts with any metamethods that may appear in future versions of the language.</p>
<a name="t29.1.1"></a> <h2 id="_language_mop.pod6-WHAT"><a name="265"></a>WHAT</h2>
<p>The type object of the type. This is a pseudo-method that can be overloaded without producing error or warning, but will be ignored.</p>
<p>For example <span class="code">42.WHAT</span> returns the <span class="code">Int</span> type object.</p>
<a name="t29.1.2"></a> <h2 id="_language_mop.pod6-WHICH"><a name="266"></a>WHICH</h2>
<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="t29.1.3"></a> <h2 id="_language_mop.pod6-WHO"><a name="267"></a>WHO</h2>
<p>The package supporting the object.</p>
<a name="t29.1.4"></a> <h2 id="_language_mop.pod6-WHERE"><a name="268"></a>WHERE</h2>
<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="t29.1.5"></a> <h2 id="_language_mop.pod6-HOW"><a name="269"></a>HOW</h2>
<p>The metaclass object: &quot;Higher Order Workings&quot;.</p>
<a name="t29.1.6"></a> <h2 id="_language_mop.pod6-WHY"><a name="270"></a>WHY</h2>
<p>The attached Pod value.</p>
<a name="t29.1.7"></a> <h2 id="_language_mop.pod6-DEFINITE"><a name="271"></a>DEFINITE</h2>
<p>The object has a valid concrete representation. This is a pseudo-method that can be overloaded without producing error or warning, but will be ignored.</p>
<p>Returns <span class="code">True</span> for instances and <span class="code">False</span> for type objects.</p>
<a name="t29.1.8"></a> <h2 id="_language_mop.pod6-VAR"><a name="272"></a>VAR</h2>
<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 &quot;itemized&quot;.</p>
<pre class="code">.say for (1, 2, 3); # OUTPUT: «1␤2␤3␤», not itemized
.say for $(1, 2, 3); # OUTPUT: «(1 2 3)␤», itemized
say (1, 2, 3).VAR ~~ Scalar; # OUTPUT: «False␤»
say $(1, 2, 3).VAR ~~ Scalar; # OUTPUT: «True␤»</pre>
<a name="t29.2"></a> <h1 id="_language_mop.pod6-Structure_of_the_meta_object_system">Structure of the meta object system</h1>
<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="https://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.pod6">role Metamodel::RoleContainer</a> implements the functionality that a type can hold roles and <a href="#_type_Metamodel::ClassHOW.pod6">Metamodel::ClassHOW</a>, which is the meta class behind the <span class="code">class</span> keyword, does this role.</p>
<p>Most meta classes have a <span class="code">compose</span> method that you must call when you're done creating or modifying a meta object. It creates method caches, validates things and so on, and weird behavior ensues if you forget to call it, so don't :-).</p>
<a name="t29.2.1"></a> <h2 id="_language_mop.pod6-Bootstrapping_concerns">Bootstrapping concerns</h2>
<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 an NQP-level routine instead of a normal <a href="#_type_Routine.pod6">Routine</a> object, or a bootstrap-attribute instead of <a href="#_type_Attribute.pod6">Attribute</a>.</p>
<a name="t29.2.2"></a> <h2 id="_language_mop.pod6-Composition_time_and_static_reasoning">Composition time and static reasoning</h2>
<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="t29.2.3"></a> <h2 id="_language_mop.pod6-Power_and_Responsibility">Power and Responsibility</h2>
<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="t29.2.4"></a> <h2 id="_language_mop.pod6-Power,_Convenience_and_Pitfalls">Power, Convenience and Pitfalls</h2>
<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.pod6">integer</a> 42, not on the <a href="#_type_Scalar.pod6">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 subtleties of Perl 6 in order to avoid pitfalls when working with the MOP, and can't expect the same &quot;do what I mean&quot; convenience that ordinary Perl 6 code offers.</p>
</div>
<!-- /language/nativecall.pod6 --><div class="pod-body"><a id="_language_nativecall.pod6"></a><a name="t30"></a><h1 class="title">30 Native Calling Interface</h1> <p class="subtitle">Call into dynamic libraries that follow the C calling convention</p> <a name="t30.1"></a> <h1 id="_language_nativecall.pod6-Getting_Started">Getting Started</h1>
<p><a id="i273" name="nativecall"></a><span class="indexed"></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 &quot;native&quot; trait in order to specify that the sub is actually defined in a native library. The platform-specific extension (e.g., '.so' or '.dll'), as well as any customary prefixes (e.g., 'lib') will be added for you.</p>
<p>The first time you call &quot;some_argless_function&quot;, the &quot;libsomething&quot; will be loaded and the &quot;some_argless_function&quot; 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 &quot;native&quot; trait.</p>
<a name="t30.2"></a> <h1 id="_language_nativecall.pod6-Changing_names">Changing names</h1>
<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 &quot;symbol&quot; 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">unit module Foo;
use NativeCall;
our sub init() is native('foo') is symbol('FOO_INIT') { * }
</pre>
<p>Inside of &quot;libfoo&quot; there is a routine called &quot;FOO_INIT&quot; 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 &quot;symbol&quot; trait to specify the name of the symbol in &quot;libfoo&quot; and call the subroutine whatever we want (&quot;init&quot; in this case).</p>
<a name="t30.3"></a> <h1 id="_language_nativecall.pod6-Passing_and_Returning_Values">Passing and Returning Values</h1>
<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">use NativeCall;
sub add(int32, int32) returns int32 is native(&quot;calculator&quot;) { * }</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>
<p><a id="i274" name="int8"></a><span class="indexed"></span><a id="i275" name="int16"></a><span class="indexed"></span><a id="i276" name="int32"></a><span class="indexed"></span><a id="i277" name="int64"></a><span class="indexed"></span><a id="i278" name="uint8"></a><span class="indexed"></span><a id="i279" name="uint16"></a><span class="indexed"></span><a id="i280" name="uint32"></a><span class="indexed"></span><a id="i281" name="uint64"></a><span class="indexed"></span><a id="i282" name="long"></a><span class="indexed"></span><a id="i283" name="longlong"></a><span class="indexed"></span><a id="i284" name="ulong"></a><span class="indexed"></span><a id="i285" name="ulonglong"></a><span class="indexed"></span><a id="i286" name="num32"></a><span class="indexed"></span><a id="i287" name="num64"></a><span class="indexed"></span><a id="i288" name="Str"></a><span class="indexed"></span><a id="i289" name="CArray"></a><span class="indexed"></span><a id="i290" name="Pointer"></a><span class="indexed"></span><a id="i291" name="bool"></a><span class="indexed"></span><a id="i292" name="size_t"></a><span class="indexed"></span><a id="i293" name="ssize_t"></a><span class="indexed"></span></p>
<table>
<tr><td>int8</td> <td>(int8_t in C, also used for char)</td></tr>
<tr><td>int16</td> <td>(int16_t in C, also used for short)</td></tr>
<tr><td>int32</td> <td>(int32_t in C, also used for int)</td></tr>
<tr><td>int64</td> <td>(int64_t in C)</td></tr>
<tr><td>uint8</td> <td>(uint8_t in C, also used for unsigned char)</td></tr>
<tr><td>uint16</td> <td>(uint16_t in C, also used for unsigned short)</td></tr>
<tr><td>uint32</td> <td>(uint32_t in C, also used for unsigned int)</td></tr>
<tr><td>uint64</td> <td>(uint64_t in C)</td></tr>
<tr><td>long</td> <td>(long in C)</td></tr>
<tr><td>longlong</td> <td>(long long in C, at least 64-bit)</td></tr>
<tr><td>ulong</td> <td>(unsigned long in C)</td></tr>
<tr><td>ulonglong</td> <td>(unsigned long long in C, at least 64-bit)</td></tr>
<tr><td>num32</td> <td>(float in C)</td></tr>
<tr><td>num64</td> <td>(double in C)</td></tr>
<tr><td>Str</td> <td>(C string)</td></tr>
<tr><td>CArray[int32]</td> <td>(int* in C, an array of ints)</td></tr>
<tr><td>Pointer[void]</td> <td>(void* in C, can point to all other types)</td></tr>
<tr><td>bool</td> <td>(bool from C99)</td></tr>
<tr><td>size_t</td> <td>(size_t in C)</td></tr>
<tr><td>ssize_t</td> <td>(ssize_t in C)</td></tr>
</table> <p>Don't use Perl 6 native types like <span class="code">int</span> or <span class="code">num</span>, as they don't have to correspond to the local C equivalent (e.g., Perl 6's <span class="code">int</span> can be 8 bytes but C's <span class="code">int</span> is only 4 bytes).</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 &quot;encoded&quot; trait to give some extra hints on how to do the marshaling.</p>
<pre class="code">use NativeCall;
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">use NativeCall;
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>If the C function requires the lifetime of a string to exceed the function call, the argument must be manually encoded and passed as <span class="code">CArray[uint8]</span>:</p>
<pre class="code">use NativeCall;
# C prototype is void set_foo(const char *)
sub set_foo(CArray[uint8]) is native('foo') { * }
# C prototype is void use_foo(void)
sub use_foo() is native('foo') { * } # will use pointer stored by set_foo()
my $string = &quot;FOO&quot;;
# The lifetime of this variable must be equal to the required lifetime of
# the data passed to the C function.
my $array = CArray[uint8].new($string.encode.list);
set_foo($array);
# ...
use_foo();
# It's fine if $array goes out of scope starting from here.</pre>
<a name="t30.4"></a> <h1 id="_language_nativecall.pod6-Basic_use_of_Pointers">Basic use of Pointers</h1>
<p>When the signature of your native function needs a pointer to some native type (<span class="code">int32</span>, <span class="code">uint32</span>, etc.) all you need to do is declare the argument <span class="code">is rw</span> :</p>
<pre class="code">use NativeCall;
# C prototype is void my_version(int *major, int *minor)
sub my_version(int32 is rw, int32 is rw) is native('foo') { * }
my_version(my int32 $major, my int32 $minor); # Pass a pointer to</pre>
<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">use NativeCall;
sub Foo_init() returns Pointer is native(&quot;foo&quot;) { * }
sub Foo_free(Pointer) is native(&quot;foo&quot;) { * }</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 &quot;CPointer&quot; can serve this role. This means you can expose libraries that work on handles by writing a class like this:</p>
<pre class="code">use NativeCall;
class FooHandle is repr('CPointer') {
# Here are the actual NativeCall functions.
sub Foo_init() returns FooHandle is native(&quot;foo&quot;) { * }
sub Foo_free(FooHandle) is native(&quot;foo&quot;) { * }
sub Foo_query(FooHandle, Str) returns int8 is native(&quot;foo&quot;) { * }
sub Foo_close(FooHandle) returns int8 is native(&quot;foo&quot;) { * }
# Here are the methods we use to expose it to the outside world.
method new {
Foo_init();
}
method query(Str $stmt) {
Foo_query(self, $stmt);
}
method close {
Foo_close(self);
}
# Free data when the object is garbage collected.
submethod DESTROY {
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="t30.5"></a> <h1 id="_language_nativecall.pod6-Function_Pointers">Function Pointers</h1>
<p>C libraries can expose pointers to C functions as return values of functions and as members of Structures like, e.g., structs and unions.</p>
<p>Example of invoking a function pointer &quot;$fptr&quot; returned by a function &quot;f&quot;, using a signature defining the desired function parameters and return value:</p>
<pre class="code">sub f() returns Pointer is native('mylib') { * }
my $fptr = f();
my &amp;newfunc = nativecast(:(Str, size_t --&gt; int32), $fptr);
say newfunc(&quot;test&quot;, 4);
</pre>
<a name="t30.6"></a> <h1 id="_language_nativecall.pod6-Arrays">Arrays</h1>
<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, int32, CArray[Str], CArray[num64]) is native(&quot;chart&quot;) { * }
my @titles := CArray[Str].new;
@titles[0] = 'Me';
@titles[1] = 'You';
@titles[2] = 'Hagrid';
my @values := CArray[num64].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">use NativeCall;
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">use NativeCall;
sub get_n_ints(CArray[int32], int32) returns int32 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[int32].new;
my $number_of_ints = 10;
$ints[$number_of_ints - 1] = 0; # extend the array to 10 items
my $n = get_n_ints($ints, $number_of_ints);
</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="t30.7"></a> <h1 id="_language_nativecall.pod6-Structs">Structs</h1>
<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 &quot;repr&quot; 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 marshal into struct fields. Currently, structs can contain machine-sized integers, doubles, strings, and other NativeCall objects (CArrays, and those using the CPointer and CStruct reprs). Other than that, you can do the usual set of things you would with a class; you could even have some of the attributes come from roles or have them inherited from another class. Of course, methods are completely fine too. Go wild!</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:</p>
<pre class="code">class MyStruct is repr('CStruct') {
has CArray[num64] $!arr;
has Str $!str;
has Point $!point; # Point is a user-defined class
submethod TWEAK {
my $arr := CArray[num64].new;
$arr[0] = 0.9e0;
$arr[1] = 0.2e0;
$!arr := $arr;
$!str := 'Perl 6 is fun';
$!point := Point.new;
}
}
</pre>
<p>As you may have predicted by now, a null is represented by the type object of the struct type.</p>
<a name="t30.7.1"></a> <h2 id="_language_nativecall.pod6-CUnions">CUnions</h2>
<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">use NativeCall;
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="t30.7.2"></a> <h2 id="_language_nativecall.pod6-Embedding_CStructs_and_CUnions">Embedding CStructs and CUnions</h2>
<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 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="t30.7.3"></a> <h2 id="_language_nativecall.pod6-Notes_on_Memory_management">Notes on Memory management</h2>
<p>When allocating a struct for use as a struct, make sure that you allocate your own memory in your C functions. If you're passing a struct into a C function which needs a <span class="code">Str</span>/<span class="code">char*</span> allocated ahead of time, be sure to assign a container for a variable of type <span class="code">Str</span> prior to passing your struct into the function.</p>
<a name="t30.7.3.1"></a> <h3 id="_language_nativecall.pod6-In_your_Perl6_code...">In your Perl6 code...</h3>
<pre class="code">class AStringAndAnInt is repr(&quot;CStruct&quot;) {
has Str $.a_string;
has int32 $.an_int32;
submethod TWEAK {
$!a_string := Str.new;
$!an_int32 = 0;
}
sub init_struct(AStringAndAnInt is rw, Str, int32) is native('simple-struct') { * }
method init(:$a_string, :$an_int) {
init_struct(self, $a_string, $an_int);
}
}
</pre>
<p>In this code we first set up our members, <span class="code">$.a_string</span> and <span class="code">$.an_int32</span>. We then set the container of <span class="code">$.a_string</span> to a new <span class="code">Str</span>. After that we declare our <span class="code">init_struct()</span> function for the <span class="code">init()</span> method to wrap around.</p>
<a name="t30.7.3.2"></a> <h3 id="_language_nativecall.pod6-In_your_C_code...">In your C code...</h3>
<pre class="code">typedef struct a_string_and_an_int32_t_ {
char *a_string;
int32_t an_int32;
} a_string_and_an_int32_t;
</pre>
<p>Here's the structure. Notice how we've got a <span class="code">char *</span> there.</p>
<pre class="code">void init_struct(a_string_and_an_int32_t *target, char *str, int32_t int32) {
target-&gt;an_int32 = int32;
strcpy(target-&gt;a_string, str);
return;
}
</pre>
<p>In this function we initialize the C structure by assigning an integer by value, and copying the string by reference. This function assumes that there is memory allocated to <span class="code">char *a_string</span> within the structure into which it can copy the string.</p>
<p># A long time ago in a galaxy far, far away...</p>
<pre class="code">my $foo = AStringAndAnInt.new;
$foo.init(&quot;str&quot;, 123);
</pre>
<a name="t30.8"></a> <h1 id="_language_nativecall.pod6-Typed_Pointers">Typed Pointers</h1>
TODO
<p>TBD more</p>
<p>You can type your <span class="code">Pointer</span> by passing the type as a parameter. It works with the native type but also with <span class="code">CArray</span> and <span class="code">CStruct</span> defined types. NativeCall will not implicitly allocate the memory for it even when calling new on them. It's mostly useful in the case of a C routine returning a pointer, or if it's a pointer embedded in a <span class="code">CStruct</span>.</p>
<p>You have to call <span class="code">.deref</span> on it to access the embedded 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>
<p>It's quite common for a native function to return a pointer to an array of elements. Typed pointers can be dereferenced as an array to obtain individual elements.</p>
<pre class="code">my $n = 5;
# returns a pointer to an array of length $n
my Pointer[Point] $plot = some_other_c_routine($n);
# display the 5 elements in the array
for 1 .. $n -&gt; $i {
my $x = $plot[$i - 1].x;
my $y = $plot[$i - 1].y;
say &quot;$i: ($x, $y)&quot;;
}
</pre>
<p>Pointers can also be updated to reference successive elements in the array:</p>
<pre class="code">my Pointer[Point] $elem = $plot;
# show differences between successive points
for 1 ..^ $n {
my Point $lo = $elem.deref;
++$elem; # equivalent to $elem = $elem.add(1);
my Point $hi = (++$elem).deref;
my $dx = $hi.x = $lo.x;
my $dy = $hi.y = $lo.y;
say &quot;$_: delta ($dx, $dy)&quot;;
}
</pre>
<a name="t30.9"></a> <h1 id="_language_nativecall.pod6-Buffers_and_Blobs">Buffers and Blobs</h1>
TODO
<p>TBD</p>
<a name="t30.10"></a> <h1 id="_language_nativecall.pod6-Function_arguments">Function arguments</h1>
<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">use NativeCall;
# void SetCallback(int (*callback)(const char *))
my sub SetCallback(&amp;callback (Str --&gt; 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="t30.11"></a> <h1 id="_language_nativecall.pod6-Library_Paths_and_Names">Library Paths and Names</h1>
TODO
<p>TBD more</p>
<p>The <span class="code">native</span> trait accepts the library name or the full path.</p>
<pre class="code">use NativeCall;
constant LIBMYSQL = 'mysqlclient';
constant LIBFOO = '/usr/lib/libfoo.so.1';
# and later
sub mysql_affected_rows returns int32 is native(LIBMYSQL) {*};
sub bar is native(LIBFOO) {*}</pre>
<p>You can also put an incomplete path like './foo' and NativeCall will automatically put the right extension according to the platform specification.</p>
<p>BE CAREFUL: the <span class="code">native</span> trait and <span class="code">constant</span> are evaluated at compile time. Don't write a constant that depends on a dynamic variable like:</p>
<pre class="code"># WRONG:
constant LIBMYSQL = %*ENV&lt;P6LIB_MYSQLCLIENT&gt; || 'mysqlclient';</pre>
<p>This will keep the value given at compile time. A module will be precompiled and <span class="code">LIBMYSQL</span> will keep the value it acquires when the module gets precompiled.</p>
<a name="t30.11.1"></a> <h2 id="_language_nativecall.pod6-ABI/API_Version">ABI/API Version</h2>
<p>If you write <span class="code">native('foo')</span> NativeCall will search libfoo.so under Unix like system (libfoo.dynlib on OS X, foo.dll on win32). In most modern system it will require you or the user of your module to install the development package because it's recommended to always provide an API/ABI version to a shared library, so libfoo.so ends often being a symbolic link provided only by a development package.</p>
<p>To avoid that, the <span class="code">native</span> trait allows you to specify the API/ABI version. It can be a full version or just a part of it. (Try to stick to Major version, some BSD code does not care for Minor.)</p>
<pre class="code">use NativeCall;
sub foo1 is native('foo', v1) {*} # Will try to load libfoo.so.1
sub foo2 is native('foo', v1.2.3) {*} # Will try to load libfoo.so.1.2.3
my List $lib = ('foo', 'v1');
sub foo3 is native($lib) {*}</pre>
<a name="t30.11.2"></a> <h2 id="_language_nativecall.pod6-Routine">Routine</h2>
<p>The <span class="code">native</span> trait also accepts 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">use NativeCall;
sub foo is native(sub {'libfoo.so.42'}) {*}</pre>
<p>It will only be called at the first invocation of the sub.</p>
<a name="t30.11.3"></a> <h2 id="_language_nativecall.pod6-Calling_into_the_standard_library">Calling into the standard library</h2>
<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(uint32 $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="t30.12"></a> <h1 id="_language_nativecall.pod6-Exported_variables">Exported variables</h1>
<p>Variables exported by a library – also named &quot;global&quot; or &quot;extern&quot; variables – can be accessed using <span class="code">cglobal</span>. For example:</p>
<pre class="code">my $var := cglobal('libc.so.6', 'errno', int32)
</pre>
<p>This code binds to <span class="code">$var</span> a new <a href="#_type_Proxy.pod6">Proxy</a> object that redirects all its accesses to the integer variable named &quot;errno&quot; as exported by the &quot;libc.so.6&quot; library.</p>
<a name="t30.13"></a> <h1 id="_language_nativecall.pod6-C++_Support">C++ Support</h1>
<p>NativeCall offers support to use classes and methods from C++ as shown in <a href="https://github.com/rakudo/rakudo/blob/master/t/04-nativecall/13-cpp-mangling.t">https://github.com/rakudo/rakudo/blob/master/t/04-nativecall/13-cpp-mangling.t</a> (and its associated C++ file). Note that at the moment it's not as tested and developed as C support.</p>
<a name="t30.14"></a> <h1 id="_language_nativecall.pod6-Helper_Functions">Helper Functions</h1>
<p>The <span class="code">NativeCall</span> library exports several subroutines to help you work with data from native libraries.</p>
<a name="t30.14.1"></a> <h2 id="_language_nativecall.pod6-sub_nativecast">sub nativecast</h2>
<pre class="code">sub nativecast($target-type, $source) is export(:DEFAULT)</pre>
<p>This will <i>cast</i> the Pointer <span class="code">$source</span> to an object of <span class="code">$target-type</span>. The source pointer will typically have been obtained from a call to a native subroutine that returns a pointer or as a member of a <span class="code">struct</span>, this may be specified as <span class="code">void *</span> in the <span class="code">C</span> library definition for instance, but you may also cast from a pointer to a less specific type to a more specific one.</p>
<p>As a special case, if a <a href="#_type_Signature.pod6">Signature</a> is supplied as <span class="code">$target-type</span> then a <span class="code">subroutine</span> will be returned which will call the native function pointed to by <span class="code">$source</span> in the same way as a subroutine declared with the <span class="code">native</span> trait. This is described in <a href="#29-Function_Pointers">Function Pointers</a>.</p>
<a name="t30.14.2"></a> <h2 id="_language_nativecall.pod6-sub_cglobal">sub cglobal</h2>
<pre class="code">sub cglobal($libname, $symbol, $target-type) is export is rw</pre>
<p>This returns a <a href="#_type_Proxy.pod6">Proxy</a> object that provides access to the <span class="code">extern</span> named <span class="code">$symbol</span> that is exposed by the specified library. The library can be specified in the same ways that they can be to the <span class="code">native</span> trait.</p>
<a name="t30.14.3"></a> <h2 id="_language_nativecall.pod6-sub_nativesizeof">sub nativesizeof</h2>
<pre class="code">sub nativesizeof($obj) is export(:DEFAULT)</pre>
<p>This returns the size in bytes of the supplied object, it can be thought of as being equivalent to <span class="code">sizeof</span> in <b>C</b>. The object can be a builtin native type such as <span class="code">int64</span> or <span class="code">num64</span>, a <span class="code">CArray</span> or a class with the <span class="code">repr</span> <span class="code">CStruct</span>, <span class="code">CUnion</span> or <span class="code">CPointer</span>.</p>
<a name="t30.15"></a> <h1 id="_language_nativecall.pod6-Examples">Examples</h1>
<p>Some examples can be found <a href="https://github.com/perl6/DBIish/tree/master/examples">in the DBIsh repository</a>.</p>
<a name="t30.15.1"></a> <h2 id="_language_nativecall.pod6-MySQL">MySQL</h2>
<p>You'll need to install MySQL server locally; on Debian-esque systems it can be installed with something like:</p>
<pre class="code">sudo apt-get install mysql-server
</pre>
<p>Prepare your system along these lines before trying out the examples:</p>
<pre class="code">$ mysql -u root -p
UPDATE mysql.user SET password=password('sa') WHERE user = 'root';
CREATE DATABASE test;
</pre>
<a name="t30.15.2"></a> <h2 id="_language_nativecall.pod6-Microsoft_Windows">Microsoft Windows</h2>
<p>Here is an example of a Windows API call:</p>
<pre class="code">use NativeCall;
sub MessageBoxA(int32, Str, Str, int32)
returns int32
is native('user32')
{ * }
MessageBoxA(0, &quot;We have NativeCall&quot;, &quot;ohai&quot;, 64);
</pre>
</div>
<!-- /language/objects.pod6 --><div class="pod-body"><a id="_language_objects.pod6"></a><a name="t31"></a><h1 class="title">31 Object Orientation</h1> <p class="subtitle">Object Orientation in Perl 6</p> <p>Perl 6 provides strong support for object oriented programming. Although Perl 6 allows programmers to program in multiple paradigms, object oriented programming is at the heart of the language.</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="t31.1"></a> <h1 id="_language_objects.pod6-Using_Objects">Using Objects</h1>
<p>To call a method on an object, add a dot, followed by the method name:</p>
<pre class="code">say &quot;abc&quot;.uc;
# OUTPUT: «ABC␤»
</pre>
<p>This calls the <span class="code">uc</span> method on <span class="code">&quot;abc&quot;</span>, which is an object of type <span class="code">Str</span>. To supply arguments to the method, add arguments inside parentheses after the method.</p>
<pre class="code">my $formatted-text = &quot;Fourscore and seven years ago...&quot;.indent(8);
say $formatted-text;
# OUTPUT: « Fourscore and seven years ago...␤»
</pre>
<p><span class="code">$formatted-text</span> now contains the above text, but indented 8 spaces.</p>
<p>Multiple arguments are separated by commas:</p>
<pre class="code">my @words = &quot;Abe&quot;, &quot;Lincoln&quot;;
@words.push(&quot;said&quot;, $formatted-text.comb(/\w+/));
say @words;
# OUTPUT: «[Abe Lincoln said (Fourscore and seven years ago)]␤»
</pre>
<p>Multiple arguments can be specified by separating the argument list with a colon:</p>
<pre class="code">say @words.join: '--';
# OUTPUT: «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 parentheses is unambiguously a method call without an argument list:</p>
<pre class="code">say 4.log: ; # OUTPUT: «1.38629436111989␤» ( natural logarithm of 4 )
say 4.log: +2; # OUTPUT: «2␤» ( base-2 logarithm of 4 )
say 4.log +2; # OUTPUT: «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.nl-in = &quot;\r\n&quot;;
</pre>
<p>Here, we call 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="#_type_Mu.pod6">Mu</a>, which is the type hierarchy root. All objects derive from <span class="code">Mu</span>.</p>
<a name="t31.1.1"></a> <h2 id="_language_objects.pod6-Type_Objects">Type Objects</h2>
<p>Types themselves are objects and you can get the <i>type object</i> 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="#_type_Mu.pod6">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 === Int {
say 'you passed an Int';
}
else {
say 'you passed a subtype of Int';
}
}
</pre>
<p>Although, in most cases, the <a href="#_routine_isa.pod6"><span class="code">.isa</span></a> method will suffice:</p>
<pre class="code">sub f($x) {
if $x.isa(Int) {
...
}
...
}
</pre>
<p>Subtype checking is done by <a href="#_language_operators.pod6-infix_~~">smart-matching</a>:</p>
<pre class="code">if $type ~~ Real {
say '$type contains Real or a subtype thereof';
}
</pre>
<a name="t31.2"></a> <h1 id="_language_objects.pod6-Classes"><a name="294"></a>Classes</h1>
<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="t31.2.1"></a> <h2 id="_language_objects.pod6-Attributes">Attributes <a name="295"></a> <a name="296"></a> <a name="297"></a> <a name="298"></a></h2>
<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 @!travelers;
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 @!travelers;
has $.notes;
}</pre>
<p>This defaults to providing a read-only accessor. In order to allow changes to the attribute, add the <a href="#_routine_is rw.pod6">is rw</a> trait:</p>
<pre class="code">class Journey {
has $.origin;
has $.destination;
has @!travelers;
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>If an object is instantiated without certain attributes, such as origin or destination, we may not get the desired result. To prevent this, provide default values or make sure that an attribute is set on object creation by marking an attribute with an <a href="#_routine_is required.pod6">is required</a> trait.</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 @!travelers;
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 =&gt; 'Sweden',
destination =&gt; 'Switzerland',
notes =&gt; '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, although the default constructor can initialize read-only attributes, it will only set attributes that have an accessor method. That is, even if you pass <span class="code">travelers =&gt; [&quot;Alex&quot;, &quot;Betty&quot;]</span> to the default constructor, the attribute <span class="code">@!travelers</span> is not initialized.</p>
<a name="t31.2.2"></a> <h2 id="_language_objects.pod6-Methods">Methods</h2>
<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 @!travelers;
has $.notes is rw;
method add-traveler($name) {
if $name ne any(@!travelers) {
push @!travelers, $name;
}
else {
warn &quot;$name is already going on the journey!&quot;;
}
}
method describe() {
&quot;From $!origin to $!destination&quot;
}
}
</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 the <span class="code">.</span> twigil declares a <span class="code">!</span> twigil and 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>. <span class="code">$!origin</span> is an inexpensive and obvious lookup of the attribute. <span class="code">$.origin</span> is a method call and thus may be overridden in a subclass. Only use <span class="code">$.origin</span> if you want to allow overriding.</p>
<p>Unlike Subroutines, additional named arguments will not produce compile time or runtime errors. That allows chaining of methods via <a href="#_language_functions.pod6-Re-dispatching">Re-dispatching</a></p>
<p>Method names can be resolved at runtime with the <span class="code">.&quot;&quot;</span> operator.</p>
<pre class="code">class A { has $.b };
my $name = 'b';
A.new.&quot;$name&quot;().say;
# OUTPUT: «(Any)␤»</pre>
<a name="t31.2.3"></a> <h2 id="_language_objects.pod6-Class_and_Instance_Methods">Class and Instance Methods</h2>
<p>A method's signature can have an <i>invocant</i> as its first parameter followed by a colon, which allows for the method to refer to the object it was called on.</p>
<pre class="code">class Foo {
method greet($me: $person) {
say &quot;Hi, I am $me.^name(), nice to meet you, $person&quot;;
}
}
Foo.new.greet(&quot;Bob&quot;); # OUTPUT: «Hi, I am Foo, nice to meet you, Bob␤»</pre>
<p>Providing an invocant in the method signature also allows for defining the method as either as a class method, or as an object method, through the use of <a href="#_type_Signature.pod6-Type_Constraints">type constraints</a>. The <span class="code">::?CLASS</span> variable can be used to provide the class name at compile time, combined with either <span class="code">:U</span> (for class methods) or <span class="code">:D</span> (for instance methods).</p>
<pre class="code">class Pizza {
has $!radius = 42;
has @.ingredients;
# class method: construct from a list of ingredients
method from-ingredients(::?CLASS:U $pizza: @ingredients) {
$pizza.new( ingredients =&gt; @ingredients );
}
# instance method
method get-radius(::?CLASS:D:) { $!radius }
}
my $p = Pizza.from-ingredients: &lt;cheese pepperoni vegetables&gt;;
say $p.ingredients; # OUTPUT: «[cheese pepperoni vegetables]␤»
say $p.get-radius; # OUTPUT: «42␤»
say Pizza.get-radius; # This will fail.
CATCH { default { put .^name ~ &quot;:\n&quot; ~ .Str } };
# OUTPUT: «X::Parameter::InvalidConcreteness:␤
# Invocant of method 'get-radius' must be
# an object instance of type 'Pizza',
# not a type object of type 'Pizza'.
# Did you forget a '.new'?»</pre>
<p>A method can be both a class and object method by using the <a href="#_syntax_multi.pod6">multi</a> declarator:</p>
<pre class="code">class C {
multi method f(::?CLASS:U:) { say &quot;class method&quot; }
multi method f(::?CLASS:D:) { say &quot;object method&quot; }
}
C.f; # OUTPUT: «class method␤»
C.new.f; # OUTPUT: «object method␤»</pre>
<a name="t31.2.4"></a> <h2 id="_language_objects.pod6-self">self</h2>
<p>Inside a method, the term <span class="code">self</span> is available, which is bound to the invocant. <span class="code">self</span> can be used to call further methods on the invocant, including constructors:</p>
<pre class="code">class Box {
has $.data;
method make-new-box-from() {
self.new: data =&gt; $!data;
}
}</pre>
<p><span class="code">self</span> can be used in class or instance methods as well, though beware of trying to invoke one type of method from the other:</p>
<pre class="code">class C {
method g() { 42 }
method f(::?CLASS:U:) { self.g }
method d(::?CLASS:D:) { self.f }
}
C.f; # OUTPUT: «42␤»
C.new.d; # This will fail.
CATCH { default { put .^name ~ &quot;:\n&quot; ~ .Str } };
# OUTPUT: «X::Parameter::InvalidConcreteness:␤
# Invocant of method 'f' must be a type object of type 'C',
# not an object instance of type 'C'. Did you forget a 'multi'?»</pre>
<p>Within methods, <span class="code">$.origin</span> works the same as <span class="code">self.origin</span>, however the colon-syntax for method arguments is only supported for method calls using <span class="code">self</span>, not the shortcut.</p>
<p>Note that if the relevant methods <span class="code">bless</span>, <span class="code">CREATE</span> of <a href="#_type_Mu.pod6">Mu</a> are not overloaded, <span class="code">self</span> will point to the type object in those methods.</p>
<p>On the other hand, <span class="code">BUILDALL</span> and the submethods <span class="code">BUILD</span> and <span class="code">TWEAK</span> are called on instances, in different stages of initialization. In the latter two submethods, submethods of the same name from subclasses have not yet run, so you should not rely on potentially virtual method calls inside these methods.</p>
<a name="t31.2.5"></a> <h2 id="_language_objects.pod6-Private_Methods">Private Methods</h2>
<p>Methods with an exclamation mark <span class="code">!</span> before the method name are not callable from anywhere outside the defining class; such methods are private in the sense that they are not visible from outside the class that declares them. Private methods are invoked 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 by subclasses.</p>
<a name="t31.2.6"></a> <h2 id="_language_objects.pod6-Submethods">Submethods</h2>
<p>Submethods are public methods that are not inherited by 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.pod6-method_new">default method new</a> calls submethod <span class="code">BUILD</span> on each class in an <a href="#30-Inheritance">inheritance</a> chain:</p>
<pre class="code">class Point2D {
has $.x;
has $.y;
submethod BUILD(:$!x, :$!y) {
say &quot;Initializing Point2D&quot;;
}
}
class InvertiblePoint2D is Point2D {
submethod BUILD() {
say &quot;Initializing InvertiblePoint2D&quot;;
}
method invert {
self.new(x =&gt; - $.x, y =&gt; - $.y);
}
}
say InvertiblePoint2D.new(x =&gt; 1, y =&gt; 2);
# OUTPUT: «Initializing Point2D␤»
# OUTPUT: «Initializing InvertiblePoint2D␤»
# OUTPUT: «InvertiblePoint2D.new(x =&gt; 1, y =&gt; 2)␤»
</pre>
<p>See also: <a href="#30-Object Construction">#Object Construction</a>.</p>
<a name="t31.2.7"></a> <h2 id="_language_objects.pod6-Inheritance">Inheritance</h2>
<p>Classes can have <i>parent classes</i>.</p>
<pre class="code">class Child is Parent1 is Parent2 { }
</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.^mro; # ((List) (Cool) (Any) (Mu))</pre>
<p>If a class does not specify a parent class, <a href="#_type_Any.pod6">Any</a> is assumed by default. All classes directly or indirectly derive from <a href="#_type_Mu.pod6">Mu</a>, the root of the type hierarchy.</p>
<p>All calls to public methods are &quot;virtual&quot; 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 &quot;the parent class frobs&quot;
}
}
class Child is Parent {
method frob {
say &quot;the child's somewhat more fancy frob is called&quot;
}
}
my Parent $test;
$test = Child.new;
$test.frob; # calls the frob method of Child rather than Parent
# OUTPUT: «the child's somewhat more fancy frob is called␤»
</pre>
<a name="t31.2.8"></a> <h2 id="_language_objects.pod6-Object_Construction"><a name="299"></a>Object Construction</h2>
<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="#_type_Mu.pod6">Mu</a> provides a constructor method called <a href="#_routine_new.pod6">new</a>, which takes named arguments and uses them to initialize public attributes.</p>
<pre class="code">class Point {
has $.x;
has $.y;
}
my $p = Point.new( x =&gt; 5, y =&gt; 2);
# ^^^ inherited from class Mu
say &quot;x: &quot;, $p.x;
say &quot;y: &quot;, $p.y;
# OUTPUT: «x: 5␤»
# OUTPUT: «y: 2␤»</pre>
<p><span class="code">Mu.new</span> calls method <a href="#_routine_bless.pod6">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="#_type_Mu.pod6">Mu</a> to most derived classes) and in each class checks for the existence of a method named <span class="code">BUILD</span>. If the method exists, the method is called with all the named arguments from the <span class="code">new</span> method. 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.</p>
<p><a id="i300" name="TWEAK"></a><span class="indexed"></span> After the <span class="code">BUILD</span> methods have been called, methods named <span class="code">TWEAK</span> are called, if they exist, again with all the named arguments that were passed to <span class="code">new</span>.</p>
<p>Due to the default behavior of <span class="code">BUILDALL</span> and <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 of 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 BUILD(:encoding(:$enc), :$data) {
$!enc := $enc;
$!data := $data;
}
}
my $b1 = EncodedBuffer.new( encoding =&gt; 'UTF-8', data =&gt; [64, 65] );
my $b2 = EncodedBuffer.new( enc =&gt; 'UTF-8', data =&gt; [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(:$!enc), :$!data) {
# nothing to do here anymore, the signature binding
# does all the work for us.
}
</pre>
<p>However, be careful when using this auto-binding of attributes when the attribute may have special type requirements, such as an <span class="code">:$!id</span> that must be a positive integer. Remember, default values will be assigned unless you specifically take care of this attribute, and that default value will be <span class="code">Any</span>, which would cause a type error.</p>
<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.bless(:$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 construction 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.
self # return the fully built object
}
}
</pre>
<p>The <span class="code">TWEAK</span> method allows you to check things or modify attributes after object construction:</p>
<pre class="code">class RectangleWithCachedArea {
has ($.x1, $.x2, $.y1, $.y2);
has $.area;
submethod TWEAK() {
$!area = abs( ($!x2 - $!x1) * ( $!y2 - $!y1) );
}
}
say RectangleWithCachedArea.new( x2 =&gt; 5, x1 =&gt; 1, y2 =&gt; 1, y1 =&gt; 0).area;
# OUTPUT: «4␤»
</pre>
<a name="t31.2.9"></a> <h2 id="_language_objects.pod6-Object_Cloning">Object Cloning</h2>
<p>The cloning is done using <a href="#_routine_clone.pod6">clone</a> method available on all objects, which shallow-clones both public and private attributes. New values for <i>public</i> attributes can be supplied as named arguments.</p>
<pre class="code">class Foo {
has $.foo = 42;
has $.bar = 100;
}
my $o1 = Foo.new;
my $o2 = $o1.clone: :bar(5000);
say $o1; # Foo.new(foo =&gt; 42, bar =&gt; 100)
say $o2; # Foo.new(foo =&gt; 42, bar =&gt; 5000)
</pre>
<p>See document for <a href="#_routine_clone.pod6">clone</a> for details on how non-scalar attributes get cloned, as well as examples of implementing your own custom clone methods.</p>
<a name="t31.3"></a> <h1 id="_language_objects.pod6-Roles"><a name="301"></a>Roles</h1>
<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 objects and roles are meant for managing behavior and code reuse.</p>
<pre class="code">use MONKEY-SEE-NO-EVAL;
role Serializable {
method serialize() {
self.perl; # very primitive serialization
}
method deserialize($buf) {
EVAL $buf; # reverse operation to .perl
}
}
class Point does Serializable {
has $.x;
has $.y;
}
my $p = Point.new(:x(1), :y(2));
my $serialized = $p.serialize;
my $clone-of-p = Point.deserialize($serialized);
say $clone-of-p.x; # OUTPUT: «1␤»
</pre>
<p>Roles are immutable as soon as the compiler parses the closing curly brace of the role declaration.</p>
<a name="t31.3.1"></a> <h2 id="_language_objects.pod6-Application_of_Role">Application of Role</h2>
<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 resolved to the superclass that appears earlier in the method resolution order, which 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;
say $t.steer;
# OUTPUT: «Taurus.new(castrated =&gt; Bool::True, direction =&gt; Any)␤»</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 a lot of headaches:</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="t31.3.2"></a> <h2 id="_language_objects.pod6-Stubs">Stubs</h2>
<p>When a role contains a <a href="#_routine_....pod6">stubbed</a> 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() { ... } # 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's required by a role
class APoint does AbstractSerializable {
has $.x;
has $.y;
}
# this works:
class SPoint does AbstractSerializable {
has $.x;
has $.y;
method serialize() { &quot;p($.x, $.y)&quot; }
}
</pre>
<p>The implementation of the stubbed method may also be provided by another role.</p>
<a name="t31.3.3"></a> <h2 id="_language_objects.pod6-Inheritance">Inheritance</h2>
<p>Roles cannot inherit from classes, but they may cause any class which does that role to inherit from another class. So if you write:</p>
<pre class="code">role A is Exception { }
class X::Ouch does A { }
X::Ouch.^parents.say # OUTPUT: «((Exception))␤»
</pre>
<p>then <span class="code">X::Ouch</span> will inherit directly from Exception, as we can see above by listing its parents.</p>
<a name="t31.3.4"></a> <h2 id="_language_objects.pod6-Pecking_order">Pecking order</h2>
<p>A method defined directly in a class will always override definitions from applied roles or from inherited classes. If no such definition exists, methods from roles override methods inherited from classes. This happens both when said class was brought in by a role, and also when said class was inherited directly.</p>
<pre class="code">role M {
method f { say &quot;I am in role M&quot; }
}
class A {
method f { say &quot;I am in class A&quot; }
}
class B is A does M {
method f { say &quot;I am in class B&quot; }
}
class C is A does M { }
B.new.f; # OUTPUT «I am in class B␤»
C.new.f; # OUTPUT «I am in role M␤»</pre>
<p>Note that each candidate for a multi-method is its own method. In this case, the above only applies if two such candidates have the same signature. Otherwise, there is no conflict, and the candidate is just added to the multi-method.</p>
<a name="t31.3.5"></a> <h2 id="_language_objects.pod6-Automatic_Role_Punning">Automatic Role Punning</h2>
<p>Any attempt to directly instantiate a role, as well as many other operations on it, will automatically create an instance of 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 =&gt; 6, y =&gt; 8).abs; # OUTPUT «10␤»
</pre>
<p>We call this automatic creation of classes <i>punning</i>, and the generated class a <i>pun</i>.</p>
<a name="t31.3.6"></a> <h2 id="_language_objects.pod6-Parameterized_Roles">Parameterized Roles</h2>
<p><a id="i302" name="Parameterized Roles"></a><span class="indexed"></span></p>
<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 -&gt; $branch {
$branch.visit-preorder(&amp;cb) if defined $branch;
}
}
method visit-postorder(&amp;cb) {
for $.left, $.right -&gt; $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 =&gt; $middle,
left =&gt; @left ?? self.new-from-list(@left) !! self,
right =&gt; @right ?? self.new-from-list(@right) !! self,
);
}
}
my $t = BinaryTree[Int].new-from-list(4, 5, 6);
$t.visit-preorder(&amp;say); # OUTPUT: «5␤4␤6␤»
$t.visit-postorder(&amp;say); # OUTPUT: «4␤6␤5␤»
</pre>
<p>Here the signature consists only of a type capture, but any signature will do:</p>
<pre class="code">enum Severity &lt;debug info warn error critical&gt;;
role Logging[$filehandle = $*ERR] {
method log(Severity $sev, $message) {
$filehandle.print(&quot;[{uc $sev}] $message\n&quot;);
}
}
Logging[$*OUT].log(debug, 'here we go'); # OUTPUT: «[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="t31.3.7"></a> <h2 id="_language_objects.pod6-Mixins_of_Roles"><a name="303"></a>Mixins of Roles</h2>
<p>Roles can be mixed into objects. A role's given attributes and methods will be added to the methods and attributes the object already has. Multiple mixins and anonymous roles are supported.</p>
<pre class="code">role R { method Str() {'hidden!'} };
my $i = 2 but R;
sub f(\bound){ put bound };
f($i); # OUTPUT: «hidden!␤»</pre>
<p>Note that the object got the role mixed in, not the object's class or the container. Thus, @-sigiled containers will require binding to make the role stick. Some operators will return a new value, which effectively strips the mixin from the result.</p>
<p>Mixins can be used at any point in your object's 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 math with Not A Number
say $toc-counter; # OUTPUT: «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; # OUTPUT: «NaN␤» (because that's numerical context)
put $toc-counter; # OUTPUT: «2.2.2␤» (put will call TOC-Counter::Str)</pre>
<p>Roles can be anonymous.</p>
<pre class="code">my %seen of Int is default(0 but role :: { method Str() {'NULL'} });
say %seen&lt;not-there&gt;; # OUTPUT: «NULL␤»
say %seen&lt;not-there&gt;.defined; # OUTPUT: «True␤» (0 may be False but is well defined)
say Int.new(%seen&lt;not-there&gt;); # OUTPUT: «0␤»</pre>
<a name="t31.4"></a> <h1 id="_language_objects.pod6-Meta-Object_Programming_and_Introspection">Meta-Object Programming and Introspection</h1>
<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 works 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; # OUTPUT: «True␤»
say 1.HOW === Int.HOW; # OUTPUT: «True␤»
say 1.HOW === Num.HOW; # OUTPUT: «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); # OUTPUT: «Int␤»
# or shorter:
say 1.HOW.name(1); # OUTPUT: «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>There's a shortcut to keep from using the same object twice:</p>
<pre class="code">say 1.^name; # OUTPUT: «Int␤»
# same as
say 1.HOW.name(1); # OUTPUT: «Int␤»</pre>
<p>See <a href="#_type_Metamodel::ClassHOW.pod6">Metamodel::ClassHOW</a> for documentation on the meta class of <span class="code">class</span> and also the <a href="#_language_mop.pod6">general documentation on the meta object protocol</a>.</p>
</div>
<!-- /language/operators.pod6 --><div class="pod-body"><a id="_language_operators.pod6"></a><a name="t32"></a><h1 class="title">32 Operators</h1> <p class="subtitle">Common Perl 6 infixes, prefixes, postfixes, and more!</p> <p>See <a href="#_type_Sub.pod6">Sub</a> on how to define operators.</p>
<a name="t32.1"></a> <h1 id="_language_operators.pod6-Operator_Precedence">Operator Precedence</h1>
<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 &quot;eek&quot; qq[&quot;foo&quot;] $x :!verbose @$array</td></tr>
<tr><td>L</td> <td>Method postfix</td> <td>.meth .+ .? .* .() .[] .{} .&lt;&gt; .«» .:: .= .^ .:</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>Dotty infix</td> <td>.= .</td></tr>
<tr><td>L</td> <td>Multiplicative</td> <td>* / % %% +&amp; +&lt; +&gt; ~&amp; ~&lt; ~&gt; ?&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;=&gt; leg cmp .. ..^ ^.. ^..^</td></tr>
<tr><td>C</td> <td>Chaining infix</td> <td>!= == &lt; &lt;= &gt; &gt;= 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>= =&gt; += -= **= 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 notandthen</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;==, ==&gt;, &lt;&lt;==, ==&gt;&gt;</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;!&gt;($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="t32.2"></a> <h1 id="_language_operators.pod6-Operator_classification">Operator classification</h1>
<p><a id="i304" name="prefix operator"></a><span class="indexed"></span> <a id="i305" name="infix operator"></a><span class="indexed"></span> <a id="i306" name="postfix operator"></a><span class="indexed"></span> <a id="i307" name="circumfix operator"></a><span class="indexed"></span> <a id="i308" name="postcircumfix operator"></a><span class="indexed"></span></p>
<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;+&gt;(1, 2); # same as 1 + 2
circumfix:«[ ]»(&lt;a b c&gt;); # same as [&lt;a b c&gt;]</pre>
<p>As a special case, a <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="#31-prefix ...">#prefix ...</a> etc. stub operators.</p>
<p>Defining custom operators is covered in <a href="#_language_functions.pod6-Defining_Operators">Defining Operators functions</a>.</p>
<a name="t32.3"></a> <h1 id="_language_operators.pod6-Meta_Operators">Meta Operators</h1>
<p>Meta operators can be parameterized with other operators or subroutines in the same way as functions can take functions as parameters. To use a subroutine as a parameter, prefix its name with a <span class="code">&amp;</span>. Perl 6 will generate the actual combined operator in the background, allowing the mechanism to be applied to user defined operators. To disambiguate chained meta operators enclose the inner operator in square brackets. There are quite a few Meta operators with different semantics as explained, next.</p>
<a name="t32.4"></a> <h1 id="_language_operators.pod6-Substitution_Operators">Substitution Operators</h1>
<a name="t32.4.1"></a> <h2 id="_language_operators.pod6-s///_in-place_substitution"><span class="code">s///</span> in-place substitution</h2>
<pre class="code">my $str = 'old string';
$str ~~ s/o .+ d/new/;
say $str; # OUTPUT: «new string␤»</pre>
<p>Operates on <span class="code">$_</span> topical variable, changing it in place. Uses the given <a href="#_type_Regex.pod6"><span class="code">Regex</span></a> to find portions to replace and changes them to the provided replacement string. Sets <span class="code">$/</span> to the <a href="#_type_Match.pod6"><span class="code">Match</span></a> object or, if multiple matches were made, a <a href="#_type_List.pod6"><span class="code">List</span></a> of <span class="code">Match</span> objects. Returns <span class="code">$/</span>.</p>
<p>It's common to use this operator with the <span class="code">~~</span> smartmatch operator, as it aliases left hand side to <span class="code">$_</span>, which <span class="code">s///</span> uses.</p>
<p>Regex captures can be referenced in the replacement part. Takes the same adverbs as the <a href="#_routine_subst.pod6"><span class="code">.subst</span> method</a>, which go between the <span class="code">s</span> and the opening <span class="code">/</span>, separated with optional whitespace:</p>
<pre class="code">my $str = 'foo muCKed into the lEn';
# replace second 'o' with 'x'
$str ~~ s:2nd/o/x/;
# replace 'M' or 'L' followed by non-whitespace stuff with 'd'
# and lower-cased version of that stuff:
$str ~~ s :g :i/&lt;[ML]&gt; (\S+)/d{lc $0}/;
say $str; # OUTPUT: «fox ducked into the den␤»</pre>
<p>You can also use a different delimiter:</p>
<pre class="code">my $str = 'foober';
$str ~~ s!foo!fox!;
$str ~~ s{b(.)r} = &quot; d$0n&quot;;
say $str; # OUTPUT: «fox den␤»</pre>
<p>Non-paired characters can simply replace the original slashes. Paired characters, like braces, are used only on the match portion, with the substitution given by assignment (of anything: a string, a routine call, etc.).</p>
<a name="t32.4.2"></a> <h2 id="_language_operators.pod6-S///_non-destructive_substitution"><span class="code">S///</span> non-destructive substitution</h2>
<pre class="code">say S/o .+ d/new/ with 'old string'; # OUTPUT: «new string␤»
S:g/« (.)/$0.uc()/.say for &lt;foo bar ber&gt;; # OUTPUT: «Foo␤Bar␤Ber␤»</pre>
<p>Same semantics as the <span class="code">s///</span> operator, except leaves the original string intact and <i>returns the resultant string</i> instead of <span class="code">$/</span> (<span class="code">$/</span> still being set to the same values as with <span class="code">s///</span>).</p>
<p><b>Note:</b> since the result is obtained as a return value, using this operator with the <span class="code">~~</span> smartmatch operator is a mistake and will issue a warning. To execute the substitution on a variable that isn't the <span class="code">$_</span> this operator uses, alias it to <span class="code">$_</span> with <span class="code">given</span>, <span class="code">with</span>, or any other way. Alternatively, use the <a href="#_routine_subst.pod6"><span class="code">.subst</span> method</a>.</p>
<a name="t32.4.3"></a> <h2 id="_language_operators.pod6-tr///_in-place_transliteration"><span class="code">tr///</span> in-place transliteration</h2>
<pre class="code">my $str = 'old string';
$str ~~ tr/dol/wne/;
say $str; # OUTPUT: «new string␤»</pre>
<p>Operates on <span class="code">$_</span> topical variable, changing it in place. Behaves similar to <a href="#_routine_trans.pod6"><span class="code">Str.trans</span></a> called with a single <a href="#_type_Pair.pod6">Pair</a> argument where key is the matching part (characters <span class="code">dol</span> in example above) and value is the replacement part (characters <span class="code">wne</span> in the example above). Accepts the same adverbs as <a href="#_routine_trans.pod6"><span class="code">Str.trans</span></a>. Returns <a href="#_type_StrDistance.pod6">StrDistance</a> object that measures the distance between original value and the resultant string.</p>
<pre class="code">my $str = 'old string';
$str ~~ tr:c:d/dol st//;
say $str; # OUTPUT: «ring␤»</pre>
<a name="t32.4.4"></a> <h2 id="_language_operators.pod6-TR///_non-destructive_transliteration"><span class="code">TR///</span> non-destructive transliteration</h2>
<pre class="code">with 'old string' {
say TR/dol/wne/; # OUTPUT: «new string␤»
}</pre>
<p>Behaves the same as <span class="code">tr///</span> operator with the exception that it leaves <span class="code">$_</span> value untouched and instead returns the resultant string.</p>
<pre class="code">say TR:d/dol // with 'old string'; # OUTPUT: «string␤»</pre>
<a name="t32.5"></a> <h1 id="_language_operators.pod6-Assignment_Operators">Assignment Operators</h1>
<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. Some examples:</p>
<pre class="code">my $a = 32;
$a += 10; # 42
$a -= 2; # 40
$a = 3;
$a min= 5; # still 3
$a min= 2; # 2
my $s = 'a';
$s ~= 'b'; # 'ab'</pre>
<p>This behavior is automatically extended to include custom-defined infix operators.</p>
<pre class="code">sub infix:&lt;space-concat&gt; ($a, $b) { $a ~ &quot; &quot; ~ $b };
my $a = 'word1';
$a space-concat= 'word2'; # RESULT: «'word1 word2'»</pre>
<p>Although not strictly operators, methods can be used in the same fashion.</p>
<pre class="code">my Real $a = 1/2;
$a = 3.14;
$a .= round; # RESULT: «3»</pre>
<a name="t32.6"></a> <h1 id="_language_operators.pod6-Negated_Relational_Operators">Negated Relational Operators <a name="309"></a><a name="310"></a><a name="311"></a></h1>
<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 visual 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; # OUTPUT: «False␤»
my $i = 10;
my $release = Date.new(:2015year, :12month, :24day);
my $today = Date.today;
say so $release !before $today; # OUTPUT: «False␤»</pre>
<a name="t32.7"></a> <h1 id="_language_operators.pod6-Reversed_Operators">Reversed Operators <a name="312"></a></h1>
<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 4 R/ 12; # OUTPUT: «3␤»
say [R/] 2, 4, 16; # OUTPUT: «2␤»</pre>
<a name="t32.8"></a> <h1 id="_language_operators.pod6-Hyper_Operators"><a name="313"></a>Hyper Operators</h1>
<p>Hyper Operators include <span class="code">«</span> and <span class="code">»</span>, with their ASCII variants <span class="code">&lt;&lt;</span> and <span class="code">&gt;&gt;</span>.</p>
<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 than 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; # OUTPUT: «(2 4 6)␤»
say (1, 2, 3, 4) »~» &lt;a b&gt;; # OUTPUT: «(1a 2b 3a 4b)␤»
say (1, 2, 3) »+« (4, 5, 6); # OUTPUT: «(5 7 9)␤»</pre>
<p>Assignment meta operators can be hyped.</p>
<pre class="code">my @a = 1, 2, 3;
say @a »+=» 1; # OUTPUT: «[2 3 4]␤»</pre>
<p>Hyper forms of unary operators 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; # OUTPUT: «[False True False]␤»
my @a = 1, 2, 3;
@a»++; # OUTPUT: «(2, 3, 4)␤»</pre>
<p>Hyper operators are defined recursively on nested arrays.</p>
<pre class="code">say -« [[1, 2], 3]; # OUTPUT: «[[-1 -2] -3]␤»</pre>
<p>Also, methods can be called in an out of order, concurrent fashion. The resulting list is in order. Note that all hyper operators are candidates for autothreading and will cause tears if the methods have side effects. The optimizer has full reign over hyper operators, which is the reason that they cannot be defined by the user.</p>
<pre class="code">class CarefulClass { method take-care {} }
my CarefulClass @objs;
my @results = @objs».take-care();
my @slops; # May Contain Nuts
@slops».?this-method-may-not-exist();</pre>
<p>Hyper operators can work with hashes. The pointy direction indicates if missing keys are to be ignored in the resulting hash. The enclosed operator operates on all values that have keys in both hashes.</p>
<table>
<tr><td>%foo «+» %bar;</td> <td>intersection of keys</td></tr>
<tr><td>%foo »+« %bar;</td> <td>union of keys</td></tr>
<tr><td>%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=&gt; &lt;a b c&gt;;
my %inner = 1, 2 Z=&gt; &lt;x z&gt;;
say %outer «~» %inner; # OUTPUT: «{&quot;1&quot; =&gt; &quot;ax&quot;, &quot;2&quot; =&gt; &quot;bz&quot;}␤»</pre>
<p>Hyper operators can take user defined operators as its operator argument.</p>
<pre class="code">sub pretty-file-site (Int $size --&gt; Str) {
# rounding version of infix:&lt;/&gt;(Int, Int)
sub infix:&lt;r/&gt;(Int \i1, Int \i2) {
round(i1 / i2, 0.1)
}
# we build a vector of fractions of $size and zip that with the fitting prefix
for $size «[r/]« (2**60, 2**50, 2**40, 2**30, 2**20, 2**10)
Z &lt;EB PB TB GB MB KB&gt; -&gt; [\v,\suffix] {
# starting with the biggest suffix, we take the first that is 0.5 of that suffix or bigger
return v ~ ' ' ~ suffix if v &gt; 0.4
}
# this be smaller or equal then 0.4 KB
return $size.Str;
}
for 60, 50, 40, 30, 20, 10 -&gt; $test {
my &amp;a = { (2 ** $test) * (1/4, 1/2, 1, 10, 100).pick * (1..10).pick };
print pretty-file-site(a.Int) xx 2, ' ';
}
# OUTPUT: «10 EB 4 EB 2 PB 5 PB 0.5 PB 4 TB 300 GB 4.5 GB 50 MB 200 MB 9 KB 0.6 MB␤»</pre>
<p>Whether hyperoperators descend into child lists depends on the <a href="#_language_typesystem.pod6-trait_is_nodal">nodality</a> of the inner operator of a chain. For the hyper method call operator (».) the nodality of the target method is significant.</p>
<pre class="code">say (&lt;a b&gt;, &lt;c d e&gt;)».elems; # OUTPUT: «(2 3)␤»
say (&lt;a b&gt;, &lt;c d e&gt;)».&amp;{ .elems }; # OUTPUT: «((1 1) (1 1 1))␤»</pre>
<p>You can chain hyper operators to destructure a List of Lists.</p>
<pre class="code">my $neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0));
my $p = (2, 3);
say $neighbors »&gt;&gt;+&lt;&lt;» ($p, *); # OUTPUT: «((1 3) (2 2) (2 4) (3 3))␤»</pre>
<a name="t32.9"></a> <h1 id="_language_operators.pod6-Reduction_Operators">Reduction Operators <a name="314"></a><a name="315"></a></h1>
<p>The reduction metaoperator, <span class="code">[ ]</span>, reduces a list with the given infix operator. It gives the same result as the <a href="#_routine_reduce.pod6">reduce</a> routine - see there for details.</p>
<pre class="code"># These two are equivalent:
say [+] 1, 2, 3; # OUTPUT: «6␤»
say reduce &amp;infix:&lt;+&gt;, 1, 2, 3; # OUTPUT: «6␤»</pre>
<p>No whitespace is allowed between the brackets and the operator. To wrap a function instead of an operator, provide an additional layer of brackets:</p>
<pre class="code">sub plus { $^a + $^b };
say [[&amp;plus]] 1, 2, 3; # OUTPUT: «6␤»</pre>
<p>The argument list is iterated without flattening. This means that you can pass a nested list to the reducing form of a list infix operator:</p>
<pre class="code">say [X~] (1, 2), &lt;a b&gt;; # OUTPUT: «1, 2 X~ &lt;a b&gt;␤»</pre>
<p>By default, only the final result of the reduction is returned. Prefix the wrapped operator with a <span class="code">\</span>, to return a lazy list of all intermediate values instead. This is called a &quot;triangular reduce&quot;. 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 @n = [\~] 1..*;
say @n[^5]; # OUTPUT: «(1 12 123 1234 12345)␤»</pre>
<a name="t32.10"></a> <h1 id="_language_operators.pod6-Cross_Operators">Cross Operators <a name="316"></a></h1>
<p>The cross metaoperator, <span class="code">X</span>, will apply a given infix operator in order of cross product to all lists, such that the rightmost operator varies most quickly.</p>
<pre class="code">1..3 X~ &lt;a b&gt; # RESULT: «&lt;1a, 1b, 2a, 2b, 3a, 3b&gt;␤»</pre>
<a name="t32.11"></a> <h1 id="_language_operators.pod6-Zip_Operators">Zip Operators <a name="317"></a></h1>
<p>The zip metaoperator, (which is not the same thing as <a href="#31-infix_Z">Z</a>), will apply a given infix operator to pairs taken one left, one right, from its arguments. The resulting list is returned.</p>
<pre class="code">my @l = &lt;a b c&gt; Z~ 1, 2, 3; # RESULT: «[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. A list with a final element of <span class="code">*</span> will repeat its 2nd last element indefinitely.</p>
<pre class="code">my @l = &lt;a b c d&gt; Z~ ':' xx *; # RESULT: «&lt;a: b: c: d:&gt;»
@l = &lt;a b c d&gt; Z~ 1, 2, *; # RESULT: «&lt;a1 b2 c2 d2&gt;»</pre>
<p>If infix operator is not given, <span class="code">,</span> (comma operator) will be used by default:</p>
<pre class="code">my @l = 1 Z 2; # RESULT: «[(1 2)]»</pre>
<a name="t32.12"></a> <h1 id="_language_operators.pod6-Sequential_Operators">Sequential Operators <a name="318"></a></h1>
<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; # OUTPUT: «True␤»</pre>
<a name="t32.13"></a> <h1 id="_language_operators.pod6-Nesting_of_Meta_Operators">Nesting of Meta Operators</h1>
<p>To avoid ambiguity when chaining meta operators, use square brackets to help the compiler understand you.</p>
<pre class="code">my @a = 1, 2, 3;
my @b = 5, 6, 7;
@a X[+=] @b;
say @a; # OUTPUT: «[19 20 21]␤»</pre>
<a name="t32.14"></a> <h1 id="_language_operators.pod6-Term_Precedence"><!-- -->Term Precedence</h1>
<a name="t32.14.1"></a> <h2 id="_language_operators.pod6-term_&lt;_&gt;">term <span class="code">&lt; &gt;</span></h2>
<p>The <a id="i319" name="qw quote-words"></a><span class="indexed">quote-words</span> construct breaks up the contents on whitespace and returns a <a href="#_type_List.pod6">List</a> of the words. If a word looks like a number literal or a <span class="code">Pair</span> literal, it's converted to the appropriate number.</p>
<pre class="code">say &lt;a b c&gt;[1]; # OUTPUT: «b␤»</pre>
<a name="t32.14.2"></a> <h2 id="_language_operators.pod6-term_(_)">term <span class="code">( )</span></h2>
<p>The <a id="i320" name=""></a><span class="indexed">grouping operator</span>.</p>
<p>An empty group <span class="code">()</span> creates an <a href="#_type_List.pod6-index-entry-()_empty_list">empty list</a>. Parentheses around non-empty expressions simply structure the expression, but do 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 =&gt; 1; # OUTPUT: «named␤»
p (a =&gt; 1); # OUTPUT: «positional␤»</pre>
<a name="t32.14.3"></a> <h2 id="_language_operators.pod6-term_{_}">term <span class="code">{ }</span></h2>
<p>Block or <a href="#_type_Hash.pod6">Hash</a> constructor.<a id="i321" name="block constructor hash constructor"></a><span class="indexed"></span></p>
<p>If the content looks like a list of pairs and does not use <a href="#_syntax_$_.pod6">$_</a> or other placeholder parameters, the constructor returns an itemized <a href="#_type_Hash.pod6">Hash</a>.</p>
<p>Otherwise it constructs a <a href="#_type_Block.pod6">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="#_type_Hash.pod6">Hash</a>.</p>
<a name="t32.14.4"></a> <h2 id="_language_operators.pod6-circumfix_[_]">circumfix <span class="code">[ ]</span></h2>
<p>The <a id="i322" name=""></a><span class="indexed"><a href="#_type_Array.pod6">Array</a> constructor</span> returns an itemized <a href="#_type_Array.pod6">Array</a> which does not flatten in list context.</p>
<a name="t32.15"></a> <h1 id="_language_operators.pod6-Method_Postfix_Precedence">Method Postfix Precedence</h1>
<a name="t32.15.1"></a> <h2 id="_language_operators.pod6-postcircumfix_[_]">postcircumfix <span class="code">[ ]</span></h2>
<pre class="code">sub postcircumfix:&lt;[ ]&gt;(@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. &quot;<a id="i323" name="array indexing operator array subscript operator"></a><span class="indexed">array indexing operator</span>&quot;.</p>
<pre class="code">my @alphabet = 'a' .. 'z';
say @alphabet[0]; # OUTPUT: «a␤»
say @alphabet[1]; # OUTPUT: «b␤»
say @alphabet[*-1]; # OUTPUT: «z␤»
say @alphabet[100]:exists; # OUTPUT: «False␤»
say @alphabet[15, 4, 17, 11].join; # OUTPUT: «perl␤»
say @alphabet[23 .. *].perl; # OUTPUT: «(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;)␤»
@alphabet[1, 2] = &quot;B&quot;, &quot;C&quot;;
say @alphabet[0..3].perl # OUTPUT: «(&quot;a&quot;, &quot;B&quot;, &quot;C&quot;, &quot;d&quot;)␤»</pre>
<p>See <a href="#_language_subscripts.pod6">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="t32.15.2"></a> <h2 id="_language_operators.pod6-postcircumfix_{_}">postcircumfix <span class="code">{ }</span></h2>
<pre class="code">sub postcircumfix:&lt;{ }&gt;(%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. &quot;<a id="i324" name="hash indexing operator hash subscript operator"></a><span class="indexed">hash indexing operator</span>&quot;.</p>
<pre class="code">my %color = kiwi =&gt; &quot;green&quot;, banana =&gt; &quot;yellow&quot;, cherry =&gt; &quot;red&quot;;
say %color{&quot;banana&quot;}; # OUTPUT: «yellow␤»
say %color{&quot;cherry&quot;, &quot;kiwi&quot;}.perl; # OUTPUT: «(&quot;red&quot;, &quot;green&quot;)␤»
say %color{&quot;strawberry&quot;}:exists; # OUTPUT: «False␤»
%color{&quot;banana&quot;, &quot;lime&quot;} = &quot;yellowish&quot;, &quot;green&quot;;
%color{&quot;cherry&quot;}:delete;
say %color; # OUTPUT: «banana =&gt; yellowish, kiwi =&gt; green, lime =&gt; green␤»</pre>
<p>See <a href="#_routine_&lt; &gt;.pod6-(Operators)_postcircumfix_&lt;_&gt;"><span class="code">postcircumfix &lt; &gt;</span></a> and <a href="#_routine_« ».pod6-(Operators)_postcircumfix_«_»"><span class="code">postcircumfix « »</span></a> for convenient shortcuts, and <a href="#_language_subscripts.pod6">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="t32.15.3"></a> <h2 id="_language_operators.pod6-postcircumfix_&lt;_&gt;">postcircumfix <span class="code">&lt; &gt;</span></h2>
<p>Shortcut for <a href="#_routine_{ }.pod6-(Operators)_postcircumfix_{_}"><span class="code">postcircumfix { }</span></a> that quotes its argument using the same rules as the <a href="#_routine_&lt; &gt;.pod6-circumfix_&lt;_&gt;">quote-words operator</a> of the same name.</p>
<pre class="code">my %color = kiwi =&gt; &quot;green&quot;, banana =&gt; &quot;yellow&quot;, cherry =&gt; &quot;red&quot;;
say %color&lt;banana&gt;; # OUTPUT: «yellow␤»
say %color&lt;cherry kiwi&gt;.perl; # OUTPUT: «(&quot;red&quot;, &quot;green&quot;)␤»
say %color&lt;strawberry&gt;:exists; # OUTPUT: «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="t32.15.4"></a> <h2 id="_language_operators.pod6-postcircumfix_«_»">postcircumfix <span class="code">« »</span></h2>
<p>Shortcut for <a href="#_routine_{ }.pod6-(Operators)_postcircumfix_{_}"><span class="code">postcircumfix { }</span></a> that quotes its argument using the same rules as the <a href="#_routine_« ».pod6-circumfix_«_»">interpolating quote-words operator</a> of the same name.</p>
<pre class="code">my %color = kiwi =&gt; &quot;green&quot;, banana =&gt; &quot;yellow&quot;, cherry =&gt; &quot;red&quot;;
my $fruit = &quot;kiwi&quot;;
say %color«cherry &quot;$fruit&quot;».perl; # OUTPUT: «(&quot;red&quot;, &quot;green&quot;)␤»</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="t32.15.5"></a> <h2 id="_language_operators.pod6-postcircumfix_(_)">postcircumfix <span class="code">( )</span></h2>
<p>The <a id="i325" name=""></a><span class="indexed">call operator</span> treats the invocant as a <a href="#_type_Callable.pod6">Callable</a> and invokes it, using the expression between the parentheses as arguments.</p>
<p>Note that an identifier followed by a pair of parentheses 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="t32.15.6"></a> <h2 id="_language_operators.pod6-postfix_.">postfix <span class="code">.</span></h2>
<p>The operator for calling one method, <span class="code">$invocant.method</span>.<a id="i326" name="method call"></a><span class="indexed"></span></p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<p><a id="i327" name="postfix .&amp;"></a><span class="indexed"></span></p>
<a name="t32.15.7"></a> <h2 id="_language_operators.pod6-postfix_.&amp;">postfix <span class="code">.&amp;</span></h2>
<p>The operator to call a subroutine (with at least one positional argument) like a method. The invocant will be bound to the first positional argument.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<pre class="code">my sub f($invocant){ &quot;The arg has a value of $invocant&quot; }
42.&amp;f;
# OUTPUT: «The arg has a value of 42␤»
42.&amp;(-&gt; $invocant { &quot;The arg has a value of $invocant&quot; });
# OUTPUT: «The arg has a value of 42␤»</pre>
<a name="t32.15.8"></a> <h2 id="_language_operators.pod6-postfix_.=">postfix <span class="code">.=</span></h2>
<p>A <a id="i328" name=""></a><span class="indexed">mutating method call</span>. <span class="code">$invocant.=method</span> desugars to <span class="code">$invocant = $invocant.method</span>, similar to <a href="&lt;span class=&quot;code&quot;&gt;=&lt;/span&gt;"><span class="code">=</span></a>.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<p><a id="i329" name="postfix .^"></a><span class="indexed"></span></p>
<a name="t32.15.9"></a> <h2 id="_language_operators.pod6-postfix_.^">postfix <span class="code">.^</span></h2>
<p>A <a id="i330" name=""></a><span class="indexed">meta-method call</span>. <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="#_language_mop.pod6-index-entry-syntax_HOW-HOW">HOW</a> for more information.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<p><a id="i331" name="postfix .?"></a><span class="indexed"></span></p>
<a name="t32.15.10"></a> <h2 id="_language_operators.pod6-postfix_.?">postfix <span class="code">.?</span></h2>
<p><a id="i332" name=""></a><span class="indexed">Safe call operator</span>. <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="#_type_Nil.pod6">Nil</a>.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<p><a id="i333" name="postfix .+"></a><span class="indexed"></span></p>
<a name="t32.15.11"></a> <h2 id="_language_operators.pod6-postfix_.+">postfix <span class="code">.+</span></h2>
<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="#_type_List.pod6">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>
<p><a id="i334" name="postfix .*"></a><span class="indexed"></span></p>
<a name="t32.15.12"></a> <h2 id="_language_operators.pod6-postfix_.*">postfix <span class="code">.*</span></h2>
<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="#_type_List.pod6">List</a> of the results. If no such method was found, an empty <a href="#_type_List.pod6">List</a> is returned.</p>
<p>Technically this is not an operator, but syntax special-cased in the compiler.</p>
<p><a id="i335" name="postfix »."></a><span class="indexed"></span><a id="i336" name="postfix &gt;&gt;."></a><span class="indexed"></span></p>
<a name="t32.15.13"></a> <h2 id="_language_operators.pod6-postfix_»._/_postfix_&gt;&gt;.">postfix <span class="code">».</span> / postfix <span class="code">&gt;&gt;.</span></h2>
<p><a id="i337" name=""></a><span class="indexed">Hyper method call operator</span>. 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&gt;;
my @b = @a».ord; # OUTPUT: «[97, 98, 99]␤»
sub foo(Str:D $c){ $c.ord * 2 }; # The first parameter of a method is the invocant.
say @a».&amp;foo; # So we can pretend to have a method call with a sub that got a good first positional argument.
say @a».&amp;{ .ord}; # Blocks have an implicit positional arguments that lands in $_. The latter can be omitted for method calls.</pre>
<p>Take care to avoid a <a href="#_language_traps.pod6-Using_»_and_map_interchangeably">common mistake</a> of expecting side-effects to occur in order. The following <span class="code">say</span> is <b>not</b> guaranteed to produce the output in order:</p>
<pre class="code">@a».say; # WRONG! Could produce a␤b␤c␤ or c␤b␤a␤ or any other order
</pre>
<a name="t32.15.14"></a> <h2 id="_language_operators.pod6-postfix_.postfix_/_.postcircumfix">postfix <span class="code">.postfix</span> / <span class="code">.postcircumfix</span> <a name="338"></a><a name="339"></a><a name="340"></a></h2>
<p>In most cases, a dot may be placed before a postfix or postcircumfix:</p>
<pre class="code">my @a;
@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;+&gt;, :function{ $^a + $^b });
say $addition.function()(1, 2); # OUTPUT: «3␤»
# OR
say $addition.function.(1, 2); # OUTPUT: «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. <a id="i341" name="postfix call"></a><span class="indexed"></span></p>
<a name="t32.15.15"></a> <h2 id="_language_operators.pod6-postfix_.:&lt;prefix&gt;">postfix <span class="code">.:&lt;prefix&gt;</span></h2>
<p>A prefix can be called like a method using colonpair notation. For example:</p>
<pre class="code">my $a = 1;
say ++$a; # OUTPUT: «2␤»
say $a.:&lt;++&gt;; # OUTPUT: «3␤»</pre>
<p>Technically this is not an operator, but syntax special-cased in the compiler. <a id="i342" name="prefix call"></a><span class="indexed"></span></p>
<a name="t32.15.16"></a> <h2 id="_language_operators.pod6-postfix_.::">postfix <span class="code">.::</span></h2>
<p>A <a id="i343" name=""></a><span class="indexed">class-qualified method call</span>, 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 { &quot;nope&quot; }
}
say Foo.Bar::baz; # OUTPUT: «42␤»</pre>
<a name="t32.16"></a> <h1 id="_language_operators.pod6-Autoincrement_Precedence">Autoincrement Precedence</h1>
<a name="t32.16.1"></a> <h2 id="_language_operators.pod6-prefix_++">prefix <a name="344"></a><span class="code">++</span></h2>
<pre class="code">multi sub prefix:&lt;++&gt;($x is rw) is assoc&lt;non&gt;</pre>
<p>Increments its argument by one, and returns the updated value.<a id="i345" name="increment operator"></a><span class="indexed"></span></p>
<pre class="code">my $x = 3;
say ++$x; # OUTPUT: «4␤»
say $x; # OUTPUT: «4␤»</pre>
<p>It works by calling the <a href="#_routine_succ.pod6">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="t32.16.2"></a> <h2 id="_language_operators.pod6-prefix_--">prefix <a name="346"></a><span class="code">--</span></h2>
<pre class="code">multi sub prefix:&lt;--&gt;($x is rw) is assoc&lt;non&gt;</pre>
<p>Decrements its argument by one, and returns the updated value.<a id="i347" name="decrement operator"></a><span class="indexed"></span></p>
<pre class="code">my $x = 3;
say --$x; # OUTPUT: «2␤»
say $x; # OUTPUT: «2␤»</pre>
<p>It works by calling the <a href="#_routine_pred.pod6">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="t32.16.3"></a> <h2 id="_language_operators.pod6-postfix_++">postfix <a name="348"></a><span class="code">++</span></h2>
<pre class="code">multi sub postfix:&lt;++&gt;($x is rw) is assoc&lt;non&gt;</pre>
<p>Increments its argument by one, and returns the original value.<a id="i349" name="increment operator"></a><span class="indexed"></span></p>
<pre class="code">my $x = 3;
say $x++; # OUTPUT: «3␤»
say $x; # OUTPUT: «4␤»</pre>
<p>It works by calling the <a href="#_routine_succ.pod6">succ</a> method (for <i>successor</i>) on its argument, which gives custom types the freedom to implement their own increment semantics.</p>
<p>Note that this does not necessarily return its argument; e.g., for undefined values, it returns 0:</p>
<pre class="code">my $x;
say $x++; # OUTPUT: «0␤»
say $x; # OUTPUT: «1␤»</pre>
<p>Increment on <a href="#_type_Str.pod6">Str</a> will increment the number part of a string and assign the resulting string to the container. A <span class="code">is rw</span>-container is required.</p>
<pre class="code">my $filename = &quot;somefile-001.txt&quot;;
say $filename++ for 1..3;
# OUTPUT: «somefile-001.txt␤somefile-002.txt␤somefile-003.txt␤»</pre>
<a name="t32.16.4"></a> <h2 id="_language_operators.pod6-postfix_--">postfix <span class="code">--</span></h2>
<pre class="code">multi sub postfix:&lt;--&gt;($x is rw) is assoc&lt;non&gt;</pre>
<p>Decrements its argument by one, and returns the original value.<a id="i350" name="decrement operator"></a><span class="indexed"></span></p>
<pre class="code">my $x = 3;
say $x--; # OUTPUT: «3␤»
say $x; # OUTPUT: «2␤»</pre>
<p>It works by calling the <a href="#_routine_pred.pod6">pred</a> method (for <i>predecessor</i>) on its argument, which gives custom types the freedom to implement their own decrement semantics.</p>
<p>Note that this does not necessarily return its argument;e.g., for undefined values, it returns 0:</p>
<pre class="code">my $x;
say $x--; # OUTPUT: «0␤»
say $x; # OUTPUT: «-1␤»</pre>
<p>Decrement on <a href="#_type_Str.pod6">Str</a> will decrement the number part of a string and assign the resulting string to the container. A <span class="code">is rw</span>-container is required. Crossing 0 is prohibited and throws <span class="code">X::AdHoc</span>.</p>
<pre class="code">my $filename = &quot;somefile-003.txt&quot;;
say $filename-- for 1..3;
# OUTPUT: «somefile-003.txt␤somefile-002.txt␤somefile-001.txt␤»</pre>
<a name="t32.17"></a> <h1 id="_language_operators.pod6-Exponentiation_Precedence">Exponentiation Precedence</h1>
<a name="t32.17.1"></a> <h2 id="_language_operators.pod6-infix_**">infix <span class="code">**</span></h2>
<pre class="code">multi sub infix:&lt;**&gt;(Any, Any --&gt; Numeric:D) is assoc&lt;right&gt;</pre>
<p>The <a id="i351" name=""></a><span class="indexed">exponentiation operator</span> coerces both arguments to <a href="#_type_Numeric.pod6">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="#_type_Int.pod6">Int</a>, <a href="#_type_FatRat.pod6">FatRat</a>), then the calculation is carried out without loss of precision.</p>
<a name="t32.18"></a> <h1 id="_language_operators.pod6-Symbolic_Unary_Precedence">Symbolic Unary Precedence</h1>
<a name="t32.18.1"></a> <h2 id="_language_operators.pod6-prefix_?">prefix <span class="code">?</span></h2>
<pre class="code">multi sub prefix:&lt;?&gt;(Mu --&gt; Bool:D)</pre>
<p><a id="i352" name=""></a><span class="indexed">Boolean context operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Bool.pod6">Bool</a> by calling the <span class="code">Bool</span> method on it. Note that this collapses <a href="#_type_Junction.pod6">Junction</a>s.</p>
<a name="t32.18.2"></a> <h2 id="_language_operators.pod6-prefix_!">prefix <span class="code">!</span></h2>
<pre class="code">multi sub prefix:&lt;!&gt;(Mu --&gt; Bool:D)</pre>
<p><a id="i353" name=""></a><span class="indexed">Negated boolean context operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Bool.pod6">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="#_type_Junction.pod6">Junction</a>s.</p>
<a name="t32.18.3"></a> <h2 id="_language_operators.pod6-prefix_+">prefix <span class="code">+</span></h2>
<pre class="code">multi sub prefix:&lt;+&gt;(Any --&gt; Numeric:D)</pre>
<p><a id="i354" name=""></a><span class="indexed">Numeric context operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Numeric.pod6">Numeric</a> by calling the <span class="code">Numeric</span> method on it.</p>
<a name="t32.18.4"></a> <h2 id="_language_operators.pod6-prefix_-">prefix <span class="code">-</span></h2>
<pre class="code">multi sub prefix:&lt;-&gt;(Any --&gt; Numeric:D)</pre>
<p><a id="i355" name=""></a><span class="indexed">Negative numeric context operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Numeric.pod6">Numeric</a> by calling the <span class="code">Numeric</span> method on it, and then negates the result.</p>
<a name="t32.18.5"></a> <h2 id="_language_operators.pod6-prefix_~">prefix <span class="code">~</span></h2>
<pre class="code">multi sub prefix:&lt;~&gt;(Any --&gt; Str:D)</pre>
<p><a id="i356" name=""></a><span class="indexed">String context operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Str.pod6">Str</a> by calling the <a href="#_type_List.pod6-method_Str">Str</a> method on it.</p>
<a name="t32.18.6"></a> <h2 id="_language_operators.pod6-prefix_|">prefix <span class="code">|</span></h2>
<p>Flattens objects of type <a href="#_type_Capture.pod6">Capture</a>, <a href="#_type_Pair.pod6">Pair</a>, <a href="#_type_List.pod6">List</a>, <a href="#_type_Map.pod6">Map</a> and <a href="#_type_Hash.pod6">Hash</a> into an argument list.</p>
<p>Outside of argument lists, it returns a <a href="#_type_Slip.pod6">Slip</a>, which makes it flatten into the outer list. Inside <a href="#_language_list.pod6-Argument_List_(Capture)_Context">argument list</a> <a href="#_type_Positional.pod6"><span class="code">Positional</span> s</a> are turned into positional arguments and <a href="#_type_Associative.pod6"><span class="code">Associative</span> s</a> are turned into named arguments.</p>
<a name="t32.18.7"></a> <h2 id="_language_operators.pod6-prefix_||">prefix <span class="code">||</span></h2>
<p>TODO</p>
<a name="t32.18.8"></a> <h2 id="_language_operators.pod6-prefix_+^">prefix <span class="code">+^</span></h2>
<pre class="code">multi sub prefix:&lt;+^&gt;(Any --&gt; Int:D)</pre>
<p><a id="i357" name=""></a><span class="indexed">Integer bitwise negation operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Int.pod6">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="t32.18.9"></a> <h2 id="_language_operators.pod6-prefix_~^">prefix <span class="code">~^</span></h2>
<p>Coerces the argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then flips each bit in that buffer.</p>
<p>Please note that this has not yet been implemented.</p>
<a name="t32.18.10"></a> <h2 id="_language_operators.pod6-prefix_?^">prefix <span class="code">?^</span></h2>
<pre class="code">multi sub prefix:&lt;?^&gt;(Mu --&gt; Bool:D)</pre>
<p><a id="i358" name=""></a><span class="indexed">Boolean bitwise negation operator</span>.</p>
<p>Coerces the argument to <a href="#_type_Bool.pod6">Bool</a> and then does a bit flip, which makes it the same as <span class="code">prefix:&lt;!&gt; </span>.</p>
<a name="t32.18.11"></a> <h2 id="_language_operators.pod6-prefix_^">prefix <span class="code">^</span></h2>
<pre class="code">multi sub prefix:&lt;^&gt;(Any --&gt; Range:D)</pre>
<p><i>upto</i> operator.<a id="i359" name="upto operator"></a><span class="indexed"></span></p>
<p>Coerces the argument to <a href="#_type_Numeric.pod6">Numeric</a>, and generates a range from 0 up to (but excluding) the argument.</p>
<pre class="code">say ^5; # OUTPUT: «0..^5␤»
for ^5 { } # 5 iterations</pre>
<a name="t32.19"></a> <h1 id="_language_operators.pod6-Dotty_Infix_Precedence">Dotty Infix Precedence</h1>
<p>These operators are like their Method Postfix counterparts, but require surrounding whitespace (before and/or after) to distinguish them.</p>
<a name="t32.19.1"></a> <h2 id="_language_operators.pod6-infix_.=">infix <span class="code">.=</span></h2>
<p>Calls the right-side method on the value in the left-side container, replacing the resulting value in the left-side container.</p>
<p>In most cases this behaves identically to the postfix mutator, but the precedence is lower so:</p>
<pre class="code"> my $a = -5
say ++$a.=abs
# OUTPUT: «6␤»
say ++$a .= abs
# OUTPUT: «Cannot modify an immutable Int␤
# in block &lt;unit&gt; at &lt;tmp&gt; line 1␤␤»
</pre>
<a name="t32.19.2"></a> <h2 id="_language_operators.pod6-infix_.">infix <span class="code">.</span></h2>
<p>Calls the following method (whose name must be alphabetic) on the left-side invocant.</p>
<p>Note that the infix form of the operator has a slightly lower precedence than postfix <span class="code">.meth</span>.</p>
<pre class="code">say -5.abs; # like: -(5.abs)
# OUTPUT: «-5␤»
say -5 . abs; # like: (-5) . abs
# OUTPUT: «5␤»
say -5 .abs; # following whitespace is optional
# OUTPUT: «5␤»</pre>
<a name="t32.20"></a> <h1 id="_language_operators.pod6-Multiplicative_Precedence">Multiplicative Precedence</h1>
<a name="t32.20.1"></a> <h2 id="_language_operators.pod6-infix_*">infix <span class="code">*</span></h2>
<pre class="code">multi sub infix:&lt;*&gt;(Any, Any --&gt; Numeric:D)</pre>
<p><a id="i360" name=""></a><span class="indexed">Multiplication operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Numeric.pod6">Numeric</a> and multiplies them. The result is of the wider type. See <a href="#_type_Numeric.pod6">Numeric</a> for details.</p>
<a name="t32.20.2"></a> <h2 id="_language_operators.pod6-infix_/">infix <span class="code">/</span></h2>
<pre class="code">multi sub infix:&lt;/&gt;(Any, Any --&gt; Numeric:D)</pre>
<p><a id="i361" name=""></a><span class="indexed">Division operator</span>.</p>
<p>Coerces both argument to <a href="#_type_Numeric.pod6">Numeric</a> and divides the left through the right number. Division of <a href="#_type_Int.pod6">Int</a> values returns <a href="#_type_Rat.pod6">Rat</a>, otherwise the &quot;wider type&quot; rule described in <a href="#_type_Numeric.pod6">Numeric</a> holds.</p>
<a name="t32.20.3"></a> <h2 id="_language_operators.pod6-infix_div">infix <span class="code">div</span></h2>
<pre class="code">multi sub infix:&lt;div&gt;(Int:D, Int:D --&gt; Int:D)</pre>
<p><a id="i362" name=""></a><span class="indexed">Integer division operator</span>. Rounds down.</p>
<a name="t32.20.4"></a> <h2 id="_language_operators.pod6-infix_%">infix <span class="code">%</span></h2>
<pre class="code">multi sub infix:&lt;%&gt;($x, $y --&gt; Numeric:D)</pre>
<p><a id="i363" name=""></a><span class="indexed">Modulo operator</span>. Coerces to <a href="#_type_Numeric.pod6">Numeric</a> first.</p>
<p>Generally the following identity holds:</p>
<pre class="code">my ($x, $y) = 1,2;
$x % $y == $x - floor($x / $y) * $y</pre>
<a name="t32.20.5"></a> <h2 id="_language_operators.pod6-infix_%%">infix <span class="code">%%</span></h2>
<pre class="code">multi sub infix:&lt;%%&gt;($a, $b --&gt; Bool:D)</pre>
<p><a id="i364" name=""></a><span class="indexed">Divisibility operator</span>. Returns <span class="code">True</span> if <span class="code">$a % $b == 0</span>.</p>
<a name="t32.20.6"></a> <h2 id="_language_operators.pod6-infix_mod">infix <span class="code">mod</span></h2>
<pre class="code">multi sub infix:&lt;mod&gt;(Int:D $a, Int:D $b --&gt; Int:D)</pre>
<p><a id="i365" name=""></a><span class="indexed">Integer modulo operator</span>. Returns the remainder of an integer modulo operation.</p>
<a name="t32.20.7"></a> <h2 id="_language_operators.pod6-infix_+&amp;">infix <span class="code">+&amp;</span></h2>
<pre class="code">multi sub infix:&lt;+&amp;&gt;($a, $b --&gt; Int:D)</pre>
<p>Numeric bitwise <i>AND</i> operator. Coerces both arguments to <a href="#_type_Int.pod6">Int</a> and does a bitwise <i>AND</i> operation assuming two's complement.<a id="i366" name="Numeric bitwise AND operator"></a><span class="indexed"></span></p>
<a name="t32.20.8"></a> <h2 id="_language_operators.pod6-infix_+&lt;">infix <span class="code">+&lt;</span></h2>
<pre class="code">multi sub infix:&lt;&lt; +&lt; &gt;&gt;($a, $b --&gt; Int:D)</pre>
<p>Integer bit shift to the left.<a id="i367" name="integer bit shift operator left"></a><span class="indexed"></span></p>
<a name="t32.20.9"></a> <h2 id="_language_operators.pod6-infix_+&gt;">infix <span class="code">+&gt;</span></h2>
<pre class="code">multi sub infix:&lt;&lt; +&gt; &gt;&gt;($a, $b --&gt; Int:D)</pre>
<p>Integer bit shift to the right.<a id="i368" name="integer bit shift operator right"></a><span class="indexed"></span></p>
<a name="t32.20.10"></a> <h2 id="_language_operators.pod6-infix_~&amp;">infix <span class="code">~&amp;</span></h2>
<p>Coerces each argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then performs a numeric bitwise AND on corresponding integers of the two buffers, padding the shorter buffer with zeroes.</p>
<a name="t32.20.11"></a> <h2 id="_language_operators.pod6-infix_~&lt;">infix <span class="code">~&lt;</span></h2>
<p>Coerces the left argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then performs a numeric bitwise left shift on the bits of the buffer.</p>
<p>Please note that this has not yet been implemented.</p>
<a name="t32.20.12"></a> <h2 id="_language_operators.pod6-infix_~&gt;">infix <span class="code">~&gt;</span></h2>
<p>Coerces the left argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then performs a numeric bitwise right shift on the bits of the buffer.</p>
<p>Please note that this has not yet been implemented.</p>
<a name="t32.20.13"></a> <h2 id="_language_operators.pod6-infix_gcd">infix <span class="code">gcd</span></h2>
<pre class="code">multi sub infix:&lt;gcd&gt;($a, $b --&gt; Int:D)</pre>
<p>Coerces both arguments to <a href="#_type_Int.pod6">Int</a> and returns the greatest common divisor.<a id="i369" name="greatest common divisor operator"></a><span class="indexed"></span></p>
<a name="t32.20.14"></a> <h2 id="_language_operators.pod6-infix_lcm">infix <span class="code">lcm</span></h2>
<pre class="code">multi sub infix:&lt;lcm&gt;($a, $b --&gt; Int:D)</pre>
<p>Coerces both arguments to <a href="#_type_Int.pod6">Int</a> and returns the least common multiple, that is the smallest integer that is evenly divisible by both arguments.<a id="i370" name="least common multiple operator"></a><span class="indexed"></span></p>
<a name="t32.21"></a> <h1 id="_language_operators.pod6-Additive_Precedence">Additive Precedence</h1>
<a name="t32.21.1"></a> <h2 id="_language_operators.pod6-infix_+">infix <span class="code">+</span></h2>
<pre class="code">multi sub infix:&lt;+&gt;($a, $b --&gt; Numeric:D)</pre>
<p><a id="i371" name=""></a><span class="indexed">Addition operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Numeric.pod6">Numeric</a> and adds them.</p>
<a name="t32.21.2"></a> <h2 id="_language_operators.pod6-infix_-">infix <span class="code">-</span></h2>
<pre class="code">multi sub infix:&lt;-&gt;($a, $b --&gt; Numeric:D)</pre>
<p><a id="i372" name=""></a><span class="indexed">Subtraction operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Numeric.pod6">Numeric</a> and subtracts the second from the first.</p>
<a name="t32.21.3"></a> <h2 id="_language_operators.pod6-infix_+|">infix <span class="code">+|</span></h2>
<pre class="code">multi sub infix:&lt;+|&gt;($a, $b --&gt; Int:D)</pre>
<p><a id="i373" name=""></a><span class="indexed">Integer bitwise OR operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Int.pod6">Int</a> and does a bitwise <i>OR</i> (inclusive OR) operation.</p>
<a name="t32.21.4"></a> <h2 id="_language_operators.pod6-infix_+^">infix <span class="code">+^</span></h2>
<pre class="code">multi sub infix:&lt;+^&gt;($a, $b --&gt; Int:D)</pre>
<p><a id="i374" name=""></a><span class="indexed">Integer bitwise XOR operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Int.pod6">Int</a> and does a bitwise <i>XOR</i> (exclusive OR) operation.</p>
<a name="t32.21.5"></a> <h2 id="_language_operators.pod6-infix_~|">infix <span class="code">~|</span></h2>
<p>Coerces each argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then performs a numeric bitwise OR on corresponding integers of the two buffers, padding the shorter buffer with zeroes.</p>
<a name="t32.21.6"></a> <h2 id="_language_operators.pod6-infix_~^">infix <span class="code">~^</span></h2>
<p>Coerces each argument to a non-variable-encoding string buffer type (e.g. <span class="code">buf8</span>, <span class="code">buf16</span>, <span class="code">buf32</span>) and then performs a numeric bitwise XOR on corresponding integers of the two buffers, padding the shorter buffer with zeroes.</p>
<a name="t32.21.7"></a> <h2 id="_language_operators.pod6-infix_?|">infix <span class="code">?|</span></h2>
<pre class="code">multi sub infix:&lt;?|&gt;($a, $b --&gt; Bool:D)</pre>
<p><a id="i375" name=""></a><span class="indexed">Boolean logical OR operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Bool.pod6">Bool</a> and does a logical <i>OR</i> (inclusive OR) operation.</p>
<a name="t32.22"></a> <h1 id="_language_operators.pod6-Replication_Precedence">Replication Precedence</h1>
<a name="t32.22.1"></a> <h2 id="_language_operators.pod6-infix_x">infix <span class="code">x</span></h2>
<pre class="code">sub infix:&lt;x&gt;($a, $b --&gt; Str:D)</pre>
<p><a id="i376" name=""></a><span class="indexed">String repetition operator</span>.</p>
<p>Repeats the string <span class="code">$a</span> <span class="code">$b</span> times, if necessary coercing <span class="code">$a</span> to <a href="#_type_Str.pod6"><span class="code">Str</span></a> and <span class="code">$b</span> <a href="#_type_Int.pod6"><span class="code">Int</span></a>. Returns an empty string if <span class="code">$b &lt;= 0 </span>.</p>
<pre class="code">say 'ab' x 3; # OUTPUT: «ababab␤»
say 42 x 3; # OUTPUT: «424242␤»
my $a = 'a'.IO;
my $b = 3.5;
say $a x $b; # OUTPUT: «aaa␤»</pre>
<a name="t32.22.2"></a> <h2 id="_language_operators.pod6-infix_xx">infix <span class="code">xx</span></h2>
<pre class="code">multi sub infix:&lt;xx&gt;($a, $b --&gt; List:D)</pre>
<p><a id="i377" name=""></a><span class="indexed">List repetition operator</span>.</p>
<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="#_type_Int.pod6">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">say [1, 2] xx 5;
# OUTPUT: «([1 2] [1 2] [1 2] [1 2] [1 2])␤»</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="t32.23"></a> <h1 id="_language_operators.pod6-Concatenation">Concatenation</h1>
<a name="t32.23.1"></a> <h2 id="_language_operators.pod6-infix_~">infix <span class="code">~</span></h2>
<pre class="code">multi sub infix:&lt;~&gt;(Any, Any)
multi sub infix:&lt;~&gt;(Str:D, Str:D)
multi sub infix:&lt;~&gt;(Buf:D, Buf:D)</pre>
<p><a id="i378" name=""></a><span class="indexed">String concatenation operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">Str</a> and concatenates them. If both arguments are <a href="#_type_Buf.pod6">Buf</a>, a combined buffer is returned.</p>
<pre class="code">say 'ab' ~ 'c'; # OUTPUT: «abc␤»</pre>
<a name="t32.23.2"></a> <h2 id="_language_operators.pod6-infix_∘">infix <span class="code">∘</span></h2>
<pre class="code">multi sub infix:&lt;∘&gt;()
multi sub infix:&lt;∘&gt;(&amp;f)
multi sub infix:&lt;∘&gt;(&amp;f, &amp;g --&gt; Block:D)</pre>
<p><a id="i379" name=""></a><span class="indexed">Function combinator operator</span></p>
<p>The function composition operator <span class="code">infix:&lt;∘&gt;</span> or <span class="code">infix:&lt;o&gt;</span> combines two functions, so that the left function is called with the return value of the right function. If the <a href="#_routine_count.pod6"><span class="code">.count</span></a> of the left function is greater than 1, the return value of the right function will be <a href="#_type_Slip.pod6">slipped</a> into the left function.</p>
<p>Both <span class="code">.count</span> and <span class="code">.arity</span> of the RHS will be maintained.</p>
<pre class="code">sub f($p){ say 'f'; $p / 2 }
sub g($p){ say 'g'; $p * 2 }
my &amp;composed = &amp;f ∘ &amp;g;
say composed 2; # OUTPUT: «g␤f␤2␤»
# equivalent to:
say 2.&amp;g.&amp;f;
# or to:
say f g 2;</pre>
<pre class="code">sub f($a, $b, $c) { [~] $c, $b, $a }
sub g($str){ $str.comb }
my &amp;composed = &amp;f ∘ &amp;g;
say composed 'abc'; # OUTPUT: «cba␤»
# equivalent to:
say f |g 'abc';
</pre>
<a name="t32.24"></a> <h1 id="_language_operators.pod6-Junctive_AND_(all)_Precedence">Junctive AND (all) Precedence</h1>
<a name="t32.24.1"></a> <h2 id="_language_operators.pod6-infix_&amp;">infix <span class="code">&amp;</span></h2>
<pre class="code">multi sub infix:&lt;&amp;&gt;($a, $b --&gt; Junction:D) is assoc&lt;list&gt;</pre>
<p><a id="i380" name=""></a><span class="indexed">All junction operator</span>.</p>
<p>Creates an <i>all</i> <a href="#_type_Junction.pod6">Junction</a> from its arguments. See <a href="#_type_Junction.pod6">Junction</a> for more details.</p>
<a name="t32.25"></a> <h1 id="_language_operators.pod6-Junctive_OR_(any)_Precedence">Junctive OR (any) Precedence</h1>
<a name="t32.25.1"></a> <h2 id="_language_operators.pod6-infix_|">infix <span class="code">|</span></h2>
<pre class="code">multi sub infix:&lt;|&gt;($a, $b --&gt; Junction:D) is assoc&lt;list&gt;</pre>
<p><a id="i381" name=""></a><span class="indexed">Any junction operator</span>.</p>
<p>Creates an <i>any</i> <a href="#_type_Junction.pod6">Junction</a> from its arguments. See <a href="#_type_Junction.pod6">Junction</a> for more details.</p>
<a name="t32.25.2"></a> <h2 id="_language_operators.pod6-infix_^">infix <span class="code">^</span></h2>
<pre class="code">multi sub infix:&lt;^&gt;($a, $b --&gt; Junction:D) is assoc&lt;list&gt;</pre>
<p><a id="i382" name=""></a><span class="indexed">One junction operator</span>.</p>
<p>Creates a <i>one</i> <a href="#_type_Junction.pod6">Junction</a> from its arguments. See <a href="#_type_Junction.pod6">Junction</a> for more details.</p>
<a name="t32.26"></a> <h1 id="_language_operators.pod6-Named_Unary_Precedence">Named Unary Precedence</h1>
<a name="t32.26.1"></a> <h2 id="_language_operators.pod6-prefix_temp">prefix <span class="code">temp</span></h2>
<pre class="code">sub prefix:&lt;temp&gt;(Mu $a is rw)</pre>
<p>&quot;temporizes&quot; the variable passed as the argument. The variable begins with the same value as it had in the outer scope, but can be assigned new values in this scope. Upon exiting the scope, the variable will be restored to its original value.</p>
<pre class="code">my $a = &quot;three&quot;;
say $a; # OUTPUT: «three␤»
{
temp $a;
say $a; # OUTPUT: «three␤»
$a = &quot;four&quot;;
say $a; # OUTPUT: «four␤»
}
say $a; # OUTPUT: «three␤»</pre>
<p>You can also assign immediately as part of the call to temp:</p>
<pre class="code">temp $a = &quot;five&quot;;
</pre>
<p>Be warned the <span class="code">temp</span> effects get removed once the block is left. If you were to access the value from, say, within a <a href="#_type_Promise.pod6">Promise</a> after the <span class="code">temp</span> was undone, you'd get the original value, not the <span class="code">temp</span> one:</p>
<pre class="code">my $v = &quot;original&quot;;
{
temp $v = &quot;new one&quot;;
start {
say &quot;[PROMISE] Value before block is left: `$v`&quot;;
sleep 1;
say &quot;[PROMISE] Block was left while we slept; value is now `$v`&quot;;
}
sleep ½;
say &quot;About to leave the block; value is `$v`&quot;;
}
say &quot;Left the block; value is now `$v`&quot;;
sleep 2;
# OUTPUT:
# [PROMISE] Value before block is left: `new one`
# About to leave the block; value is `new one`
# Left the block; value is now `original`
# [PROMISE] Block was left while we slept; value is now `original`
</pre>
<a name="t32.26.2"></a> <h2 id="_language_operators.pod6-prefix_let">prefix <span class="code">let</span></h2>
<pre class="code">sub prefix:&lt;let&gt;(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 &quot;it's been reset :(&quot; }
}
say &quot;we made it 84 sticks!&quot;;
}
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="t32.27"></a> <h1 id="_language_operators.pod6-Nonchaining_Binary_Precedence">Nonchaining Binary Precedence</h1>
<a name="t32.27.1"></a> <h2 id="_language_operators.pod6-infix_does">infix <span class="code">does</span></h2>
<pre class="code">sub infix:&lt;does&gt;(Mu $obj, Mu $role) is assoc&lt;non&gt;</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>Similar to <a href="#_routine_but.pod6">but</a> operator, the <span class="code">$role</span> can instead be an instantiated object, in which case, the operator will create a role for you automatically. The role will contain a single method named the same as <span class="code">$obj.^name</span> and that returns <span class="code">$obj</span>:</p>
<pre class="code">my $o = class { method Str { &quot;original&quot; } }.new;
put $o; # OUTPUT: «original␤»
$o does &quot;modded&quot;;
put $o; # OUTPUT: «modded␤»</pre>
<p>If methods of the same name are present already, the last mixed in role takes precedence.</p>
<a name="t32.27.2"></a> <h2 id="_language_operators.pod6-infix_but">infix <span class="code">but</span></h2>
<pre class="code">multi sub infix:&lt;but&gt;(Mu $obj1, Mu $role) is assoc&lt;non&gt;
multi sub infix:&lt;but&gt;(Mu $obj1, Mu:D $obj2) is assoc&lt;non&gt;</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>Instead of a role, you can provide an instantiated object. In this case, the operator will create a role for you automatically. The role will contain a single method named the same as <span class="code">$obj.^name</span> and that returns <span class="code">$obj</span>:</p>
<pre class="code">say 42 but 'forty two'; # OUTPUT: «forty two␤»
my $s = 12 but class Warbles { method hi { 'hello' } }.new;
say $s.Warbles.hi; # OUTPUT: «hello␤»
say $s + 42; # OUTPUT: «54␤»
</pre>
<p>If methods of the same name are present already, the last mixed in role takes precedence. A list of methods can be provided in parentheses separated by comma. In this case conflicts will be reported at runtime.</p>
<a name="t32.27.3"></a> <h2 id="_language_operators.pod6-infix_cmp">infix <span class="code">cmp</span></h2>
<pre class="code">multi sub infix:&lt;cmp&gt;(Any, Any)
multi sub infix:&lt;cmp&gt;(Real:D, Real:D)
multi sub infix:&lt;cmp&gt;(Str:D, Str:D)
multi sub infix:&lt;cmp&gt;(Version:D, Version:D)</pre>
<p><a id="i383" name=""></a><span class="indexed">Generic, &quot;smart&quot; three-way comparator</span>.</p>
<p>Compares strings with string semantics, numbers with number semantics, <a href="#_type_Pair.pod6">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 =&gt; 3) cmp (a =&gt; 4); # OUTPUT: «Less␤»
say 4 cmp 4.0; # OUTPUT: «Same␤»
say 'b' cmp 'a'; # OUTPUT: «More␤»</pre>
<a name="t32.27.4"></a> <h2 id="_language_operators.pod6-infix_leg">infix <span class="code">leg</span></h2>
<pre class="code">multi sub infix:&lt;leg&gt;(Any, Any)
multi sub infix:&lt;leg&gt;(Str:D, Str:D)</pre>
<p><a id="i384" name=""></a><span class="indexed">String three-way comparator</span>. Short for <i>less, equal or greater?</i>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">Str</a>, and then does a lexicographic comparison.</p>
<pre class="code">say 'a' leg 'b'; # OUTPUT: «Less␤»
say 'a' leg 'a'; # OUTPUT: «Same␤»
say 'b' leg 'a'; # OUTPUT: «More␤»</pre>
<a name="t32.27.5"></a> <h2 id="_language_operators.pod6-infix_&lt;=&gt;">infix <span class="code">&lt;=&gt;</span></h2>
<pre class="code">multi sub infix:«&lt;=&gt;»($a, $b --&gt; Order:D) is assoc&lt;non&gt;</pre>
<p><a id="i385" name=""></a><span class="indexed">Numeric three-way comparator</span>.<a id="i386" name="spaceship operator"></a><span class="indexed"></span></p>
<p>Coerces both arguments to <a href="#_type_Real.pod6">Real</a>, and then does a numeric comparison.</p>
<a name="t32.27.6"></a> <h2 id="_language_operators.pod6-infix_..">infix <span class="code">..</span></h2>
<pre class="code">multi sub infix:&lt;..&gt;($a, $b --&gt; Range:D) is assoc&lt;non&gt;</pre>
<p><a id="i387" name=""></a><span class="indexed">Range operator</span></p>
<p>Constructs a <a href="#_type_Range.pod6">Range</a> from the arguments.</p>
<a name="t32.27.7"></a> <h2 id="_language_operators.pod6-infix_..^">infix <span class="code">..^</span></h2>
<pre class="code">multi sub infix:&lt;..^&gt;($a, $b --&gt; Range:D) is assoc&lt;non&gt;</pre>
<p><a id="i388" name=""></a><span class="indexed">Right-open range operator</span>.</p>
<p>Constructs a <a href="#_type_Range.pod6">Range</a> from the arguments, excluding the end point.</p>
<a name="t32.27.8"></a> <h2 id="_language_operators.pod6-infix_^..">infix <span class="code">^..</span></h2>
<pre class="code">multi sub infix:&lt;^..&gt;($a, $b --&gt; Range:D) is assoc&lt;non&gt;</pre>
<p><a id="i389" name=""></a><span class="indexed">Left-open range operator</span>.</p>
<p>Constructs a <a href="#_type_Range.pod6">Range</a> from the arguments, excluding the start point.</p>
<a name="t32.27.9"></a> <h2 id="_language_operators.pod6-infix_^..^">infix <span class="code">^..^</span></h2>
<pre class="code">multi sub infix:&lt;^..^&gt;($a, $b --&gt; Range:D) is assoc&lt;non&gt;</pre>
<p><a id="i390" name=""></a><span class="indexed">Open range operator</span></p>
<p>Constructs a <a href="#_type_Range.pod6">Range</a> from the arguments, excluding both start and end point.</p>
<a name="t32.28"></a> <h1 id="_language_operators.pod6-Chaining_Binary_Precedence">Chaining Binary Precedence</h1>
<a name="t32.28.1"></a> <h2 id="_language_operators.pod6-infix_==">infix <span class="code">==</span></h2>
<pre class="code">multi sub infix:&lt;==&gt;(Any, Any)
multi sub infix:&lt;==&gt;(Int:D, Int:D)
multi sub infix:&lt;==&gt;(Num:D, Num:D)
multi sub infix:&lt;==&gt;(Rational:D, Rational:D)
multi sub infix:&lt;==&gt;(Real:D, Real:D)
multi sub infix:&lt;==&gt;(Complex:D, Complex:D)
multi sub infix:&lt;==&gt;(Numeric:D, Numeric:D)</pre>
<p><a id="i391" name=""></a><span class="indexed">Numeric equality operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Numeric.pod6">Numeric</a> if necessary, and returns <span class="code">True</span> if they are equal.</p>
<a name="t32.28.2"></a> <h2 id="_language_operators.pod6-infix_!=">infix <span class="code">!=</span></h2>
<pre class="code">sub infix:&lt;!=&gt;(Mu, Mu --&gt; Bool:D)</pre>
<p><a id="i392" name=""></a><span class="indexed">Numeric inequality operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Numeric.pod6">Numeric</a> (if necessary), and returns <span class="code">True</span> if they are distinct.</p>
<p>Is an alias to <span class="code">!==</span>.</p>
<a name="t32.28.3"></a> <h2 id="_language_operators.pod6-infix_≠">infix <span class="code">≠</span></h2>
<p>Numeric inequality operator.</p>
<p>Equivalent to <a href="!=">!=</a>, at codepoint U+2260 (NOT EQUAL TO).</p>
<a name="t32.28.4"></a> <h2 id="_language_operators.pod6-infix_&lt;">infix <span class="code">&lt;</span></h2>
<pre class="code">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><a id="i393" name=""></a><span class="indexed">Numeric less than operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Real.pod6">Real</a> (if necessary), and returns <span class="code">True</span> if the first argument is smaller than the second.</p>
<a name="t32.28.5"></a> <h2 id="_language_operators.pod6-infix_&lt;=">infix <span class="code">&lt;=</span></h2>
<pre class="code">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><a id="i394" name=""></a><span class="indexed">Numeric less than or equal to operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Real.pod6">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="t32.28.6"></a> <h2 id="_language_operators.pod6-infix_≤">infix <span class="code">≤</span></h2>
<p>Numeric less than or equal to operator.</p>
<p>Equivalent to <a href="&amp;lt;=">&lt;=</a>, at codepoint U+2264 (LESS-THAN OR EQUAL TO).</p>
<a name="t32.28.7"></a> <h2 id="_language_operators.pod6-infix_&gt;">infix <span class="code">&gt;</span></h2>
<pre class="code">multi sub infix:«&gt;»(Int:D, Int:D)
multi sub infix:«&gt;»(Num:D, Num:D)
multi sub infix:«&gt;»(Real:D, Real:D)</pre>
<p><a id="i395" name=""></a><span class="indexed">Numeric greater than operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Real.pod6">Real</a> (if necessary), and returns <span class="code">True</span> if the first argument is larger than the second.</p>
<a name="t32.28.8"></a> <h2 id="_language_operators.pod6-infix_&gt;=">infix <span class="code">&gt;=</span></h2>
<pre class="code">multi sub infix:«&gt;=»(Int:D, Int:D)
multi sub infix:«&gt;=»(Num:D, Num:D)
multi sub infix:«&gt;=»(Real:D, Real:D)</pre>
<p><a id="i396" name=""></a><span class="indexed">Numeric greater than or equal to operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Real.pod6">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="t32.28.9"></a> <h2 id="_language_operators.pod6-infix_≥">infix <span class="code">≥</span></h2>
<p>Numeric greater than or equal to operator.</p>
<p>Equivalent to <a href="&amp;gt;=">&gt;=</a>, at codepoint U+2265 (GREATER-THAN OR EQUAL TO).</p>
<a name="t32.28.10"></a> <h2 id="_language_operators.pod6-infix_eq">infix <span class="code">eq</span></h2>
<pre class="code">multi sub infix:&lt;eq&gt;(Any, Any)
multi sub infix:&lt;eq&gt;(Str:D, Str:D)</pre>
<p><a id="i397" name=""></a><span class="indexed">String equality operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">Str</a> (if necessary), and returns <span class="code">True</span> if both are equal.</p>
<p>Mnemonic: <i>equal</i></p>
<a name="t32.28.11"></a> <h2 id="_language_operators.pod6-infix_ne">infix <span class="code">ne</span></h2>
<pre class="code">multi sub infix:&lt;ne&gt;(Mu, Mu)
multi sub infix:&lt;ne&gt;(Str:D, Str:D)</pre>
<p><a id="i398" name=""></a><span class="indexed">String inequality operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">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="t32.28.12"></a> <h2 id="_language_operators.pod6-infix_gt">infix <span class="code">gt</span></h2>
<pre class="code">multi sub infix:&lt;gt&gt;(Mu, Mu)
multi sub infix:&lt;gt&gt;(Str:D, Str:D)</pre>
<p><a id="i399" name=""></a><span class="indexed">String greater than operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">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="t32.28.13"></a> <h2 id="_language_operators.pod6-infix_ge">infix <span class="code">ge</span></h2>
<pre class="code">multi sub infix:&lt;ge&gt;(Mu, Mu)
multi sub infix:&lt;ge&gt;(Str:D, Str:D)</pre>
<p><a id="i400" name=""></a><span class="indexed">String greater than or equal to operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">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="t32.28.14"></a> <h2 id="_language_operators.pod6-infix_lt">infix <span class="code">lt</span></h2>
<pre class="code">multi sub infix:&lt;lt&gt;(Mu, Mu)
multi sub infix:&lt;lt&gt;(Str:D, Str:D)</pre>
<p><a id="i401" name=""></a><span class="indexed">String less than operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">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="t32.28.15"></a> <h2 id="_language_operators.pod6-infix_le">infix <span class="code">le</span></h2>
<pre class="code">multi sub infix:&lt;le&gt;(Mu, Mu)
multi sub infix:&lt;le&gt;(Str:D, Str:D)</pre>
<p><a id="i402" name=""></a><span class="indexed">String less than or equal to operator</span>.</p>
<p>Coerces both arguments to <a href="#_type_Str.pod6">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="t32.28.16"></a> <h2 id="_language_operators.pod6-infix_before">infix <span class="code">before</span></h2>
<pre class="code">multi sub infix:&lt;before&gt;(Any, Any)
multi sub infix:&lt;before&gt;(Real:D, Real:D)
multi sub infix:&lt;before&gt;(Str:D, Str:D)
multi sub infix:&lt;before&gt;(Version:D, Version:D)</pre>
<p>Generic ordering, uses the same semantics as <a href="#31-infix cmp">cmp</a>. Returns <span class="code">True</span> if the first argument is smaller than the second.</p>
<a name="t32.28.17"></a> <h2 id="_language_operators.pod6-infix_after">infix <span class="code">after</span></h2>
<pre class="code">multi sub infix:&lt;after&gt;(Any, Any)
multi sub infix:&lt;after&gt;(Real:D, Real:D)
multi sub infix:&lt;after&gt;(Str:D, Str:D)
multi sub infix:&lt;after&gt;(Version:D, Version:D)</pre>
<p>Generic ordering, uses the same semantics as <a href="#31-infix cmp">cmp</a>. Returns <span class="code">True</span> if the first argument is larger than the second.</p>
<a name="t32.28.18"></a> <h2 id="_language_operators.pod6-infix_eqv">infix <span class="code">eqv</span></h2>
<pre class="code">sub infix:&lt;eqv&gt;(Any, Any)</pre>
<p><a id="i403" name=""></a><span class="indexed">Equivalence operator</span>. Returns <span class="code">True</span> if the two arguments are structurally the same, i.e. from the same type and (recursively) contain equivalent values.</p>
<pre class="code">say [1, 2, 3] eqv [1, 2, 3]; # OUTPUT: «True␤»
say Any eqv Any; # OUTPUT: «True␤»
say 1 eqv 2; # OUTPUT: «False␤»
say 1 eqv 1.0; # OUTPUT: «False␤»</pre>
<p>Lazy <a href="#_type_Iterable.pod6"><span class="code">Iterables</span></a> cannot be compared, as they're assumed to be infinite. However, the operator will do its best and return <span class="code">False</span> if the two lazy <span class="code">Iterables</span> are of different types or if only one <span class="code">Iterable</span> is lazy.</p>
<pre class="code">say (1…∞) eqv (1…∞).List; # Both lazy, but different types; OUTPUT: «False␤»
say (1…∞) eqv (1…3); # Same types, but only one is lazy; OUTPUT: «False␤»
(try say (1…∞) eqv (1…∞)) # Both lazy and of the same type. Cannot compare; throws.
orelse say $!.^name; # OUTPUT: «X::Cannot::Lazy␤»</pre>
<p>The default <span class="code">eqv</span> operator even works with arbitrary objects. E.g., <span class="code">eqv</span> will consider two instances of the same object as being structurally equivalent:</p>
<pre class="code">my class A {
has $.a;
}
say A.new(a =&gt; 5) eqv A.new(a =&gt; 5); # OUTPUT: «True␤»</pre>
<p>Although the above example works as intended the <span class="code">eqv</span> code might fall back to a slower code path in order to do its job. One way to avoid this is to implement an appropriate infix <span class="code">eqv</span> operator:</p>
<pre class="code">my class A {
has $.a;
}
multi infix:&lt;eqv&gt;(A $l, A $r) { $l.a eqv $r.a }
say A.new(a =&gt; 5) eqv A.new(a =&gt; 5); # OUTPUT: «True␤»</pre>
<a name="t32.28.19"></a> <h2 id="_language_operators.pod6-infix_===">infix <span class="code">===</span></h2>
<pre class="code">sub infix:&lt;===&gt;(Any, Any)</pre>
<p><a id="i404" name=""></a><span class="indexed">Value identity operator</span>. Returns <span class="code">True</span> if both arguments are the same object.</p>
<pre class="code">my class A { };
my $a = A.new;
say $a === $a; # OUTPUT: «True␤»
say A.new === A.new; # OUTPUT: «False␤»
say A === A; # OUTPUT: «True␤»</pre>
<p>For value types, <span class="code">===</span> behaves like <span class="code">eqv</span>:</p>
<pre class="code">say 'a' === 'a'; # OUTPUT: «True␤»
say 'a' === 'b'; # OUTPUT: «False␤»
# different types
say 1 === 1.0; # OUTPUT: «False␤»</pre>
<p><span class="code">===</span> uses the <a href="#_routine_WHICH.pod6">WHICH</a> method to obtain the object identity, so all value types must override method <span class="code">WHICH</span>.</p>
<a name="t32.28.20"></a> <h2 id="_language_operators.pod6-infix_=:=">infix <span class="code">=:=</span></h2>
<pre class="code">multi sub infix:&lt;=:=&gt;(Mu \a, Mu \b)</pre>
<p><a id="i405" name=""></a><span class="indexed">Container identity operator</span>. Returns <span class="code">True</span> 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; # OUTPUT: «False␤»
$b = 2;
say $a; # OUTPUT: «1␤»
$b := $a;
say $a =:= $b; # OUTPUT: «True␤»
$a = 5;
say $b; # OUTPUT: «5␤»</pre>
<a name="t32.28.21"></a> <h2 id="_language_operators.pod6-infix_~~">infix <span class="code">~~</span></h2>
<p><a id="i406" name="smartmatch operator"></a><span class="indexed"></span> The <a id="i407" name=""></a><span class="indexed">smart-match operator</span>. 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 a partial list of some of the built-in smart-matching functionality. For full details, see <a href="#_routine_ACCEPTS.pod6">ACCEPTS</a> documentation for the type on the right-hand side of the operator.</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>Set/Bag</td> <td>equal element values</td></tr>
<tr><td>Any:D</td> <td>object identity</td></tr>
</table> <a name="t32.28.22"></a> <h2 id="_language_operators.pod6-infix_=~=">infix <span class="code">=~=</span></h2>
<pre class="code">multi sub infix:&lt;=~=&gt;(Any, Any)
multi sub infix:&lt;=~=&gt;(Int:D, Int:D)
multi sub infix:&lt;=~=&gt;(Num:D, Num:D)
multi sub infix:&lt;=~=&gt;(Rational:D, Rational:D)
multi sub infix:&lt;=~=&gt;(Real:D, Real:D)
multi sub infix:&lt;=~=&gt;(Complex:D, Complex:D)
multi sub infix:&lt;=~=&gt;(Numeric:D, Numeric:D)</pre>
<p>The approximately-equal operator <a id="i408" name="infix ≅"></a><span class="indexed"><span class="code">≅</span></span>, whose ASCII variant is <span class="code">=~=</span>. Calculates the relative difference between the left-hand and right-hand sides and returns <span class="code">True</span> if the difference is less than $*TOLERANCE (which defaults to 1e-15). However, if either side is zero then it checks that the absolute difference between the sides is less than $*TOLERANCE. Note that this operator is not arithmetically symmetrical (doesn't do ± Δ):</p>
<pre class="code">my $x = 1;
say ($x + $*TOLERANCE) =~= $x; # OUTPUT: «False␤»
say ($x - $*TOLERANCE) =~= $x; # OUTPUT: «True␤»</pre>
<p>The tolerance is supposed to be modifiable via an adverb:</p>
RT #128210
<pre class="code">my ($x, $y) = 42, 42.1;
say $x =~= $y :tolerance(.1);
</pre>
<p>however, this is not yet implemented. The same effect can be achieved by assigning to $*TOLERANCE.</p>
<pre class="code">{
my $*TOLERANCE = .1;
say 11 =~= 10; # OUTPUT: «True␤»
}</pre>
<p>Note that setting $*TOLERANCE = 0 will cause all comparisons to fail.</p>
<pre class="code">{
my $*TOLERANCE = 0;
say 1 =~= 1; # OUTPUT: «False␤»
}</pre>
<a name="t32.29"></a> <h1 id="_language_operators.pod6-Tight_AND_Precedence">Tight AND Precedence</h1>
<a name="t32.29.1"></a> <h2 id="_language_operators.pod6-infix_&amp;&amp;">infix <span class="code">&amp;&amp;</span></h2>
<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 &quot;never called&quot; };
say a() &amp;&amp; b() &amp;&amp; c(); # OUTPUT: «0␤»</pre>
<a name="t32.30"></a> <h1 id="_language_operators.pod6-Tight_OR_Precedence">Tight OR Precedence</h1>
<a name="t32.30.1"></a> <h2 id="_language_operators.pod6-infix_||">infix <span class="code">||</span></h2>
<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 &quot;never called&quot; };
say a() || b() || c(); # OUTPUT: «1␤»</pre>
<a name="t32.30.2"></a> <h2 id="_language_operators.pod6-infix_^^">infix <span class="code">^^</span></h2>
<p><a id="i409" name=""></a><span class="indexed">Short-circuit exclusive-or</span>. Returns the true argument if there is one (and only one). Returns the last argument if all arguments are false. Returns <span class="code">Nil</span> otherwise (when more than one argument is true).</p>
<p>This operator short-circuits in the sense that it does not evaluate any arguments after a 2nd true result.</p>
<pre class="code">say 0 ^^ 42; # OUTPUT: «42␤»
say '' ^^ 0; # OUTPUT: «0␤»
say 0 ^^ 42 ^^ 1 ^^ die &quot;never called&quot;; # OUTPUT: «␤»</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 &quot;find the one true value&quot; semantics, not &quot;boolean parity&quot; semantics.)</p>
<a name="t32.30.3"></a> <h2 id="_language_operators.pod6-infix_//">infix <span class="code">//</span></h2>
<p><a id="i410" name=""></a><span class="indexed">Defined-or operator</span>. Returns the first defined operand or else the last operand. Short-circuits.</p>
<pre class="code">say Any // 0 // 42; # OUTPUT: «0␤»</pre>
<a name="t32.30.4"></a> <h2 id="_language_operators.pod6-infix_min">infix <span class="code">min</span></h2>
<p>Returns the smallest of the arguments, as determined by <a href="#_routine_cmp.pod6">cmp</a> semantics.</p>
<pre class="code">my $foo = 42;
$foo min= 0 # read as: $foo decreases to 0</pre>
<a name="t32.30.5"></a> <h2 id="_language_operators.pod6-infix_max">infix <span class="code">max</span></h2>
<p>Returns the largest of the arguments, as determined by <a href="#_routine_cmp.pod6">cmp</a> semantics.</p>
<pre class="code">my $foo = -42;
$foo max= 0 # read as: $foo increases to 0</pre>
<a name="t32.30.6"></a> <h2 id="_language_operators.pod6-infix_minmax">infix <span class="code">minmax</span></h2>
<p>Returns the <a href="#_type_Range.pod6">Range</a> starting from the lowest to the highest of the values, as determined by the <a href="#_routine_cmp.pod6">cmp</a> semantics. For instance:</p>
<pre class="code"># numeric comparison
10 minmax 3; # 3..10
# string comparison
'10' minmax '3'; # &quot;10&quot;..&quot;3&quot;
'z' minmax 'k'; # &quot;k&quot;..&quot;z&quot;
</pre>
<p>If the lowest and highest values coincide, the operator returns a <a href="#_type_Range.pod6">Range</a> made by the same value:</p>
<pre class="code">1 minmax 1; # 1..1
</pre>
<p>When applied to <a href="#_type_List.pod6">List</a>s, the operator evaluates the lowest and highest values among all available values:</p>
<pre class="code">(10,20,30) minmax (0,11,22,33); # 0..33
('a','b','z') minmax ('c','d','w'); # &quot;a&quot;..&quot;z&quot;
</pre>
<p>Similarly, when applied to <a href="#_type_Hash.pod6">Hash</a>es, it performs a <a href="#_routine_cmp.pod6">cmp</a> way comparison:</p>
<pre class="code">my %winner = points =&gt; 30, misses =&gt; 10;
my %loser = points =&gt; 20, misses =&gt; 10;
%winner cmp %loser; # More
%winner minmax %loser;
# ${:misses(10), :points(20)}..${:misses(10), :points(30)}
</pre>
<a name="t32.31"></a> <h1 id="_language_operators.pod6-Conditional_Operator_Precedence">Conditional Operator Precedence</h1>
<a name="t32.31.1"></a> <h2 id="_language_operators.pod6-infix_??_!!">infix <span class="code">?? !!</span></h2>
<p><a id="i411" name=""></a><span class="indexed">Ternary operator</span>, <a id="i412" name=""></a><span class="indexed">conditional operator</span>.</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="t32.31.2"></a> <h2 id="_language_operators.pod6-infix_ff">infix <span class="code">ff</span></h2>
<pre class="code">sub infix:&lt;ff&gt;(Mu $a, Mu $b)</pre>
<p><a id="i413" name=""></a><span class="indexed">Flipflop operator</span>.</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 &quot;start&quot; condition, and the right-hand is the &quot;stop&quot; 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>&quot;=begin code&quot; ff &quot;=end code&quot;</b>
}
# this will print four lines, starting with &quot;=begin code&quot; and ending with
# &quot;=end code&quot;
say @codelines.join(&quot;\n&quot;);
</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&gt; {
say $_ if /A/ ff /B/; # OUTPUT: «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 &quot;stop&quot; condition.</p>
<pre class="code">for &lt;A B C D E&gt; {
say $_ if /C/ ff *; # OUTPUT: «C␤D␤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="&lt;span class=&quot;code&quot;&gt;fff&lt;/span&gt;"><span class="code">fff</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.3"></a> <h2 id="_language_operators.pod6-infix_^ff">infix <span class="code">^ff</span></h2>
<pre class="code">sub infix:&lt;^ff&gt;(Mu $a, Mu $b)</pre>
<p>Works like <a href="&lt;span class=&quot;code&quot;&gt;ff&lt;/span&gt;"><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&gt;;
say $_ if /A/ ff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ ^ff /C/ for @list; # OUTPUT: «B␤C␤»</pre>
<p>The sed-like version can be found in <a href="#_routine_^fff.pod6"><span class="code">^fff</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.4"></a> <h2 id="_language_operators.pod6-infix_ff^">infix <span class="code">ff^</span></h2>
<pre class="code">sub infix:&lt;ff^&gt;(Mu $a, Mu $b)</pre>
<p>Works like <a href="&lt;span class=&quot;code&quot;&gt;ff&lt;/span&gt;"><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&gt;;
say $_ if /A/ ff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ ff^ /C/ for @list; # OUTPUT: «A␤B␤»</pre>
<p>The sed-like version can be found in <a href="&lt;span class=&quot;code&quot;&gt;fff^&lt;/span&gt;"><span class="code">fff^</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.5"></a> <h2 id="_language_operators.pod6-infix_^ff^">infix <span class="code">^ff^</span></h2>
<pre class="code">sub infix:&lt;^ff^&gt;(Mu $a, Mu $b)</pre>
<p>Works like <a href="&lt;span class=&quot;code&quot;&gt;ff&lt;/span&gt;"><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&gt;;
say $_ if /A/ ff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ ^ff^ /C/ for @list; # OUTPUT: «B␤»</pre>
<p>The sed-like version can be found in <a href="#_routine_^fff^.pod6"><span class="code">^fff^</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.6"></a> <h2 id="_language_operators.pod6-infix_fff">infix <span class="code">fff</span></h2>
<pre class="code">sub infix:&lt;fff&gt;(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="&lt;span class=&quot;code&quot;&gt;ff&lt;/span&gt;"><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&gt; {
say $_ if /A/ fff /B/; # OUTPUT: «AB␤C␤D␤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="&lt;span class=&quot;code&quot;&gt;ff&lt;/span&gt;"><span class="code">ff</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.7"></a> <h2 id="_language_operators.pod6-infix_^fff">infix <span class="code">^fff</span></h2>
<pre class="code">sub infix:&lt;^fff&gt;(Mu $a, Mu $b)</pre>
<p>Like <a href="&lt;span class=&quot;code&quot;&gt;fff&lt;/span&gt;"><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&gt;;
say $_ if /A/ fff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ ^fff /C/ for @list; # OUTPUT: «B␤C␤»</pre>
<p>For the non-sed version, see <a href="#_routine_^ff.pod6"><span class="code">^ff</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.8"></a> <h2 id="_language_operators.pod6-infix_fff^">infix <span class="code">fff^</span></h2>
<pre class="code">sub infix:&lt;fff^&gt;(Mu $a, Mu $b)</pre>
<p>Like <a href="&lt;span class=&quot;code&quot;&gt;fff&lt;/span&gt;"><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&gt;;
say $_ if /A/ fff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ fff^ /C/ for @list; # OUTPUT: «A␤B␤»</pre>
<p>For the non-sed version, see <a href="&lt;span class=&quot;code&quot;&gt;ff^&lt;/span&gt;"><span class="code">ff^</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.31.9"></a> <h2 id="_language_operators.pod6-infix_^fff^">infix <span class="code">^fff^</span></h2>
<pre class="code">sub infix:&lt;^fff^&gt;(Mu $a, Mu $b)</pre>
<p>Like <a href="&lt;span class=&quot;code&quot;&gt;fff&lt;/span&gt;"><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&gt;;
say $_ if /A/ fff /C/ for @list; # OUTPUT: «A␤B␤C␤»
say $_ if /A/ ^fff^ /C/ for @list; # OUTPUT: «B␤»</pre>
<p>For the non-sed version, see <a href="#_routine_^ff^.pod6"><span class="code">^ff^</span></a>.</p>
<p>This operator cannot be overloaded, as it's handled specially by the compiler.</p>
<a name="t32.32"></a> <h1 id="_language_operators.pod6-Item_Assignment_Precedence">Item Assignment Precedence</h1>
<a name="t32.32.1"></a> <h2 id="_language_operators.pod6-infix_=">infix <span class="code">=</span></h2>
<pre class="code">sub infix:&lt;=&gt;(Mu $a is rw, Mu $b)
</pre>
<p><a id="i414" name=""></a><span class="indexed">Item assignment operator</span>.</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="t32.32.2"></a> <h2 id="_language_operators.pod6-infix_=&gt;">infix <span class="code">=&gt;</span></h2>
<pre class="code">sub infix:«=&gt;»($key, Mu $value --&gt; Pair:D)</pre>
<p><a href="#_type_Pair.pod6">Pair</a> constructor.<a id="i415" name="pair constructor"></a><span class="indexed"></span></p>
<p>Constructs a <a href="#_type_Pair.pod6">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">=&gt; </span> operator is syntactically special-cased, in that it allows unquoted identifier on the left-hand side.</p>
<pre class="code">my $p = a =&gt; 1;
say $p.key; # OUTPUT: «a␤»
say $p.value; # OUTPUT: «1␤»</pre>
<p>A <a href="#_type_Pair.pod6">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.pod6-Pair">the Terms language documentation</a> for more ways to create <span class="code">Pair</span> objects.</p>
<a name="t32.33"></a> <h1 id="_language_operators.pod6-Loose_Unary_Precedence">Loose Unary Precedence</h1>
<a name="t32.33.1"></a> <h2 id="_language_operators.pod6-prefix_not">prefix <span class="code">not</span></h2>
<pre class="code">multi sub prefix:&lt;not&gt;(Mu $x --&gt; Bool:D)</pre>
<p>Evaluates its argument in boolean context (and thus collapses <a href="#_type_Junction.pod6">Junction</a>s), and negates the result. Please note that <span class="code">not</span> is easy to misuse, see <a href="#_language_traps.pod6-Loose_boolean_operators">traps</a>.</p>
<a name="t32.33.2"></a> <h2 id="_language_operators.pod6-prefix_so">prefix <span class="code">so</span></h2>
<pre class="code">multi sub prefix:&lt;so&gt;(Mu $x --&gt; Bool:D)</pre>
<p>Evaluates its argument in boolean context (and thus collapses <a href="#_type_Junction.pod6">Junction</a>s), and returns the result.</p>
<a name="t32.34"></a> <h1 id="_language_operators.pod6-Comma_Operator_Precedence">Comma Operator Precedence</h1>
<a name="t32.34.1"></a> <h2 id="_language_operators.pod6-infix_,">infix <span class="code">,</span></h2>
<pre class="code">sub infix:&lt;,&gt;(*@a --&gt; List:D) is assoc&lt;list&gt;</pre>
<p>Constructs a <a href="#_type_List.pod6">List</a> from its arguments. Also used syntactically as the separator of arguments in calls.</p>
<a name="t32.34.2"></a> <h2 id="_language_operators.pod6-infix_:">infix <span class="code">:</span></h2>
<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's a syntax error.</p>
<a name="t32.35"></a> <h1 id="_language_operators.pod6-List_Infix_Precedence">List Infix Precedence</h1>
<a name="t32.35.1"></a> <h2 id="_language_operators.pod6-infix_Z">infix <span class="code">Z</span></h2>
<pre class="code">sub infix:&lt;Z&gt;(**@lists --&gt; Seq:D) is assoc&lt;chain&gt;</pre>
<p><a id="i416" name=""></a><span class="indexed">Zip operator</span>.</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. The returned <span class="code">Seq</span> contains a nested list with values for all <span class="code">Z</span> operators in a chain.</p>
<pre class="code">say (1, 2 Z &lt;a b c&gt; Z &lt;+ -&gt;).perl; # OUTPUT: «((1, &quot;a&quot;, &quot;+&quot;), (2, &quot;b&quot;, &quot;-&quot;)).Seq␤»
for &lt;a b c&gt; Z &lt;1 2 3&gt; -&gt; [$l, $r] {
say &quot;$l:$r&quot;
}
# OUTPUT: «a:1␤b:2␤c:3␤»</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 operator to the list:</p>
<pre class="code">say 100, 200 Z+ 42, 23; # OUTPUT: «(142 223)␤»
say 1..3 Z~ &lt;a b c&gt; Z~ 'x' xx 3; # OUTPUT: «(1ax 2bx 3cx)␤»</pre>
<a name="t32.35.2"></a> <h2 id="_language_operators.pod6-infix_X">infix <span class="code">X</span></h2>
<pre class="code">sub infix:&lt;X&gt;(**@lists --&gt; List:D)</pre>
<p>Creates a cross product from all the lists, order so that the rightmost elements vary most rapidly:<a id="i417" name="cross product operator"></a><span class="indexed"></span></p>
<pre class="code">1..3 X &lt;a b c&gt; 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 operator to the list:</p>
<pre class="code">1..3 X~ &lt;a b c&gt; X~ 9
# produces (1a9 1b9 1c9 2a9 2b9 2c9 3a9 3b9 3c9)</pre>
<a name="t32.35.3"></a> <h2 id="_language_operators.pod6-infix_...">infix <span class="code">...</span> <a name="418"></a><a name="419"></a><a name="420"></a><a name="421"></a><a name="422"></a></h2>
<pre class="code">multi sub infix:&lt;...&gt;(**@) is assoc&lt;list&gt;
multi sub infix:&lt;...^&gt;(**@) is assoc&lt;list&gt;</pre>
<p>The <a id="i423" name=""></a><span class="indexed">sequence operator</span> 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="#_routine_succ.pod6">succ</a> or <span class="code">*.</span><a href="#_routine_pred.pod6">pred</a>, depending on how the end points compare:</p>
<pre class="code">say 1 ... 4; # OUTPUT: «(1 2 3 4)␤»
say 4 ... 1; # OUTPUT: «(4 3 2 1)␤»
say 'a' ... 'e'; # OUTPUT: «(a b c d e)␤»
say 'e' ... 'a'; # OUTPUT: «(e d c b a)␤»</pre>
<p>An endpoint of <span class="code">*</span> (<a href="#_type_Whatever.pod6">Whatever</a>) generates an infinite sequence, with a default generator of *.succ</p>
<pre class="code">say (1 ... *)[^5]; # OUTPUT: «(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, -&gt; $a, $b { $a + $b } ... *)[^8]; # OUTPUT: «(1 1 2 3 5 8 13 21)␤»
# same but shorter
say (1, 1, *+* ... *)[^8]; # OUTPUT: «(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; # OUTPUT: «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; # OUTPUT: «(2 4 6 8 10 12)␤»
say 1, 2, 4 ... 32; # OUTPUT: «(1 2 4 8 16 32)␤»</pre>
<p>If the endpoint is not <span class="code">*</span>, it's 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's excluded.</p>
<p>This allows you to write</p>
<pre class="code">say 1, 1, *+* ...^ *&gt;= 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 &quot;generated elements&quot; as well, so the are also checked against the endpoint:</p>
<pre class="code">my $end = 4;
say 1, 2, 4, 8, 16 ... $end;
# OUTPUT: «(1 2 4)␤»</pre>
<a name="t32.36"></a> <h1 id="_language_operators.pod6-List_Prefix_Precedence">List Prefix Precedence</h1>
<a name="t32.36.1"></a> <h2 id="_language_operators.pod6-infix_=">infix <span class="code">=</span></h2>
<p><a id="i424" name=""></a><span class="indexed">List assignment operator</span>. Its exact semantics are left to the container type on the left-hand side. See <a href="#_type_Array.pod6">Array</a> and <a href="#_type_Hash.pod6">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="t32.36.2"></a> <h2 id="_language_operators.pod6-infix_:=">infix <span class="code">:=</span></h2>
<p><a id="i425" name=""></a><span class="indexed">Binding operator</span>. 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 = $a;
$b++;
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.pod6-Binding">containers</a> were different.</p>
<pre class="code">my $a = 42;
my $b := $a;
$b++;
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>
<p>Please note that <span class="code">:=</span> is a compile time construct. As such it can not be referred to at runtime and thus can't be used as an argument to meta operators.</p>
<a name="t32.36.3"></a> <h2 id="_language_operators.pod6-infix_::=">infix <span class="code">::=</span></h2>
<p><a id="i426" name=""></a><span class="indexed">Read-only binding operator</span>, not yet implemented in Rakudo. See <a href=":="><span class="code">infix :=</span></a>.</p>
<a name="t32.36.4"></a> <h2 id="_language_operators.pod6-listop_...">listop <span class="code">...</span></h2>
<p><a id="i427" name="stub operator"></a><span class="indexed"></span> The <i>yada, yada, yada</i> operator or <i>stub</i> operator. If it's 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="#_routine_fail.pod6">fail</a>, with the default message <span class="code">stub code executed</span>.</p>
<a name="t32.36.5"></a> <h2 id="_language_operators.pod6-listop_!!!">listop <span class="code">!!!</span></h2>
<p><a id="i428" name=""></a><span class="indexed">Fatal stub operator</span>.</p>
<p>If it's 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="#_routine_die.pod6">die</a>, with the default message <span class="code">stub code executed</span>.</p>
<a name="t32.36.6"></a> <h2 id="_language_operators.pod6-listop_???">listop <span class="code">???</span></h2>
<p><a id="i429" name=""></a><span class="indexed">Admonitory stub operator</span>.</p>
<p>If it's 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="#_routine_warn.pod6">warn</a>, with the default message <span class="code">stub code executed</span>.</p>
<a name="t32.36.7"></a> <h2 id="_language_operators.pod6-Reduction_operators">Reduction operators</h2>
<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">say [+] 1, 2, 3; # 1 + 2 + 3 = 6
my @a = (5, 6);
say [*] @a; # 5 * 6 = 30</pre>
<p>Reduction operators have the same associativity as the operators they are based on.</p>
<pre class="code">say [-] 4, 3, 2; # 4-3-2 = (4-3)-2 = -1
say [**] 4, 3, 2; # 4**3**2 = 4**(3**2) = 262144</pre>
<a name="t32.37"></a> <h1 id="_language_operators.pod6-Loose_AND_precedence">Loose AND precedence</h1>
<a name="t32.37.1"></a> <h2 id="_language_operators.pod6-infix_and">infix <span class="code">and</span></h2>
<p>Same as <a href="#31-infix &amp;amp;&amp;amp;">#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, it short-circuits. Please note that <span class="code">and</span> is easy to misuse, see <a href="#_language_traps.pod6-Loose_boolean_operators">traps</a>.</p>
<a name="t32.37.2"></a> <h2 id="_language_operators.pod6-infix_andthen">infix <span class="code">andthen</span></h2>
<p>Returns <a href="#_type_Slip.pod6-index-entry-Empty-Empty"><span class="code">Empty</span></a> upon encountering the first <a href="#_routine_defined.pod6">undefined</a> argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to <span class="code">$_</span> for the right side, or passed as arguments if the right side is a <a href="#_type_Callable.pod6"><span class="code">Callable</span></a>, whose <a href="#_routine_count.pod6">count</a> must be <span class="code">0</span> or <span class="code">1</span>.</p>
<p>A handy use of this operator is to alias a routine's return value to <span class="code">$_</span> and to do additional manipulation with it, such as printing or returning it to caller. Since the <span class="code">andthen</span> operator short-circuits, statements on the right-hand side won't get executed, unless left-hand side is defined (tip: <a href="#_type_Failure.pod6">Failures</a> are never defined, so you can handle them with this operator).</p>
<pre class="code">sub load-data {
rand &gt; .5 or return; # simulated load data failure; return Nil
(rand &gt; .3 ?? 'error' !! 'good data') xx 10 # our loaded data
}
load-data.first: /good/ andthen say &quot;$_ is good&quot;;
# OUTPUT: «(good data is good)␤»
load-data() andthen .return; # return loaded data, if it's defined
die &quot;Failed to load data!!&quot;;</pre>
<p>The above example will print <span class="code">good data is good</span> only if the subroutine returned any items that match <span class="code">/good/</span> and will die unless loading data returned defined value. The aliasing behaviour lets us pipe the values across the operator.</p>
<p>The <span class="code">andthen</span> operator is a close relative of <a href="#_syntax_with orwith without.pod6"><span class="code">with</span> statement modifier</a>, and some compilers compile <span class="code">with</span> to <span class="code">andthen</span>, meaning these two lines have equivalent behaviour:</p>
<pre class="code">.say with 42;
42 andthen .say;</pre>
<a name="t32.37.3"></a> <h2 id="_language_operators.pod6-infix_notandthen">infix <span class="code">notandthen</span></h2>
<p>Returns <a href="#_type_Slip.pod6-index-entry-Empty-Empty"><span class="code">Empty</span></a> upon encountering the first <a href="#_routine_defined.pod6">defined</a> argument, otherwise the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to <span class="code">$_</span> for the right side, or passed as arguments if the right side is a <a href="#_type_Callable.pod6"><span class="code">Callable</span></a>, whose <a href="#_routine_count.pod6">count</a> must be <span class="code">0</span> or <span class="code">1</span>.</p>
<p>At first glance, <a href="#_routine_notandthen.pod6">notandthen</a> might appear to be the same thing as <a href="#_routine_orelse.pod6">orelse</a> operator. The difference is subtle: <a href="#_routine_notandthen.pod6">notandthen</a> returns <a href="#_type_Slip.pod6-index-entry-Empty-Empty"><span class="code">Empty</span></a> when it encounters a <a href="#_routine_defined.pod6">defined</a> item (that isn't the last item), whereas <a href="#_routine_orelse.pod6">orelse</a> returns that item. In other words, <a href="#_routine_notandthen.pod6">notandthen</a> is a means to act when items aren't defined, whereas <a href="#_routine_orelse.pod6">orelse</a> is a means to obtain the first defined item:</p>
<pre class="code"> sub all-sensors-down { [notandthen] |@_, True }
sub first-working-sensor { [orelse] |@_, 'default sensor' }
all-sensors-down Nil, Nil, Nil
and say 'OMG! All sensors are down!'; # OUTPUT:«OMG! All sensors are down!␤»
say first-working-sensor Nil, Nil, Nil; # OUTPUT:«default sensor␤»
all-sensors-down Nil, 42, Nil
and say 'OMG! All sensors are down!'; # No output
say first-working-sensor Nil, 42, Nil; # OUTPUT:«42␤»
</pre>
<p>The <span class="code">andthen</span> operator is a close relative of <a href="#_syntax_with orwith without.pod6"><span class="code">without</span> statement modifier</a>, and some compilers compile <span class="code">without</span> to <span class="code">notandthen</span>, meaning these two lines have equivalent behaviour:</p>
<pre class="code"> sub good-things { fail }
'boo'.say without good-things;
good-things() notandthen 'boo'.say;
</pre>
<a name="t32.38"></a> <h1 id="_language_operators.pod6-Loose_OR_Precedence">Loose OR Precedence</h1>
<a name="t32.38.1"></a> <h2 id="_language_operators.pod6-infix_or">infix <span class="code">or</span></h2>
<p>Same as <a href="#31-infix || ">infix <span class="code">||</span></a>, 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, it short-circuits. Please note that <span class="code">or</span> is easy to misuse, see <a href="#_language_traps.pod6-Loose_boolean_operators">traps</a>.</p>
<a name="t32.38.2"></a> <h2 id="_language_operators.pod6-infix_orelse">infix <span class="code">orelse</span></h2>
<p>Similar to <span class="code">infix //</span>, except with looser precedence and <span class="code">$_</span> aliasing.</p>
<p>Returns the first defined argument, or else the last argument. Last argument is returned as-is, without being checked for definedness at all. Short-circuits. The result of the left side is bound to <span class="code">$_</span> for the right side, or passed as an argument if the right side is a <a href="#_type_Callable.pod6"><span class="code">Callable</span></a>, whose <a href="#_routine_count.pod6">count</a> must be <span class="code">0</span> or <span class="code">1</span>.</p>
<p>This operator is useful to handle <a href="#_type_Failure.pod6">Failures</a> returned by routines, since more often than not, the expected value would be <a href="#_routine_defined.pod6">defined</a>, while a <a href="#_type_Failure.pod6">Failure</a> never is:</p>
<pre class="code">sub meows { ++$ &lt; 4 ?? fail 'out of meows!' !! '🐱' }
sub meows-processor1 { meows() orelse .return } # return handled Failure
sub meows-processor2 { meows() orelse fail $_ } # return re-armed Failure
sub meows-processor3 {
# Use non-Failure output, or else print a message that stuff's wrong
meows() andthen .say orelse ‘something's wrong’.say;
}
say &quot;{.^name}, {.handled}&quot; # OUTPUT: «Failure, True␤»
given meows-processor1;
say &quot;{.^name}, {.handled}&quot; # OUTPUT: «Failure, False␤»
given meows-processor2;
meows-processor3; # OUTPUT: «something's wrong␤»
meows-processor3; # OUTPUT: «🐱␤»</pre>
<a name="t32.38.3"></a> <h2 id="_language_operators.pod6-infix_xor">infix <span class="code">xor</span></h2>
<p>Same as <a href="#31-infix ^^">infix <span class="code">^^</span></a>, except with looser precedence.</p>
<p>Returns the operand that evaluates to <span class="code">True</span> in boolean context, if and only if the other operand evaluates to <span class="code">False</span> in boolean context. If both operands evaluate to <span class="code">False</span>, returns the last argument. If both operands evaluate to <span class="code">True</span>, returns <span class="code">Nil</span>.</p>
<p>When chaining, returns the operand that evaluates to <span class="code">True</span>, if and only if there is one such operand. If more than one operand is true, it short-circuits after evaluating the second and returns <span class="code">Nil</span>. If all operands are false, returns the last one.</p>
<a name="t32.39"></a> <h1 id="_language_operators.pod6-Sequencer_Precedence">Sequencer Precedence</h1>
<a name="t32.39.1"></a> <h2 id="_language_operators.pod6-infix_==&gt;">infix <span class="code">==&gt;</span></h2>
<p>This <a id="i430" name=""></a><span class="indexed">feed</span> operator takes the result from the left and passes it to the next (right) routine as the last parameter.</p>
<p>The precedence is very loose so you will need to use parentheses to assign the result or you can even just use another feed operator! In the case of routines/methods that take a single argument or where the first argument is a block, it's often required that you call with parentheses (though this is not required for the very last routine/method).</p>
<pre class="code"># Traditional structure, read bottom-to-top
my @result =
sort # (4) Sort, result is &lt;Earth People&gt;
grep { /&lt;[PE]&gt;/ }, # (3) Look for P or E
map { .tc }, # (2) Capitalize the words
&lt;people of earth&gt;; # (1) Start with the input
# Feed (left-to-right) with parentheses, read top-to-bottom
my @result = (
&lt;people of earth&gt; # (1) Start with the input
==&gt; map({ .tc }) # (2) Capitalize the words
==&gt; grep /&lt;[PE]&gt;/ # (3) Look for P or E
==&gt; sort # (4) Sort, result is &lt;Earth People&gt;
);
# For illustration, method chaining equivalent, read top-to-bottom
my @result =
&lt;people of earth&gt; # (1) Start with the input
.map({ .tc }) # (2) Capitalize the words
.grep(/&lt;[PE]&gt;/) # (3) Look for P or E
.sort; # (4) Sort, result is &lt;Earth People&gt;
# To assign without the need of parentheses use another feed operator
my @result;
&lt;people of earth&gt;
==&gt; map({ .tc })
==&gt; grep /&lt;[PE]&gt;/
==&gt; sort()
==&gt; @result;
# It can be useful to capture a partial result, however, unlike
# the leftward feed operator, it does require parentheses or a semicolon
my @result;
&lt;people of earth&gt;
==&gt; map({ .tc })
==&gt; my @caps; @caps # also could wrap in parentheses instead
==&gt; grep /&lt;[PE]&gt;/
==&gt; sort()
==&gt; @result;</pre>
<p>The feed operator lets you construct method-chaining-like patterns out of routines and the results of methods on unrelated data. In method-chaining, you are restricted to the methods available on the data or the result of previous method call. With feed operators, that restriction is gone. The resulting code could also be seen to be more readable than a series of method calls broken over multiple lines.</p>
<p>Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the <b>left</b> operand is enclosable as a closure (that can be cloned and run in a subthread).</p>
<a name="t32.39.2"></a> <h2 id="_language_operators.pod6-infix_&lt;==">infix <span class="code">&lt;==</span></h2>
<p>This <a id="i431" name=""></a><span class="indexed">leftward feed</span> operator takes the result from the right and passes it to the previous (left) routine as the last parameter. This elucidates the right-to-left dataflow for a series of list manipulating functions.</p>
<pre class="code"># Traditional structure, read bottom-to-top
my @result =
sort # (4) Sort, result is &lt;Earth People&gt;
grep { /&lt;[PE]&gt;/ }, # (3) Look for P or E
map { .tc }, # (2) Capitalize the words
&lt;people of earth&gt;; # (1) Start with the input
# Feed (right-to-left) with parentheses, read bottom-to-top
my @result = (
sort() # (4) Sort, result is &lt;Earth People&gt;
&lt;== grep({ /&lt;[PE]&gt;/ }) # (3) Look for P or E
&lt;== map({ .tc }) # (2) Capitalize the words
&lt;== &lt;people of earth&gt; # (1) Start with the input
);
# To assign without parentheses, use another feed operator
my @result
&lt;== sort() # (4) Sort, result is &lt;Earth People&gt;
&lt;== grep({ /&lt;[PE]&gt;/ }) # (3) Look for P or E
&lt;== map({ .tc }) # (2) Capitalize the words
&lt;== &lt;people of earth&gt;; # (1) Start with the input
# It can be useful to capture a partial result
my @result
&lt;== sort()
&lt;== grep({ /&lt;[PE]&gt;/ })
&lt;== my @caps # unlike ==&gt;, there's no need for additional statement
&lt;== map({ .tc })
&lt;== &lt;people of earth&gt;;</pre>
<p>Unlike the rightward feed operator, the result is not closely mappable to method-chaining. However, compared to the traditional structure above where each argument is separated by a line, the resulting code is more demonstrative than commas. The leftward feed operator also allows you to &quot;break into&quot; the statement and capture an intermediary result which can be extremely useful for debugging or to take that result and create another variation on the final result.</p>
<p>Note: In the future, this operator will see some change as it gains the ability to run list operations in parallel. It will enforce that the <b>right</b> operand is enclosable as a closure (that can be cloned and run in a subthread).</p>
</div>
<!-- /language/packages.pod6 --><div class="pod-body"><a id="_language_packages.pod6"></a><a name="t33"></a><h1 class="title">33 Packages</h1> <p class="subtitle">Organizing and referencing namespaced program elements</p> * 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="t33.1"></a> <h1 id="_language_packages.pod6-Names">Names</h1>
<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 punctuation variables
</pre>
<p><a id="i432" name=":: package"></a><span class="indexed"></span> <span class="code">::</span> is used to separate nested package names.</p>
<a name="t33.1.1"></a> <h2 id="_language_packages.pod6-Package-qualified_names">Package-qualified names</h2>
<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&gt;</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="t33.2"></a> <h1 id="_language_packages.pod6-Pseudo-packages">Pseudo-packages</h1>
<p><a id="i433" name="MY (package)"></a><span class="indexed"></span><a id="i434" name="OUR (package)"></a><span class="indexed"></span><a id="i435" name="CORE (package)"></a><span class="indexed"></span><a id="i436" name="GLOBAL (package)"></a><span class="indexed"></span><a id="i437" name="PROCESS (package)"></a><span class="indexed"></span><a id="i438" name="COMPILING(package)"></a><span class="indexed"></span> The following pseudo-package names are reserved at the front of a name:</p>
<table>
<tr><td>MY</td> <td>Symbols in the current lexical scope (aka $?SCOPE)</td></tr>
<tr><td>OUR</td> <td>Symbols in the current package (aka $?PACKAGE)</td></tr>
<tr><td>CORE</td> <td>Outermost lexical scope, definition of standard Perl</td></tr>
<tr><td>GLOBAL</td> <td>Interpreter-wide package symbols, really UNIT::GLOBAL</td></tr>
<tr><td>PROCESS</td> <td>Process-related globals (superglobals). The last place dynamic variable</td></tr>
<tr><td></td> <td>lookup will look.</td></tr>
<tr><td>COMPILING</td> <td>Lexical symbols in the scope being compiled</td></tr>
</table> <p><a id="i439" name="CALLER (package)"></a><span class="indexed"></span><a id="i440" name="CALLERS (package)"></a><span class="indexed"></span><a id="i441" name="DYNAMIC (package)"></a><span class="indexed"></span><a id="i442" name="OUTER (package)"></a><span class="indexed"></span><a id="i443" name="OUTERS (package)"></a><span class="indexed"></span><a id="i444" name="LEXICAL (package)"></a><span class="indexed"></span><a id="i445" name="UNIT (package)"></a><span class="indexed"></span><a id="i446" name="SETTING (package)"></a><span class="indexed"></span><a id="i447" name="PARENT (package)"></a><span class="indexed"></span><a id="i448" name="CLIENT (package)"></a><span class="indexed"></span> The following relative names are also reserved but may be used anywhere in a name:</p>
<table>
<tr><td>CALLER</td> <td>Contextual symbols in the immediate caller's lexical scope</td></tr>
<tr><td>CALLERS</td> <td>Contextual symbols in any caller's lexical scope</td></tr>
<tr><td>DYNAMIC</td> <td>Contextual symbols in my or any caller's lexical scope</td></tr>
<tr><td>OUTER</td> <td>Symbols in the next outer lexical scope</td></tr>
<tr><td>OUTERS</td> <td>Symbols in any outer lexical scope</td></tr>
<tr><td>LEXICAL</td> <td>Contextual symbols in my or any outer's lexical scope</td></tr>
<tr><td>UNIT</td> <td>Symbols in the outermost lexical scope of compilation unit</td></tr>
<tr><td>SETTING</td> <td>Lexical symbols in the unit's DSL (usually CORE)</td></tr>
<tr><td>PARENT</td> <td>Symbols in this package's parent package (or lexical scope)</td></tr>
<tr><td>CLIENT</td> <td>The nearest CALLER that comes from a different package</td></tr>
</table> <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="t33.3"></a> <h1 id="_language_packages.pod6-Looking_up_names">Looking up names</h1>
<a name="t33.3.1"></a> <h2 id="_language_packages.pod6-Interpolating_into_names">Interpolating into names</h2>
<p><a id="i449" name="::()"></a><span class="indexed"></span> 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 parentheses. Most symbolic references are done with this notation:</p>
<pre class="code">$foo = &quot;Bar&quot;;
$foobar = &quot;Foo::Bar&quot;;
$::($foo) # lexically-scoped $Bar
$::(&quot;MY::$foo&quot;) # lexically-scoped $Bar
$::(&quot;OUR::$foo&quot;) # package-scoped $Bar
$::(&quot;GLOBAL::$foo&quot;) # global $Bar
$::(&quot;PROCESS::$foo&quot;)# process $Bar
$::(&quot;PARENT::$foo&quot;) # 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="t33.3.2"></a> <h2 id="_language_packages.pod6-Direct_lookup">Direct lookup</h2>
<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&gt; # Same as $*IN
Foo::&lt;::Bar&gt;&lt;::Baz&gt; # 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&gt;
::&lt;$foo&gt;
</pre>
<p>Each of them scans lexical scopes outward, and then the current package scope (though the package scope is then disallowed when &quot;strict&quot; 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;&gt; </span> form as long as there are no spaces in the name.</p>
<a name="t33.3.3"></a> <h2 id="_language_packages.pod6-Package_lookup">Package lookup</h2>
<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&gt;
</pre>
<a name="t33.3.4"></a> <h2 id="_language_packages.pod6-Class_member_lookup">Class member lookup</h2>
<p>Methods—including auto-generated methods, such as public attributes' accessors—are stored in the class meta object and can be looked up through by the <a href="#_method_lookup.pod6">lookup</a> method.</p>
<pre class="code">Str.^lookup('chars')
</pre>
<a name="t33.4"></a> <h1 id="_language_packages.pod6-Globals">Globals</h1>
<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 &quot;our&quot; 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="t33.5"></a> <h1 id="_language_packages.pod6-Version">Version</h1>
<p><a id="i450" name=".^ver package"></a><span class="indexed"></span> Any package may have a <a href="#_type_Version.pod6">Version</a> object attached to it. This object can be accessed via <span class="code">$?PACKAGE.^ver</span> or from outside the package <span class="code">Fully::Qualified::Name.^ver</span>.</p>
</div>
<!-- /language/performance.pod6 --><div class="pod-body"><a id="_language_performance.pod6"></a><a name="t34"></a><h1 class="title">34 Performance</h1> <p class="subtitle">Measuring and improving run-time or compile-time performance</p> <p>This page is about <a href="https://en.wikipedia.org/wiki/Computer_performance">computer performance</a> in the context of Perl 6.</p>
<a name="t34.1"></a> <h1 id="_language_performance.pod6-First,_profile_your_code">First, profile your code</h1>
<p><b>Make sure you're not wasting time on the wrong code</b>: start by identifying your <a href="https://en.wikiquote.org/wiki/Donald_Knuth">&quot;critical 3%&quot;</a> by &quot;profiling&quot; your code's performance. The rest of this document shows you how to do that.</p>
<a name="t34.1.1"></a> <h2 id="_language_performance.pod6-Time_with_now_-_INIT_now">Time with <span class="code">now - INIT now</span></h2>
<p>Expressions of the form <span class="code">now - INIT now</span>, where <span class="code">INIT</span> is a <a href="#_language_phasers.pod6">phase in the running of a Perl 6 program</a>, provide a great idiom for timing code snippets.</p>
<p>Use the <span class="code">m: your code goes here</span> <a href="#_language_glossary.pod6-camelia">#perl6 channel evalbot</a> to write lines like:</p>
<pre class="code">m: say now - INIT now
rakudo-moar abc1234: OUTPUT«0.0018558␤»
</pre>
<p>The <span class="code">now</span> to the left of <span class="code">INIT</span> runs 0.0018558 seconds <i>later</i> than the <span class="code">now</span> to the right of the <span class="code">INIT</span> because the latter occurs during <a href="#_language_phasers.pod6-INIT">the INIT phase</a>.</p>
<a name="t34.1.2"></a> <h2 id="_language_performance.pod6-Profile_locally">Profile locally</h2>
<p>When using the <a href="http://moarvm.org">MoarVM</a> backend, the <a href="http://rakudo.org">Rakudo</a> compiler's <span class="code">--profile</span> command line option writes the profile data to an HTML file. If the profile data is too big, it could take a long time for a browser to open the file. In that case, output to a file with a <span class="code">.json</span> extension, then open the file with <a href="https://github.com/tadzik/p6profiler-qt">Qt viewer</a>.</p>
<p>To deal with even larger profiles, output to a file with a <span class="code">.sql</span> extension. This will write the profile data as a series of SQL statements, suitable for opening in SQLite.</p>
<pre class="code"># create a profile
perl6 --profile --profile-filename=demo.sql -e 'say (^20).combinations(3).elems'
# create a SQLite database
sqlite3 demo.sqlite
# load the profile data
sqlite&gt; .read demo.sql
# the query below is equivalent to the default view of the &quot;Routines&quot; tab in the HTML profile
sqlite&gt; select
case when r.name = &quot;&quot; then &quot;&lt;anon&gt;&quot; else r.name end as name,
r.file,
r.line,
sum(entries) as entries,
sum(case when rec_depth = 0 then inclusive_time else 0 end) as inclusive_time,
sum(exclusive_time) as exclusive_time
from
calls c,
routines r
where
c.id = r.id
group by
c.id
order by
inclusive_time desc
limit 30;
</pre>
<p>To learn how to interpret the profile info, use the <span class="code">prof-m: your code goes here</span> evalbot (explained above) and ask questions on the channel.</p>
<a name="t34.1.3"></a> <h2 id="_language_performance.pod6-Profile_compiling">Profile compiling</h2>
<p>If you want to profile the time and memory it takes to compile your code, use Rakudo's <span class="code">--profile-compile</span> option.</p>
<a name="t34.1.4"></a> <h2 id="_language_performance.pod6-Create_or_view_benchmarks">Create or view benchmarks</h2>
<p>Use <a href="https://github.com/japhb/perl6-bench">perl6-bench</a>.</p>
<p>If you run perl6-bench for multiple compilers (typically, versions of Perl 5, Perl 6, or NQP), results for each are visually overlaid on the same graphs, to provide for quick and easy comparison.</p>
<a name="t34.1.5"></a> <h2 id="_language_performance.pod6-Share_problems">Share problems</h2>
<p>Once you've used the above techniques to identify the code to improve, you can then begin to address (and share) the problem with others:</p>
<ul><li><p>For each problem, distill it down to a one-liner or the gist and either provide performance numbers or make the snippet small enough that it can be profiled using <span class="code">prof-m: your code or gist URL goes here</span>.</p>
</li></ul> <ul><li><p>Think about the minimum speed increase (or ram reduction or whatever) you need/want, and think about the cost associated with achieving that goal. What's the improvement worth in terms of people's time and energy?</p>
</li></ul> <ul><li><p>Let others know if your Perl 6 use-case is in a production setting or just for fun.</p>
</li></ul> <a name="t34.2"></a> <h1 id="_language_performance.pod6-Solve_problems">Solve problems</h1>
<p>This bears repeating: <b>make sure you're not wasting time on the wrong code</b>. Start by identifying the <a href="https://en.wikiquote.org/wiki/Donald_Knuth">&quot;critical 3%&quot;</a> of your code.</p>
<a name="t34.2.1"></a> <h2 id="_language_performance.pod6-Line_by_line">Line by line</h2>
<p>A quick, fun, productive way to try improve code line-by-line is to collaborate with others using the <a href="#_language_glossary.pod6-IRC">#perl6</a> evalbot <a href="#_language_glossary.pod6-camelia">camelia</a>.</p>
<a name="t34.2.2"></a> <h2 id="_language_performance.pod6-Routine_by_routine">Routine by routine</h2>
<p>With multidispatch, you can drop in new variants of routines &quot;alongside&quot; existing ones:</p>
<pre class="code"># existing code generically matches a two arg foo call:
multi sub foo(Any $a, Any $b) { ... }
# new variant takes over for a foo(&quot;quux&quot;, 42) call:
multi sub foo(&quot;quux&quot;, Int $b) { ... }</pre>
<p>The call overhead of having multiple <span class="code">foo</span> definitions is generally insignificant (though see discussion of <span class="code">where</span> below), so if your new definition handles its particular case more efficiently than the previously existing set of definitions, then you probably just made your code that much more efficient for that case.</p>
<a name="t34.2.3"></a> <h2 id="_language_performance.pod6-Speed_up_type-checks_and_call_resolution">Speed up type-checks and call resolution</h2>
<p>Most <a href="#_type_Signature.pod6-Type_Constraints"><span class="code">where</span> clauses</a> – and thus most <a href="https://design.perl6.org/S12.html#Types_and_Subtypes">subsets</a> – force dynamic (run-time) type checking and call resolution for any call it <i>might</i> match. This is slower, or at least later, than compile-time.</p>
<p>Method calls are generally resolved as late as possible (dynamically at run-time), whereas sub calls are generally resolved statically at compile-time.</p>
<a name="t34.2.4"></a> <h2 id="_language_performance.pod6-Choose_better_algorithms">Choose better algorithms</h2>
<p>One of the most reliable techniques for making large performance improvements, regardless of language or compiler, is to pick a more appropriate algorithm.</p>
<p>A classic example is <a href="https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm">Boyer-Moore</a>. To match a small string in a large string, one obvious way to do it is to compare the first character of the two strings and then, if they match, compare the second characters, or, if they don't match, compare the first character of the small string with the second character in the large string, and so on. In contrast, the Boyer-Moore algorithm starts by comparing the *last* character of the small string with the correspondingly positioned character in the large string. For most strings, the Boyer-Moore algorithm is close to N times faster algorithmically, where N is the length of the small string.</p>
<p>The next couple sections discuss two broad categories for algorithmic improvement that are especially easy to accomplish in Perl 6. For more on this general topic, read the wikipedia page on <a href="https://en.wikipedia.org/wiki/Algorithmic_efficiency">algorithmic efficiency</a>, especially the 'See also' section near the end.</p>
<a name="t34.2.4.1"></a> <h3 id="_language_performance.pod6-Change_sequential/blocking_code_to_parallel/non-blocking">Change sequential/blocking code to parallel/non-blocking</h3>
<p>This is another very important class of algorithmic improvement.</p>
<p>See the slides for <a href="http://jnthn.net/papers/2015-yapcasia-concurrency.pdf#page=17">Parallelism, Concurrency, and Asynchrony in Perl 6</a> and/or <a href="https://www.youtube.com/watch?v=JpqnNCx7wVY&amp;list=PLRuESFRW2Fa77XObvk7-BYVFwobZHdXdK&amp;index=8">the matching video</a>.</p>
<a name="t34.2.5"></a> <h2 id="_language_performance.pod6-Use_existing_high_performance_code">Use existing high performance code</h2>
<p>There are plenty of high performance C libraries that you can use within Perl 6 and <a href="#_language_nativecall.pod6">NativeCall</a> makes it easy to create wrappers for them. There's experimental support for C++ libraries, too.</p>
<p>If you want to <a href="http://stackoverflow.com/a/27206428/1077672">use Perl 5 modules in Perl 6</a>, mix in Perl 6 types and the <a href="#_language_mop.pod6">Meta-Object Protocol</a>.</p>
<p>More generally, Perl 6 is designed to smoothly interoperate with other languages and there are a number of <a href="https://modules.perl6.org/#q=inline">modules aimed at facilitating the use of libs from other langs</a>.</p>
<a name="t34.2.6"></a> <h2 id="_language_performance.pod6-Make_the_Rakudo_compiler_generate_faster_code">Make the Rakudo compiler generate faster code</h2>
<p>To date, the focus for the compiler has been correctness, not how fast it generates code or how fast or lean the code it generates runs. But that's expected to change, eventually... You can talk to compiler devs on the freenode IRC channels #perl6 and #moarvm about what to expect. Better still, you can contribute yourself:</p>
<ul><li><p>Rakudo is largely written in Perl 6. So if you can write Perl 6, then you can hack on the compiler, including optimizing any of the large body of existing high-level code that impacts the speed of your code (and everyone else's).</p>
</li></ul> <ul><li><p>Most of the rest of the compiler is written in a small language called <a href="https://github.com/perl6/nqp">NQP</a> that's basically a subset of Perl 6. If you can write Perl 6, you can fairly easily learn to use and improve the mid-level NQP code too, at least from a pure language point of view. To dig into NQP and Rakudo's guts, start with <a href="http://edumentab.github.io/rakudo-and-nqp-internals-course/">NQP and internals course</a>.</p>
</li></ul> <ul><li><p>If low-level C hacking is your idea of fun, checkout <a href="http://moarvm.org">MoarVM</a> and visit the freenode IRC channel #moarvm (<a href="https://irclog.perlgeek.de/moarvm/">logs</a>).</p>
</li></ul> <a name="t34.2.7"></a> <h2 id="_language_performance.pod6-Still_need_more_ideas?">Still need more ideas?</h2>
<p>Some known current Rakudo performance weaknesses not yet covered in this page include the use of gather/take, junctions, regexes and string handling in general.</p>
<p>If you think some topic needs more coverage on this page, please submit a PR or tell someone your idea. Thanks. :)</p>
<a name="t34.3"></a> <h1 id="_language_performance.pod6-Not_getting_the_results_you_need/want?">Not getting the results you need/want?</h1>
<p>If you've tried everything on this page to no avail, please consider discussing things with a compiler dev on #perl6, so we can learn from your use-case and what you've found out about it so far.</p>
<p>Once a dev knows of your plight, allow enough time for an informed response (a few days or weeks, depending on the exact nature of your problem and potential solutions).</p>
<p>If <i>that</i> hasn't worked out, please consider filing an issue about your experience at <a href="https://github.com/perl6/user-experience/issues">our user experience repo</a> before moving on.</p>
<p>Thanks. :)</p>
</div>
<!-- /language/phasers.pod6 --><div class="pod-body"><a id="_language_phasers.pod6"></a><a name="t35"></a><h1 class="title">35 Phasers</h1> <p class="subtitle">Program execution phases and corresponding phaser blocks</p> <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="t35.1"></a> <h1 id="_language_phasers.pod6-Phasers">Phasers</h1>
<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
INIT {...} # * at run time, ASAP, only ever runs once
END {...} # at run time, ALAP, only ever runs once
ENTER {...} # * at every block entry time, repeats on loop blocks.
LEAVE {...} # at every block exit time (even stack unwinds from exceptions)
KEEP {...} # at every successful block exit, part of LEAVE queue
UNDO {...} # at every unsuccessful block exit, part of LEAVE queue
FIRST {...} # at loop initialization time, before any ENTER
NEXT {...} # at loop continuation time, before any LEAVE
LAST {...} # at loop termination time, after any LEAVE
PRE {...} # assert precondition at every block entry, before ENTER
POST {...} # assert postcondition at every block exit, after LEAVE
CATCH {...} # catch exceptions, before LEAVE
CONTROL {...} # catch control exceptions, before LEAVE
LAST {...} # supply tapped by whenever-block is done, runs very last
QUIT {...} # catch async exceptions within a whenever-block, runs very last
COMPOSE {...} # when a role is composed into a class
CLOSE {...} # appears in a supply block, called when the supply is closed
</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 $random = ENTER { rand };</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 $random = ENTER rand;</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 &quot;trapping&quot; 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 $random = rand;</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 &quot;my&quot; 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><a id="i451" name="Phasers will trait"></a><span class="indexed"></span> 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;$_&gt; </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="t35.1.1"></a> <h2 id="_language_phasers.pod6-Execution_Order">Execution Order</h2>
<p>Compilation Begins</p>
<pre class="code"> BEGIN {...} # at compile time, ASAP, only ever runs once
CHECK {...} # at compile time, ALAP, only ever runs once
COMPOSE {...} # when a role is composed into a class
</pre>
<p>Execution Begins</p>
<pre class="code"> INIT {...} # at run time, ASAP, only ever runs once
</pre>
<p>Before block execution begins</p>
<pre class="code"> PRE {...} # assert precondition at every block entry, before ENTER
</pre>
<p>Loop execution begins</p>
<pre class="code"> FIRST {...} # at loop initialization time, before any ENTER
</pre>
<p>Block execution begins</p>
<pre class="code"> ENTER {...} # at every block entry time, repeats on loop blocks.
</pre>
<p>Exception maybe happens</p>
<pre class="code"> CATCH {...} # catch exceptions, before LEAVE
CONTROL {...} # catch control exceptions, before LEAVE
</pre>
<p>End of loop, either continuing or finished</p>
<pre class="code"> NEXT {...} # at loop continuation time, before any LEAVE
LAST {...} # at loop termination time, after any LEAVE
</pre>
<p>End of block</p>
<pre class="code"> 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
</pre>
<p>Postcondition for block</p>
<pre class="code"> POST {...} # assert postcondition at every block exit, after LEAVE
</pre>
<p>Async whenever-block is complete</p>
<pre class="code"> LAST {...} # if ended normally with done, runs once after block
QUIT {...} # catch async exceptions
</pre>
<p>Program terminating</p>
<pre class="code"> END {...} # at run time, ALAP, only ever runs once
</pre>
<a name="t35.2"></a> <h1 id="_language_phasers.pod6-Program_Execution_Phasers">Program Execution Phasers</h1>
<a name="t35.2.1"></a> <h2 id="_language_phasers.pod6-BEGIN"><a name="452"></a>BEGIN</h2>
<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="t35.2.2"></a> <h2 id="_language_phasers.pod6-CHECK"><a name="453"></a>CHECK</h2>
<p>Runs at compile time, As late 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="t35.2.3"></a> <h2 id="_language_phasers.pod6-INIT"><a name="454"></a>INIT</h2>
<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="t35.2.4"></a> <h2 id="_language_phasers.pod6-END"><a name="455"></a>END</h2>
<p>Runs after compilation during main execution, as late 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="t35.2.5"></a> <h2 id="_language_phasers.pod6-CLOSE"><a name="456"></a>CLOSE</h2>
<p>Appears in a supply block. Called when the supply is closed.</p>
<a name="t35.3"></a> <h1 id="_language_phasers.pod6-Block_Phasers">Block Phasers</h1>
<p>Execution in the context of a block has its 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. 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="t35.3.1"></a> <h2 id="_language_phasers.pod6-ENTER"><a name="457"></a>ENTER</h2>
<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="t35.3.2"></a> <h2 id="_language_phasers.pod6-LEAVE"><a name="458"></a>LEAVE</h2>
<p>Runs at every block exit time (even stack unwinds from exceptions), except when the program exits abruptly (e.g. with <a href="#_routine_exit.pod6"><span class="code">exit</span></a>).</p>
<p><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>
<pre class="code">sub answer() {
LEAVE say „I say after the return value.“;
42 # this is the return value
}</pre>
<p><b>Note:</b> be mindful of <span class="code">LEAVE</span> phasers directly in blocks of routines, as they will get executed even when an attempt to call the routine with wrong arguments is made:</p>
<pre class="code">sub foo (Int) {
say &quot;Hello!&quot;;
LEAVE say &quot;oh noes!&quot;
}
try foo rand; # OUTPUT: «oh noes!␤»</pre>
<p>Although the subroutine's body did not get run, because the sub expects an <a href="#_type_Int.pod6">Int</a> and <a href="#_routine_rand.pod6"><span class="code">rand</span></a> returned a <a href="#_type_Num.pod6">Num</a>, its block was entered and left (when param binding failed), and so the <span class="code">LEAVE</span> phaser <i>was</i> run.</p>
<a name="t35.3.3"></a> <h2 id="_language_phasers.pod6-KEEP"><a name="459"></a>KEEP</h2>
<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="t35.3.4"></a> <h2 id="_language_phasers.pod6-UNDO"><a name="460"></a>UNDO</h2>
<p>Runs at every unsuccessful block exit, as part of the LEAVE queue (shares the same order of execution).</p>
<a name="t35.3.5"></a> <h2 id="_language_phasers.pod6-PRE"><a name="461"></a>PRE</h2>
<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="t35.3.6"></a> <h2 id="_language_phasers.pod6-POST"><a name="462"></a>POST</h2>
<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="t35.4"></a> <h1 id="_language_phasers.pod6-Loop_Phasers">Loop Phasers</h1>
<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="t35.4.1"></a> <h2 id="_language_phasers.pod6-FIRST"><a name="463"></a>FIRST</h2>
<p>Runs at loop initialization, before ENTER.</p>
<a name="t35.4.2"></a> <h2 id="_language_phasers.pod6-NEXT"><a name="464"></a>NEXT</h2>
<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="t35.4.3"></a> <h2 id="_language_phasers.pod6-LAST"><a name="465"></a>LAST</h2>
<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="t35.5"></a> <h1 id="_language_phasers.pod6-Exception_Handling_Phasers">Exception Handling Phasers</h1>
<a name="t35.5.1"></a> <h2 id="_language_phasers.pod6-CATCH"><a name="466"></a>CATCH</h2>
<p>Runs when an exception is raised by the current block, before the LEAVE phase.</p>
<a name="t35.5.2"></a> <h2 id="_language_phasers.pod6-CONTROL"><a name="467"></a>CONTROL</h2>
<p>Runs when a control exception is raised by the current block, before the LEAVE phase. It is raised by <span class="code">return</span>, <span class="code">fail</span>, <span class="code">redo</span>, <span class="code">next</span>, <span class="code">last</span>, <span class="code">take</span>, <span class="code">warn</span>, <span class="code">proceed</span> and <span class="code">succeed</span>.</p>
# NYI
# =head1 Object Phasers
#
# =head2 X&lt;COMPOSE|Phasers, COMPOSE&gt;
#
# Runs when a role is composed into a class.
<a name="t35.6"></a> <h1 id="_language_phasers.pod6-Asynchronous_Phasers">Asynchronous Phasers</h1>
<a name="t35.6.1"></a> <h2 id="_language_phasers.pod6-LAST"><a name="468"></a>LAST</h2>
<p>Runs when a <a href="#_type_Supply.pod6">Supply</a> finishes with a call to <span class="code">done</span> or when a <span class="code">supply</span> block exits normally. It runs completely after the <span class="code">whenever</span> block it is placed within finishes.</p>
<p>This phaser reuses the name <span class="code">LAST</span>, but works differently from the <span class="code">LAST</span> loop phaser. This phaser is similar to setting the <span class="code">done</span> routine while tapping a supply with <span class="code">tap</span>.</p>
<a name="t35.6.2"></a> <h2 id="_language_phasers.pod6-QUIT"><a name="469"></a>QUIT</h2>
<p>Runs when a <a href="#_type_Supply.pod6">Supply</a> terminates early with an exception. It runs after the <span class="code">whenever</span> block it is placed within finishes.</p>
<p>This phaser is similar to setting the <span class="code">quit</span> routine while tapping a Supply with <span class="code">tap</span>.</p>
<a name="t35.7"></a> <h1 id="_language_phasers.pod6-DOC_phasers">DOC phasers</h1>
<a name="t35.7.1"></a> <h2 id="_language_phasers.pod6-DOC"><a name="470"></a>DOC</h2>
<p>The phasers <span class="code">BEGIN</span>, <span class="code">CHECK</span> and <span class="code">INIT</span> are run only in documentation mode when prefixed with the <span class="code">DOC</span> keyword. The compiler is in documentation when run with <span class="code">--doc</span>.</p>
<pre class="code">DOC INIT { say 'init' } # prints 'init' at initialization time when in documentation mode.</pre>
</div>
<!-- /language/pod.pod6 --><div class="pod-body"><a id="_language_pod.pod6"></a><a name="t36"></a><h1 class="title">36 Perl 6 Pod</h1> <p class="subtitle">An easy-to-use markup language</p> <p>Pod is an easy-to-use markup language. Pod can be used for writing language documentation, for documenting programs and modules, as well as for other types of document composition.</p>
<p>Every Pod document has to
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment